repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
333fred/allwpilib
simulation/SimDS/src/main/java/edu/wpi/first/wpilibj/simulation/ds/SimJoystick.java
2168
/*----------------------------------------------------------------------------*/ /* Copyright (c) FIRST 2016-2017. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.simulation.ds; import gazebo.msgs.GzJoystick.Joystick; import java.util.ArrayList; import java.util.List; import org.gazebosim.transport.Node; import org.gazebosim.transport.Publisher; import net.java.games.input.Component; import net.java.games.input.Controller; public class SimJoystick implements ISimJoystick { private Controller controller; private List<Component> axes, buttons; private Publisher<Joystick> pub = null; private int prevI = -1; private Node prevNode = null; public SimJoystick(Controller controller) { this.controller = controller; axes = new ArrayList<>(); buttons = new ArrayList<>(); for(Component c : controller.getComponents()) { if (c.getIdentifier() instanceof Component.Identifier.Axis) { axes.add(c); } else if (c.getIdentifier() instanceof Component.Identifier.Button) { buttons.add(c); } } } @Override public String getName() { return controller.getName(); } @Override public String toString() { return getName(); } @Override public void advertise(Node node, int i) { if (pub == null) { // I'm good } else if (prevI != i || prevNode != node) { // TODO: pub.close(); } else { return; // No change } pub = node.advertise("ds/joysticks/"+i, Joystick.getDefaultInstance()); prevNode = node; prevI = i; } @Override public void publish() { controller.poll(); Joystick.Builder builder = Joystick.newBuilder(); for (Component a : axes) { builder.addAxes(a.getPollData()); } for (Component b : buttons) { builder.addButtons(b.getPollData() > 0.5); } pub.publish(builder.build()); } }
bsd-3-clause
ngs-doo/dsl-client-java
core/src/test/java-generated/com/dslplatform/ocd/javaasserts/DecimalAsserts.java
37145
package com.dslplatform.ocd.javaasserts; import org.junit.Assert; public class DecimalAsserts { static void assertSingleEquals(final String message, final java.math.BigDecimal expected, final java.math.BigDecimal actual) { if (expected == actual || expected.compareTo(actual) == 0) return; Assert.fail(message + "expected was \"" + expected + "\", but actual was \"" + actual + "\""); } static void assertOneEquals(final String message, final java.math.BigDecimal expected, final java.math.BigDecimal actual) { if (expected == null) Assert.fail(message + "expected was <null> - WARNING: This is a preconditions failure in expected, this assertion will never succeed!"); if (expected == actual) return; if (actual == null) Assert.fail(message + "expected was \"" + expected + "\", but actual was <null>"); assertSingleEquals(message, expected, actual); } public static void assertOneEquals(final java.math.BigDecimal expected, final java.math.BigDecimal actual) { assertOneEquals("OneDecimal mismatch: ", expected, actual); } private static void assertNullableEquals(final String message, final java.math.BigDecimal expected, final java.math.BigDecimal actual) { if (expected == actual) return; if (expected == null) Assert.fail(message + "expected was <null>, but actual was \"" + actual + "\""); if (actual == null) Assert.fail(message + "expected was \"" + expected + "\", but actual was <null>"); assertSingleEquals(message, expected, actual); } public static void assertNullableEquals(final java.math.BigDecimal expected, final java.math.BigDecimal actual) { assertNullableEquals("NullableDecimal mismatch: ", expected, actual); } private static void assertArrayOfOneEquals(final String message, final java.math.BigDecimal[] expecteds, final java.math.BigDecimal[] actuals) { if (expecteds.length != actuals.length) { Assert.fail(message + "expecteds was an array of length " + expecteds.length + ", but actuals was an array of length " + actuals.length); } for (int i = 0; i < expecteds.length; i++) { assertOneEquals(message + "element mismatch occurred at index " + i + ": ", expecteds[i], actuals[i]); } } private static void assertOneArrayOfOneEquals(final String message, final java.math.BigDecimal[] expecteds, final java.math.BigDecimal[] actuals) { if (expecteds == null) Assert.fail(message + "expecteds was <null> - WARNING: This is a preconditions failure in expecteds, this assertion will never succeed!"); for (int i = 0; i < expecteds.length; i ++) { if (expecteds[i] == null) { Assert.fail(message + "expecteds contained a <null> element at index " + i + " - WARNING: This is a preconditions failure in expecteds, this assertion will never succeed!"); } } if (expecteds == actuals) return; if (actuals == null) Assert.fail(message + "expecteds was an array of length " + expecteds.length + ", but actuals was <null>"); assertArrayOfOneEquals(message, expecteds, actuals); } public static void assertOneArrayOfOneEquals(final java.math.BigDecimal[] expecteds, final java.math.BigDecimal[] actuals) { assertOneArrayOfOneEquals("OneArrayOfOneDecimal mismatch: ", expecteds, actuals); } private static void assertNullableArrayOfOneEquals(final String message, final java.math.BigDecimal[] expecteds, final java.math.BigDecimal[] actuals) { if (expecteds == actuals) return; if (expecteds == null) Assert.fail(message + "expecteds was <null>, but actuals was an array of length " + actuals.length); if (actuals == null) Assert.fail(message + " expecteds was an array of length " + expecteds.length + ", but actuals was <null>"); assertArrayOfOneEquals(message, expecteds, actuals); } public static void assertNullableArrayOfOneEquals(final java.math.BigDecimal[] expecteds, final java.math.BigDecimal[] actuals) { assertNullableArrayOfOneEquals("NullableArrayOfOneDecimal mismatch: ", expecteds, actuals); } private static void assertArrayOfNullableEquals(final String message, final java.math.BigDecimal[] expecteds, final java.math.BigDecimal[] actuals) { if (expecteds.length != actuals.length) { Assert.fail(message + "expecteds was an array of length " + expecteds.length + ", but actuals was an array of length " + actuals.length); } for (int i = 0; i < expecteds.length; i++) { assertNullableEquals(message + "element mismatch occurred at index " + i + ": ", expecteds[i], actuals[i]); } } private static void assertOneArrayOfNullableEquals(final String message, final java.math.BigDecimal[] expecteds, final java.math.BigDecimal[] actuals) { if (expecteds == null) Assert.fail(message + "expecteds was <null> - WARNING: This is a preconditions failure in expecteds, this assertion will never succeed!"); if (expecteds == actuals) return; if (actuals == null) Assert.fail(message + "expecteds was an array of length " + expecteds.length + ", but actuals was <null>"); assertArrayOfNullableEquals(message, expecteds, actuals); } public static void assertOneArrayOfNullableEquals(final java.math.BigDecimal[] expecteds, final java.math.BigDecimal[] actuals) { assertOneArrayOfNullableEquals("OneArrayOfNullableDecimal mismatch: ", expecteds, actuals); } private static void assertNullableArrayOfNullableEquals(final String message, final java.math.BigDecimal[] expecteds, final java.math.BigDecimal[] actuals) { if (expecteds == actuals) return; if (expecteds == null) Assert.fail(message + "expecteds was <null>, but actuals was an array of length " + actuals.length); if (actuals == null) Assert.fail(message + " expecteds was an array of length " + expecteds.length + ", but actuals was <null>"); assertArrayOfNullableEquals(message, expecteds, actuals); } public static void assertNullableArrayOfNullableEquals(final java.math.BigDecimal[] expecteds, final java.math.BigDecimal[] actuals) { assertNullableArrayOfNullableEquals("NullableArrayOfNullableDecimal mismatch: ", expecteds, actuals); } private static void assertListOfOneEquals(final String message, final java.util.List<java.math.BigDecimal> expecteds, final java.util.List<java.math.BigDecimal> actuals) { final int expectedsSize = expecteds.size(); final int actualsSize = actuals.size(); if (expectedsSize != actualsSize) { Assert.fail(message + "expecteds was a list of size " + expectedsSize + ", but actuals was a list of size " + actualsSize); } final java.util.Iterator<java.math.BigDecimal> expectedsIterator = expecteds.iterator(); final java.util.Iterator<java.math.BigDecimal> actualsIterator = actuals.iterator(); for (int i = 0; i < expectedsSize; i++) { final java.math.BigDecimal expected = expectedsIterator.next(); final java.math.BigDecimal actual = actualsIterator.next(); assertOneEquals(message + "element mismatch occurred at index " + i + ": ", expected, actual); } } private static void assertOneListOfOneEquals(final String message, final java.util.List<java.math.BigDecimal> expecteds, final java.util.List<java.math.BigDecimal> actuals) { int i = 0; for (final java.math.BigDecimal expected : expecteds) { if (expected == null) { Assert.fail(message + "element mismatch occurred at index " + i + ": expected was <null> - WARNING: This is a preconditions failure in expected, this assertion will never succeed!"); } i++; } if (expecteds == actuals) return; if (actuals == null) Assert.fail(message + "expecteds was a list of size " + expecteds.size() + ", but actuals was <null>"); assertListOfOneEquals(message, expecteds, actuals); } public static void assertOneListOfOneEquals(final java.util.List<java.math.BigDecimal> expecteds, final java.util.List<java.math.BigDecimal> actuals) { assertOneListOfOneEquals("OneListOfOneDecimal mismatch: ", expecteds, actuals); } private static void assertNullableListOfOneEquals(final String message, final java.util.List<java.math.BigDecimal> expecteds, final java.util.List<java.math.BigDecimal> actuals) { if (expecteds == actuals) return; if (expecteds == null) Assert.fail(message + "expecteds was <null>, but actuals was a list of size " + actuals.size()); if (actuals == null) Assert.fail(message + " expecteds was a list of size " + expecteds.size() + ", but actuals was <null>"); assertListOfOneEquals(message, expecteds, actuals); } public static void assertNullableListOfOneEquals(final java.util.List<java.math.BigDecimal> expecteds, final java.util.List<java.math.BigDecimal> actuals) { assertNullableListOfOneEquals("NullableListOfOneDecimal mismatch: ", expecteds, actuals); } private static void assertListOfNullableEquals(final String message, final java.util.List<java.math.BigDecimal> expecteds, final java.util.List<java.math.BigDecimal> actuals) { final int expectedsSize = expecteds.size(); final int actualsSize = actuals.size(); if (expectedsSize != actualsSize) { Assert.fail(message + "expecteds was a list of size " + expectedsSize + ", but actuals was a list of size " + actualsSize); } final java.util.Iterator<java.math.BigDecimal> expectedsIterator = expecteds.iterator(); final java.util.Iterator<java.math.BigDecimal> actualsIterator = actuals.iterator(); for (int i = 0; i < expectedsSize; i++) { final java.math.BigDecimal expected = expectedsIterator.next(); final java.math.BigDecimal actual = actualsIterator.next(); assertNullableEquals(message + "element mismatch occurred at index " + i + ": ", expected, actual); } } private static void assertOneListOfNullableEquals(final String message, final java.util.List<java.math.BigDecimal> expecteds, final java.util.List<java.math.BigDecimal> actuals) { if (expecteds == null) Assert.fail(message + "expecteds was <null> - WARNING: This is a preconditions failure in expecteds, this assertion will never succeed!"); if (expecteds == actuals) return; if (actuals == null) Assert.fail(message + "expecteds was a list of size " + expecteds.size() + ", but actuals was <null>"); assertListOfNullableEquals(message, expecteds, actuals); } public static void assertOneListOfNullableEquals(final java.util.List<java.math.BigDecimal> expecteds, final java.util.List<java.math.BigDecimal> actuals) { assertOneListOfNullableEquals("OneListOfNullableDecimal mismatch: ", expecteds, actuals); } private static void assertNullableListOfNullableEquals(final String message, final java.util.List<java.math.BigDecimal> expecteds, final java.util.List<java.math.BigDecimal> actuals) { if (expecteds == actuals) return; if (expecteds == null) Assert.fail(message + "expecteds was <null>, but actuals was a list of size " + actuals.size()); if (actuals == null) Assert.fail(message + " expecteds was a list of size " + expecteds.size() + ", but actuals was <null>"); assertListOfNullableEquals(message, expecteds, actuals); } public static void assertNullableListOfNullableEquals(final java.util.List<java.math.BigDecimal> expecteds, final java.util.List<java.math.BigDecimal> actuals) { assertNullableListOfNullableEquals("NullableListOfNullableDecimal mismatch: ", expecteds, actuals); } private static void assertSetOfOneEquals(final String message, final java.util.Set<java.math.BigDecimal> expecteds, final java.util.Set<java.math.BigDecimal> actuals) { if (actuals.contains(null)) { Assert.fail(message + "actuals contained a <null> element"); } final int expectedsSize = expecteds.size(); final int actualsSize = actuals.size(); if (expectedsSize != actualsSize) { Assert.fail(message + "expecteds was a set of size " + expectedsSize + ", but actuals was a set of size " + actualsSize); } expectedsLoop: for (final java.math.BigDecimal expected : expecteds) { if (actuals.contains(expected)) continue; for (final java.math.BigDecimal actual : actuals) { try { assertOneEquals(expected, actual); continue expectedsLoop; } catch (final AssertionError e) {} } Assert.fail(message + "actuals did not contain the expecteds element \"" + expected + "\""); } } private static void assertOneSetOfOneEquals(final String message, final java.util.Set<java.math.BigDecimal> expecteds, final java.util.Set<java.math.BigDecimal> actuals) { if (expecteds.contains(null)) { Assert.fail(message + "expecteds contained a <null> element - WARNING: This is a preconditions failure in expected, this assertion will never succeed!"); } if (expecteds == actuals) return; if (actuals == null) Assert.fail(message + "expecteds was a set of size " + expecteds.size() + ", but actuals was <null>"); assertSetOfOneEquals(message, expecteds, actuals); } public static void assertOneSetOfOneEquals(final java.util.Set<java.math.BigDecimal> expecteds, final java.util.Set<java.math.BigDecimal> actuals) { assertOneSetOfOneEquals("OneSetOfOneDecimal mismatch: ", expecteds, actuals); } private static void assertNullableSetOfOneEquals(final String message, final java.util.Set<java.math.BigDecimal> expecteds, final java.util.Set<java.math.BigDecimal> actuals) { if (expecteds == actuals) return; if (expecteds == null) Assert.fail(message + "expecteds was <null>, but actuals was a set of size " + actuals.size()); if (actuals == null) Assert.fail(message + " expecteds was a set of size " + expecteds.size() + ", but actuals was <null>"); assertSetOfOneEquals(message, expecteds, actuals); } public static void assertNullableSetOfOneEquals(final java.util.Set<java.math.BigDecimal> expecteds, final java.util.Set<java.math.BigDecimal> actuals) { assertNullableSetOfOneEquals("NullableSetOfOneDecimal mismatch: ", expecteds, actuals); } private static void assertSetOfNullableEquals(final String message, final java.util.Set<java.math.BigDecimal> expecteds, final java.util.Set<java.math.BigDecimal> actuals) { final int expectedsSize = expecteds.size(); final int actualsSize = actuals.size(); if (expectedsSize != actualsSize) { Assert.fail(message + "expecteds was a set of size " + expectedsSize + ", but actuals was a set of size " + actualsSize); } expectedsLoop: for (final java.math.BigDecimal expected : expecteds) { if (actuals.contains(expected)) continue; for (final java.math.BigDecimal actual : actuals) { try { assertNullableEquals(expected, actual); continue expectedsLoop; } catch (final AssertionError e) {} } Assert.fail(message + "actuals did not contain the expecteds element \"" + expected + "\""); } } private static void assertOneSetOfNullableEquals(final String message, final java.util.Set<java.math.BigDecimal> expecteds, final java.util.Set<java.math.BigDecimal> actuals) { if (expecteds == null) Assert.fail(message + "expecteds was <null> - WARNING: This is a preconditions failure in expecteds, this assertion will never succeed!"); if (expecteds == actuals) return; if (actuals == null) Assert.fail(message + "expecteds was a set of size " + expecteds.size() + ", but actuals was <null>"); assertSetOfNullableEquals(message, expecteds, actuals); } public static void assertOneSetOfNullableEquals(final java.util.Set<java.math.BigDecimal> expecteds, final java.util.Set<java.math.BigDecimal> actuals) { assertOneSetOfNullableEquals("OneSetOfNullableDecimal mismatch: ", expecteds, actuals); } private static void assertNullableSetOfNullableEquals(final String message, final java.util.Set<java.math.BigDecimal> expecteds, final java.util.Set<java.math.BigDecimal> actuals) { if (expecteds == actuals) return; if (expecteds == null) Assert.fail(message + "expecteds was <null>, but actuals was a set of size " + actuals.size()); if (actuals == null) Assert.fail(message + " expecteds was a set of size " + expecteds.size() + ", but actuals was <null>"); assertSetOfNullableEquals(message, expecteds, actuals); } public static void assertNullableSetOfNullableEquals(final java.util.Set<java.math.BigDecimal> expecteds, final java.util.Set<java.math.BigDecimal> actuals) { assertNullableSetOfNullableEquals("NullableSetOfNullableDecimal mismatch: ", expecteds, actuals); } private static void assertQueueOfOneEquals(final String message, final java.util.Queue<java.math.BigDecimal> expecteds, final java.util.Queue<java.math.BigDecimal> actuals) { final int expectedsSize = expecteds.size(); final int actualsSize = actuals.size(); if (expectedsSize != actualsSize) { Assert.fail(message + "expecteds was a queue of size " + expectedsSize + ", but actuals was a queue of size " + actualsSize); } final java.util.Iterator<java.math.BigDecimal> expectedsIterator = expecteds.iterator(); final java.util.Iterator<java.math.BigDecimal> actualsIterator = actuals.iterator(); for (int i = 0; i < expectedsSize; i++) { final java.math.BigDecimal expected = expectedsIterator.next(); final java.math.BigDecimal actual = actualsIterator.next(); assertOneEquals(message + "element mismatch occurred at index " + i + ": ", expected, actual); } } private static void assertOneQueueOfOneEquals(final String message, final java.util.Queue<java.math.BigDecimal> expecteds, final java.util.Queue<java.math.BigDecimal> actuals) { int i = 0; for (final java.math.BigDecimal expected : expecteds) { if (expected == null) { Assert.fail(message + "element mismatch occurred at index " + i + ": expected was <null> - WARNING: This is a preconditions failure in expected, this assertion will never succeed!"); } i++; } if (expecteds == actuals) return; if (actuals == null) Assert.fail(message + "expecteds was a queue of size " + expecteds.size() + ", but actuals was <null>"); assertQueueOfOneEquals(message, expecteds, actuals); } public static void assertOneQueueOfOneEquals(final java.util.Queue<java.math.BigDecimal> expecteds, final java.util.Queue<java.math.BigDecimal> actuals) { assertOneQueueOfOneEquals("OneQueueOfOneDecimal mismatch: ", expecteds, actuals); } private static void assertNullableQueueOfOneEquals(final String message, final java.util.Queue<java.math.BigDecimal> expecteds, final java.util.Queue<java.math.BigDecimal> actuals) { if (expecteds == actuals) return; if (expecteds == null) Assert.fail(message + "expecteds was <null>, but actuals was a queue of size " + actuals.size()); if (actuals == null) Assert.fail(message + " expecteds was a queue of size " + expecteds.size() + ", but actuals was <null>"); assertQueueOfOneEquals(message, expecteds, actuals); } public static void assertNullableQueueOfOneEquals(final java.util.Queue<java.math.BigDecimal> expecteds, final java.util.Queue<java.math.BigDecimal> actuals) { assertNullableQueueOfOneEquals("NullableQueueOfOneDecimal mismatch: ", expecteds, actuals); } private static void assertQueueOfNullableEquals(final String message, final java.util.Queue<java.math.BigDecimal> expecteds, final java.util.Queue<java.math.BigDecimal> actuals) { final int expectedsSize = expecteds.size(); final int actualsSize = actuals.size(); if (expectedsSize != actualsSize) { Assert.fail(message + "expecteds was a queue of size " + expectedsSize + ", but actuals was a queue of size " + actualsSize); } final java.util.Iterator<java.math.BigDecimal> expectedsIterator = expecteds.iterator(); final java.util.Iterator<java.math.BigDecimal> actualsIterator = actuals.iterator(); for (int i = 0; i < expectedsSize; i++) { final java.math.BigDecimal expected = expectedsIterator.next(); final java.math.BigDecimal actual = actualsIterator.next(); assertNullableEquals(message + "element mismatch occurred at index " + i + ": ", expected, actual); } } private static void assertOneQueueOfNullableEquals(final String message, final java.util.Queue<java.math.BigDecimal> expecteds, final java.util.Queue<java.math.BigDecimal> actuals) { if (expecteds == null) Assert.fail(message + "expecteds was <null> - WARNING: This is a preconditions failure in expecteds, this assertion will never succeed!"); if (expecteds == actuals) return; if (actuals == null) Assert.fail(message + "expecteds was a queue of size " + expecteds.size() + ", but actuals was <null>"); assertQueueOfNullableEquals(message, expecteds, actuals); } public static void assertOneQueueOfNullableEquals(final java.util.Queue<java.math.BigDecimal> expecteds, final java.util.Queue<java.math.BigDecimal> actuals) { assertOneQueueOfNullableEquals("OneQueueOfNullableDecimal mismatch: ", expecteds, actuals); } private static void assertNullableQueueOfNullableEquals(final String message, final java.util.Queue<java.math.BigDecimal> expecteds, final java.util.Queue<java.math.BigDecimal> actuals) { if (expecteds == actuals) return; if (expecteds == null) Assert.fail(message + "expecteds was <null>, but actuals was a queue of size " + actuals.size()); if (actuals == null) Assert.fail(message + " expecteds was a queue of size " + expecteds.size() + ", but actuals was <null>"); assertQueueOfNullableEquals(message, expecteds, actuals); } public static void assertNullableQueueOfNullableEquals(final java.util.Queue<java.math.BigDecimal> expecteds, final java.util.Queue<java.math.BigDecimal> actuals) { assertNullableQueueOfNullableEquals("NullableQueueOfNullableDecimal mismatch: ", expecteds, actuals); } private static void assertLinkedListOfOneEquals(final String message, final java.util.LinkedList<java.math.BigDecimal> expecteds, final java.util.LinkedList<java.math.BigDecimal> actuals) { final int expectedsSize = expecteds.size(); final int actualsSize = actuals.size(); if (expectedsSize != actualsSize) { Assert.fail(message + "expecteds was a linked list of size " + expectedsSize + ", but actuals was a linked list of size " + actualsSize); } final java.util.Iterator<java.math.BigDecimal> expectedsIterator = expecteds.iterator(); final java.util.Iterator<java.math.BigDecimal> actualsIterator = actuals.iterator(); for (int i = 0; i < expectedsSize; i++) { final java.math.BigDecimal expected = expectedsIterator.next(); final java.math.BigDecimal actual = actualsIterator.next(); assertOneEquals(message + "element mismatch occurred at index " + i + ": ", expected, actual); } } private static void assertOneLinkedListOfOneEquals(final String message, final java.util.LinkedList<java.math.BigDecimal> expecteds, final java.util.LinkedList<java.math.BigDecimal> actuals) { int i = 0; for (final java.math.BigDecimal expected : expecteds) { if (expected == null) { Assert.fail(message + "element mismatch occurred at index " + i + ": expected was <null> - WARNING: This is a preconditions failure in expected, this assertion will never succeed!"); } i++; } if (expecteds == actuals) return; if (actuals == null) Assert.fail(message + "expecteds was a linked list of size " + expecteds.size() + ", but actuals was <null>"); assertLinkedListOfOneEquals(message, expecteds, actuals); } public static void assertOneLinkedListOfOneEquals(final java.util.LinkedList<java.math.BigDecimal> expecteds, final java.util.LinkedList<java.math.BigDecimal> actuals) { assertOneLinkedListOfOneEquals("OneLinkedListOfOneDecimal mismatch: ", expecteds, actuals); } private static void assertNullableLinkedListOfOneEquals(final String message, final java.util.LinkedList<java.math.BigDecimal> expecteds, final java.util.LinkedList<java.math.BigDecimal> actuals) { if (expecteds == actuals) return; if (expecteds == null) Assert.fail(message + "expecteds was <null>, but actuals was a linked list of size " + actuals.size()); if (actuals == null) Assert.fail(message + " expecteds was a linked list of size " + expecteds.size() + ", but actuals was <null>"); assertLinkedListOfOneEquals(message, expecteds, actuals); } public static void assertNullableLinkedListOfOneEquals(final java.util.LinkedList<java.math.BigDecimal> expecteds, final java.util.LinkedList<java.math.BigDecimal> actuals) { assertNullableLinkedListOfOneEquals("NullableLinkedListOfOneDecimal mismatch: ", expecteds, actuals); } private static void assertLinkedListOfNullableEquals(final String message, final java.util.LinkedList<java.math.BigDecimal> expecteds, final java.util.LinkedList<java.math.BigDecimal> actuals) { final int expectedsSize = expecteds.size(); final int actualsSize = actuals.size(); if (expectedsSize != actualsSize) { Assert.fail(message + "expecteds was a linked list of size " + expectedsSize + ", but actuals was a linked list of size " + actualsSize); } final java.util.Iterator<java.math.BigDecimal> expectedsIterator = expecteds.iterator(); final java.util.Iterator<java.math.BigDecimal> actualsIterator = actuals.iterator(); for (int i = 0; i < expectedsSize; i++) { final java.math.BigDecimal expected = expectedsIterator.next(); final java.math.BigDecimal actual = actualsIterator.next(); assertNullableEquals(message + "element mismatch occurred at index " + i + ": ", expected, actual); } } private static void assertOneLinkedListOfNullableEquals(final String message, final java.util.LinkedList<java.math.BigDecimal> expecteds, final java.util.LinkedList<java.math.BigDecimal> actuals) { if (expecteds == null) Assert.fail(message + "expecteds was <null> - WARNING: This is a preconditions failure in expecteds, this assertion will never succeed!"); if (expecteds == actuals) return; if (actuals == null) Assert.fail(message + "expecteds was a linked list of size " + expecteds.size() + ", but actuals was <null>"); assertLinkedListOfNullableEquals(message, expecteds, actuals); } public static void assertOneLinkedListOfNullableEquals(final java.util.LinkedList<java.math.BigDecimal> expecteds, final java.util.LinkedList<java.math.BigDecimal> actuals) { assertOneLinkedListOfNullableEquals("OneLinkedListOfNullableDecimal mismatch: ", expecteds, actuals); } private static void assertNullableLinkedListOfNullableEquals(final String message, final java.util.LinkedList<java.math.BigDecimal> expecteds, final java.util.LinkedList<java.math.BigDecimal> actuals) { if (expecteds == actuals) return; if (expecteds == null) Assert.fail(message + "expecteds was <null>, but actuals was a linked list of size " + actuals.size()); if (actuals == null) Assert.fail(message + " expecteds was a linked list of size " + expecteds.size() + ", but actuals was <null>"); assertLinkedListOfNullableEquals(message, expecteds, actuals); } public static void assertNullableLinkedListOfNullableEquals(final java.util.LinkedList<java.math.BigDecimal> expecteds, final java.util.LinkedList<java.math.BigDecimal> actuals) { assertNullableLinkedListOfNullableEquals("NullableLinkedListOfNullableDecimal mismatch: ", expecteds, actuals); } private static void assertStackOfOneEquals(final String message, final java.util.Stack<java.math.BigDecimal> expecteds, final java.util.Stack<java.math.BigDecimal> actuals) { final int expectedsSize = expecteds.size(); final int actualsSize = actuals.size(); if (expectedsSize != actualsSize) { Assert.fail(message + "expecteds was a stack of size " + expectedsSize + ", but actuals was a stack of size " + actualsSize); } final java.util.Iterator<java.math.BigDecimal> expectedsIterator = expecteds.iterator(); final java.util.Iterator<java.math.BigDecimal> actualsIterator = actuals.iterator(); for (int i = 0; i < expectedsSize; i++) { final java.math.BigDecimal expected = expectedsIterator.next(); final java.math.BigDecimal actual = actualsIterator.next(); assertOneEquals(message + "element mismatch occurred at index " + i + ": ", expected, actual); } } private static void assertOneStackOfOneEquals(final String message, final java.util.Stack<java.math.BigDecimal> expecteds, final java.util.Stack<java.math.BigDecimal> actuals) { int i = 0; for (final java.math.BigDecimal expected : expecteds) { if (expected == null) { Assert.fail(message + "element mismatch occurred at index " + i + ": expected was <null> - WARNING: This is a preconditions failure in expected, this assertion will never succeed!"); } i++; } if (expecteds == actuals) return; if (actuals == null) Assert.fail(message + "expecteds was a stack of size " + expecteds.size() + ", but actuals was <null>"); assertStackOfOneEquals(message, expecteds, actuals); } public static void assertOneStackOfOneEquals(final java.util.Stack<java.math.BigDecimal> expecteds, final java.util.Stack<java.math.BigDecimal> actuals) { assertOneStackOfOneEquals("OneStackOfOneDecimal mismatch: ", expecteds, actuals); } private static void assertNullableStackOfOneEquals(final String message, final java.util.Stack<java.math.BigDecimal> expecteds, final java.util.Stack<java.math.BigDecimal> actuals) { if (expecteds == actuals) return; if (expecteds == null) Assert.fail(message + "expecteds was <null>, but actuals was a stack of size " + actuals.size()); if (actuals == null) Assert.fail(message + " expecteds was a stack of size " + expecteds.size() + ", but actuals was <null>"); assertStackOfOneEquals(message, expecteds, actuals); } public static void assertNullableStackOfOneEquals(final java.util.Stack<java.math.BigDecimal> expecteds, final java.util.Stack<java.math.BigDecimal> actuals) { assertNullableStackOfOneEquals("NullableStackOfOneDecimal mismatch: ", expecteds, actuals); } private static void assertStackOfNullableEquals(final String message, final java.util.Stack<java.math.BigDecimal> expecteds, final java.util.Stack<java.math.BigDecimal> actuals) { final int expectedsSize = expecteds.size(); final int actualsSize = actuals.size(); if (expectedsSize != actualsSize) { Assert.fail(message + "expecteds was a stack of size " + expectedsSize + ", but actuals was a stack of size " + actualsSize); } final java.util.Iterator<java.math.BigDecimal> expectedsIterator = expecteds.iterator(); final java.util.Iterator<java.math.BigDecimal> actualsIterator = actuals.iterator(); for (int i = 0; i < expectedsSize; i++) { final java.math.BigDecimal expected = expectedsIterator.next(); final java.math.BigDecimal actual = actualsIterator.next(); assertNullableEquals(message + "element mismatch occurred at index " + i + ": ", expected, actual); } } private static void assertOneStackOfNullableEquals(final String message, final java.util.Stack<java.math.BigDecimal> expecteds, final java.util.Stack<java.math.BigDecimal> actuals) { if (expecteds == null) Assert.fail(message + "expecteds was <null> - WARNING: This is a preconditions failure in expecteds, this assertion will never succeed!"); if (expecteds == actuals) return; if (actuals == null) Assert.fail(message + "expecteds was a stack of size " + expecteds.size() + ", but actuals was <null>"); assertStackOfNullableEquals(message, expecteds, actuals); } public static void assertOneStackOfNullableEquals(final java.util.Stack<java.math.BigDecimal> expecteds, final java.util.Stack<java.math.BigDecimal> actuals) { assertOneStackOfNullableEquals("OneStackOfNullableDecimal mismatch: ", expecteds, actuals); } private static void assertNullableStackOfNullableEquals(final String message, final java.util.Stack<java.math.BigDecimal> expecteds, final java.util.Stack<java.math.BigDecimal> actuals) { if (expecteds == actuals) return; if (expecteds == null) Assert.fail(message + "expecteds was <null>, but actuals was a stack of size " + actuals.size()); if (actuals == null) Assert.fail(message + " expecteds was a stack of size " + expecteds.size() + ", but actuals was <null>"); assertStackOfNullableEquals(message, expecteds, actuals); } public static void assertNullableStackOfNullableEquals(final java.util.Stack<java.math.BigDecimal> expecteds, final java.util.Stack<java.math.BigDecimal> actuals) { assertNullableStackOfNullableEquals("NullableStackOfNullableDecimal mismatch: ", expecteds, actuals); } private static void assertVectorOfOneEquals(final String message, final java.util.Vector<java.math.BigDecimal> expecteds, final java.util.Vector<java.math.BigDecimal> actuals) { final int expectedsSize = expecteds.size(); final int actualsSize = actuals.size(); if (expectedsSize != actualsSize) { Assert.fail(message + "expecteds was a vector of size " + expectedsSize + ", but actuals was a vector of size " + actualsSize); } final java.util.Iterator<java.math.BigDecimal> expectedsIterator = expecteds.iterator(); final java.util.Iterator<java.math.BigDecimal> actualsIterator = actuals.iterator(); for (int i = 0; i < expectedsSize; i++) { final java.math.BigDecimal expected = expectedsIterator.next(); final java.math.BigDecimal actual = actualsIterator.next(); assertOneEquals(message + "element mismatch occurred at index " + i + ": ", expected, actual); } } private static void assertOneVectorOfOneEquals(final String message, final java.util.Vector<java.math.BigDecimal> expecteds, final java.util.Vector<java.math.BigDecimal> actuals) { int i = 0; for (final java.math.BigDecimal expected : expecteds) { if (expected == null) { Assert.fail(message + "element mismatch occurred at index " + i + ": expected was <null> - WARNING: This is a preconditions failure in expected, this assertion will never succeed!"); } i++; } if (expecteds == actuals) return; if (actuals == null) Assert.fail(message + "expecteds was a vector of size " + expecteds.size() + ", but actuals was <null>"); assertVectorOfOneEquals(message, expecteds, actuals); } public static void assertOneVectorOfOneEquals(final java.util.Vector<java.math.BigDecimal> expecteds, final java.util.Vector<java.math.BigDecimal> actuals) { assertOneVectorOfOneEquals("OneVectorOfOneDecimal mismatch: ", expecteds, actuals); } private static void assertNullableVectorOfOneEquals(final String message, final java.util.Vector<java.math.BigDecimal> expecteds, final java.util.Vector<java.math.BigDecimal> actuals) { if (expecteds == actuals) return; if (expecteds == null) Assert.fail(message + "expecteds was <null>, but actuals was a vector of size " + actuals.size()); if (actuals == null) Assert.fail(message + " expecteds was a vector of size " + expecteds.size() + ", but actuals was <null>"); assertVectorOfOneEquals(message, expecteds, actuals); } public static void assertNullableVectorOfOneEquals(final java.util.Vector<java.math.BigDecimal> expecteds, final java.util.Vector<java.math.BigDecimal> actuals) { assertNullableVectorOfOneEquals("NullableVectorOfOneDecimal mismatch: ", expecteds, actuals); } private static void assertVectorOfNullableEquals(final String message, final java.util.Vector<java.math.BigDecimal> expecteds, final java.util.Vector<java.math.BigDecimal> actuals) { final int expectedsSize = expecteds.size(); final int actualsSize = actuals.size(); if (expectedsSize != actualsSize) { Assert.fail(message + "expecteds was a vector of size " + expectedsSize + ", but actuals was a vector of size " + actualsSize); } final java.util.Iterator<java.math.BigDecimal> expectedsIterator = expecteds.iterator(); final java.util.Iterator<java.math.BigDecimal> actualsIterator = actuals.iterator(); for (int i = 0; i < expectedsSize; i++) { final java.math.BigDecimal expected = expectedsIterator.next(); final java.math.BigDecimal actual = actualsIterator.next(); assertNullableEquals(message + "element mismatch occurred at index " + i + ": ", expected, actual); } } private static void assertOneVectorOfNullableEquals(final String message, final java.util.Vector<java.math.BigDecimal> expecteds, final java.util.Vector<java.math.BigDecimal> actuals) { if (expecteds == null) Assert.fail(message + "expecteds was <null> - WARNING: This is a preconditions failure in expecteds, this assertion will never succeed!"); if (expecteds == actuals) return; if (actuals == null) Assert.fail(message + "expecteds was a vector of size " + expecteds.size() + ", but actuals was <null>"); assertVectorOfNullableEquals(message, expecteds, actuals); } public static void assertOneVectorOfNullableEquals(final java.util.Vector<java.math.BigDecimal> expecteds, final java.util.Vector<java.math.BigDecimal> actuals) { assertOneVectorOfNullableEquals("OneVectorOfNullableDecimal mismatch: ", expecteds, actuals); } private static void assertNullableVectorOfNullableEquals(final String message, final java.util.Vector<java.math.BigDecimal> expecteds, final java.util.Vector<java.math.BigDecimal> actuals) { if (expecteds == actuals) return; if (expecteds == null) Assert.fail(message + "expecteds was <null>, but actuals was a vector of size " + actuals.size()); if (actuals == null) Assert.fail(message + " expecteds was a vector of size " + expecteds.size() + ", but actuals was <null>"); assertVectorOfNullableEquals(message, expecteds, actuals); } public static void assertNullableVectorOfNullableEquals(final java.util.Vector<java.math.BigDecimal> expecteds, final java.util.Vector<java.math.BigDecimal> actuals) { assertNullableVectorOfNullableEquals("NullableVectorOfNullableDecimal mismatch: ", expecteds, actuals); } }
bsd-3-clause
ds-hwang/chromium-crosswalk
chrome/android/java/src/org/chromium/chrome/browser/WarmupManager.java
11393
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser; import android.content.Context; import android.os.AsyncTask; import android.view.ContextThemeWrapper; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewStub; import android.widget.FrameLayout; import org.chromium.base.ThreadUtils; import org.chromium.base.TraceEvent; import org.chromium.chrome.R; import org.chromium.chrome.browser.net.spdyproxy.DataReductionProxySettings; import org.chromium.chrome.browser.prerender.ExternalPrerenderHandler; import org.chromium.chrome.browser.profiles.Profile; import org.chromium.content_public.browser.WebContents; import java.net.InetAddress; import java.net.MalformedURLException; import java.net.URL; import java.net.UnknownHostException; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * This class is a singleton that holds utilities for warming up Chrome and prerendering urls * without creating the Activity. * * This class is not thread-safe and must only be used on the UI thread. */ public final class WarmupManager { private static WarmupManager sWarmupManager; private final Set<String> mDnsRequestsInFlight; private final Map<String, Profile> mPendingPreconnectWithProfile; private boolean mPrerenderIsAllowed; private WebContents mPrerenderedWebContents; private boolean mPrerendered; private int mToolbarContainerId; private ViewGroup mMainView; private ExternalPrerenderHandler mExternalPrerenderHandler; /** * @return The singleton instance for the WarmupManager, creating one if necessary. */ public static WarmupManager getInstance() { ThreadUtils.assertOnUiThread(); if (sWarmupManager == null) sWarmupManager = new WarmupManager(); return sWarmupManager; } private WarmupManager() { mPrerenderIsAllowed = true; mDnsRequestsInFlight = new HashSet<String>(); mPendingPreconnectWithProfile = new HashMap<String, Profile>(); } /** * Disallow prerendering from now until the browser process death. */ public void disallowPrerendering() { ThreadUtils.assertOnUiThread(); mPrerenderIsAllowed = false; cancelCurrentPrerender(); mExternalPrerenderHandler = null; } /** * Check whether prerender manager has the given url prerendered. This also works with * redirected urls. * * Uses the last used profile. * * @param url The url to check. * @return Whether the given url has been prerendered. */ public boolean hasPrerenderedUrl(String url) { ThreadUtils.assertOnUiThread(); if (!mPrerenderIsAllowed) return false; return hasAnyPrerenderedUrl() && ExternalPrerenderHandler.hasPrerenderedUrl( Profile.getLastUsedProfile(), url, mPrerenderedWebContents); } /** * @return Whether any url has been prerendered. */ public boolean hasAnyPrerenderedUrl() { ThreadUtils.assertOnUiThread(); if (!mPrerenderIsAllowed) return false; return mPrerendered; } /** * @return The prerendered {@link WebContents} clearing out the reference WarmupManager owns. */ public WebContents takePrerenderedWebContents() { ThreadUtils.assertOnUiThread(); if (!mPrerenderIsAllowed) return null; WebContents prerenderedWebContents = mPrerenderedWebContents; assert (mPrerenderedWebContents != null); mPrerenderedWebContents = null; return prerenderedWebContents; } /** * Prerenders the given url using the prerender_manager. * * Uses the last used profile. * * @param url The url to prerender. * @param referrer The referrer url to be used while prerendering * @param widthPix The width in pixels to which the page should be prerendered. * @param heightPix The height in pixels to which the page should be prerendered. */ public void prerenderUrl(final String url, final String referrer, final int widthPix, final int heightPix) { ThreadUtils.assertOnUiThread(); if (!mPrerenderIsAllowed) return; clearWebContentsIfNecessary(); if (mExternalPrerenderHandler == null) { mExternalPrerenderHandler = new ExternalPrerenderHandler(); } mPrerenderedWebContents = mExternalPrerenderHandler.addPrerender( Profile.getLastUsedProfile(), url, referrer, widthPix, heightPix, false); if (mPrerenderedWebContents != null) mPrerendered = true; } /** * Inflates and constructs the view hierarchy that the app will use. * @param baseContext The base context to use for creating the ContextWrapper. * @param toolbarContainerId Id of the toolbar container. */ public void initializeViewHierarchy(Context baseContext, int toolbarContainerId) { TraceEvent.begin("WarmupManager.initializeViewHierarchy"); try { ThreadUtils.assertOnUiThread(); if (mMainView != null && mToolbarContainerId == toolbarContainerId) return; ContextThemeWrapper context = new ContextThemeWrapper(baseContext, ChromeActivity.getThemeId()); FrameLayout contentHolder = new FrameLayout(context); mMainView = (ViewGroup) LayoutInflater.from(context).inflate( R.layout.main, contentHolder); mToolbarContainerId = toolbarContainerId; if (toolbarContainerId != ChromeActivity.NO_CONTROL_CONTAINER) { ViewStub stub = (ViewStub) mMainView.findViewById(R.id.control_container_stub); stub.setLayoutResource(toolbarContainerId); stub.inflate(); } } finally { TraceEvent.end("WarmupManager.initializeViewHierarchy"); } } /** * Transfers all the children in the view hierarchy to the giving ViewGroup as child. * @param contentView The parent ViewGroup to use for the transfer. */ public void transferViewHierarchyTo(ViewGroup contentView) { ThreadUtils.assertOnUiThread(); ViewGroup viewHierarchy = mMainView; mMainView = null; if (viewHierarchy == null) return; while (viewHierarchy.getChildCount() > 0) { View currentChild = viewHierarchy.getChildAt(0); viewHierarchy.removeView(currentChild); contentView.addView(currentChild); } } /** * Destroys the native WebContents instance the WarmupManager currently holds onto. */ public void clearWebContentsIfNecessary() { ThreadUtils.assertOnUiThread(); mPrerendered = false; if (mPrerenderedWebContents == null) return; mPrerenderedWebContents.destroy(); mPrerenderedWebContents = null; } /** * Cancel the current prerender. */ public void cancelCurrentPrerender() { ThreadUtils.assertOnUiThread(); clearWebContentsIfNecessary(); if (mExternalPrerenderHandler == null) return; mExternalPrerenderHandler.cancelCurrentPrerender(); } /** * @return Whether the view hierarchy has been prebuilt with a given toolbar ID. If there is no * match, clears the inflated view. */ public boolean hasBuiltOrClearViewHierarchyWithToolbar(int toolbarContainerId) { ThreadUtils.assertOnUiThread(); boolean match = mMainView != null && mToolbarContainerId == toolbarContainerId; if (!match) mMainView = null; return match; } /** * Launches a background DNS query for a given URL. * * @param url URL from which the domain to query is extracted. */ private void prefetchDnsForUrlInBackground(final String url) { mDnsRequestsInFlight.add(url); new AsyncTask<String, Void, Void>() { @Override protected Void doInBackground(String... params) { try { InetAddress.getByName(new URL(url).getHost()); } catch (MalformedURLException e) { // We don't do anything with the result of the request, it // is only here to warm up the cache, thus ignoring the // exception is fine. } catch (UnknownHostException e) { // As above. } return null; } @Override protected void onPostExecute(Void result) { mDnsRequestsInFlight.remove(url); if (mPendingPreconnectWithProfile.containsKey(url)) { Profile profile = mPendingPreconnectWithProfile.get(url); mPendingPreconnectWithProfile.remove(url); maybePreconnectUrlAndSubResources(profile, url); } } }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, url); } /** Launches a background DNS query for a given URL if the data reduction proxy is not in use. * * @param context The Application context. * @param url URL from which the domain to query is extracted. */ public void maybePrefetchDnsForUrlInBackground(Context context, String url) { ThreadUtils.assertOnUiThread(); if (!DataReductionProxySettings.isEnabledBeforeNativeLoad(context)) { prefetchDnsForUrlInBackground(url); } } /** Asynchronously preconnects to a given URL if the data reduction proxy is not in use. * * @param profile The profile to use for the preconnection. * @param url The URL we want to preconnect to. */ public void maybePreconnectUrlAndSubResources(Profile profile, String url) { ThreadUtils.assertOnUiThread(); if (!DataReductionProxySettings.getInstance().isDataReductionProxyEnabled()) { // If there is already a DNS request in flight for this URL, then // the preconnection will start by issuing a DNS request for the // same domain, as the result is not cached. However, such a DNS // request has already been sent from this class, so it is better to // wait for the answer to come back before preconnecting. Otherwise, // the preconnection logic will wait for the result of the second // DNS request, which should arrive after the result of the first // one. Note that we however need to wait for the main thread to be // available in this case, since the preconnection will be sent from // AsyncTask.onPostExecute(), which may delay it. if (mDnsRequestsInFlight.contains(url)) { // Note that if two requests come for the same URL with two // different profiles, the last one will win. mPendingPreconnectWithProfile.put(url, profile); } else { nativePreconnectUrlAndSubresources(profile, url); } } } private static native void nativePreconnectUrlAndSubresources(Profile profile, String url); }
bsd-3-clause
manolama/asynchbase
test/TestHBaseClientLocateRegion.java
31688
/* * Copyright (C) 2014-2018 The Async HBase Authors. All rights reserved. * This file is part of Async HBase. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of the StumbleUpon nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package org.hbase.async; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Matchers.any; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.ArrayList; import org.hbase.async.Scanner.OpenScannerRequest; import org.hbase.async.Scanner.Response; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.reflect.Whitebox; import com.google.common.collect.Lists; import com.stumbleupon.async.Deferred; import com.stumbleupon.async.DeferredGroupException; @RunWith(PowerMockRunner.class) //"Classloader hell"... It's real. Tell PowerMock to ignore these classes //because they fiddle with the class loader. We don't test them anyway. @PowerMockIgnore({"javax.management.*", "javax.xml.*", "ch.qos.*", "org.slf4j.*", "com.sum.*", "org.xml.*"}) @PrepareForTest({ HBaseClient.class, RegionClient.class, RegionInfo.class, HBaseRpc.class, RegionClientStats.class, Scanner.class, HBaseRpc.class, DeferredGroupException.class }) public class TestHBaseClientLocateRegion extends BaseTestHBaseClient { private Deferred<Object> root_deferred; private GetRequest get; @Before public void beforeLocal() throws Exception { root_deferred = new Deferred<Object>(); when(zkclient.getDeferredRoot()).thenReturn(root_deferred); get = new GetRequest(TABLE, KEY); Whitebox.setInternalState(client, "has_root", true); } //-------- ROOT AND DEAD ROOT CLIENT ---------- @Test public void locateRegionRoot98HadRootLookupInZK() throws Exception { final Object obj = Whitebox.invokeMethod(client, "locateRegion", get, HBaseClient.HBASE98_ROOT, EMPTY_ARRAY); assertTrue(root_deferred == obj); assertCounters(0, 0, 0); } @Test public void locateRegionRootHadRootLookupInZK() throws Exception { final Object obj = Whitebox.invokeMethod(client, "locateRegion", get, HBaseClient.ROOT, EMPTY_ARRAY); assertTrue(root_deferred == obj); assertCounters(0, 0, 0); } @Test public void locateRegionRootNoRootLookupInZK() throws Exception { Whitebox.setInternalState(client, "has_root", false); final Object obj = Whitebox.invokeMethod(client, "locateRegion", get, HBaseClient.ROOT, EMPTY_ARRAY); assertTrue(root_deferred == obj); assertCounters(0, 0, 0); } //--------- META AND DEAD ROOT CLIENT ------------ @Test public void locateRegionMetaHadRootLookupInZK() throws Exception { final Object obj = Whitebox.invokeMethod(client, "locateRegion", get, HBaseClient.META, EMPTY_ARRAY); assertTrue(root_deferred == obj); assertCounters(0, 0, 0); } @Test public void locateRegionMeta96HadRootLookupInZK() throws Exception { final Object obj = Whitebox.invokeMethod(client, "locateRegion", get, HBaseClient.HBASE96_META, EMPTY_ARRAY); assertTrue(root_deferred == obj); assertCounters(0, 0, 0); } @Test public void locateRegionMetaNoRootLookupInZK() throws Exception { Whitebox.setInternalState(client, "has_root", false); final Object obj = Whitebox.invokeMethod(client, "locateRegion", get, HBaseClient.META, EMPTY_ARRAY); assertTrue(root_deferred == obj); assertCounters(0, 0, 0); } @Test public void locateRegionMeta96NoRootLookupInZK() throws Exception { Whitebox.setInternalState(client, "has_root", false); final Object obj = Whitebox.invokeMethod(client, "locateRegion", get, HBaseClient.HBASE96_META, EMPTY_ARRAY); assertTrue(root_deferred == obj); assertCounters(0, 0, 0); } @Test public void locateRegionMeta98SplitMetaLookupInZK() throws Exception { client.has_root = true; client.split_meta = true; final Object obj = Whitebox.invokeMethod(client, "locateRegion", get, HBaseClient.HBASE96_META, EMPTY_ARRAY); assertTrue(root_deferred == obj); assertCounters(0, 0, 0); } // --------------- ROOT RECURSION -------------- // These make sure we don't check the root region for the root region // because that would be plain silly. @SuppressWarnings("unchecked") @Test public void locateRegionRootHadRootLiveClient() throws Exception { setLiveRootClient(); final Object obj = Whitebox.invokeMethod(client, "locateRegion", get, HBaseClient.ROOT, EMPTY_ARRAY); assertTrue(root_deferred != obj); assertNull(((Deferred<Object>)obj).joinUninterruptibly()); assertCounters(0, 0, 0); } //--------------- META LOOKUP IN ROOT -------------- @Test public void locateRegionMetaLiveRootClient() throws Exception { clearCaches(); final RegionInfo ri = new RegionInfo(HBaseClient.ROOT, HBaseClient.ROOT_REGION, EMPTY_ARRAY); final byte[] meta_key = HBaseClient.createRegionSearchKey( HBaseClient.META, EMPTY_ARRAY, false); final byte[] key = HBaseClient.createRegionSearchKey(HBaseClient.META, meta_key); Whitebox.setInternalState(client, "rootregion", rootclient); when(rootclient.isAlive()).thenReturn(true); when(rootclient.getClosestRowBefore(any(RegionInfo.class), any(byte[].class), any(byte[].class), any(byte[].class))) .thenReturn(Deferred.<ArrayList<KeyValue>>fromResult(metaRow())); final Deferred<Object> obj = Whitebox.invokeMethod(client, "locateRegion", get, HBaseClient.META, EMPTY_ARRAY); verify(rootclient, times(1)).getClosestRowBefore(ri, HBaseClient.ROOT, key, HBaseClient.INFO); assertTrue(root_deferred != obj); final RegionClient rc = (RegionClient) obj.joinUninterruptibly(); assertCounters(1, 0, 0); assertEquals(1, client2regions.size()); assertNotNull(client2regions.get(rc)); } @Test public void locateRegionMetaSplitMetaLiveRootClient() throws Exception { clearCaches(); final RegionInfo ri = new RegionInfo(HBaseClient.HBASE98_ROOT, HBaseClient.HBASE98_ROOT_REGION, EMPTY_ARRAY); final byte[] meta_key = HBaseClient.createRegionSearchKey( HBaseClient.HBASE96_META, EMPTY_ARRAY, false); final byte[] key = HBaseClient.createRegionSearchKey(HBaseClient.HBASE96_META, meta_key); client.split_meta = true; Whitebox.setInternalState(client, "rootregion", rootclient); when(rootclient.isAlive()).thenReturn(true); when(rootclient.getClosestRowBefore(any(RegionInfo.class), any(byte[].class), any(byte[].class), any(byte[].class))) .thenReturn(Deferred.<ArrayList<KeyValue>>fromResult(metaRow())); final Deferred<Object> obj = Whitebox.invokeMethod(client, "locateRegion", get, HBaseClient.HBASE96_META, EMPTY_ARRAY); verify(rootclient, times(1)).getClosestRowBefore(ri, HBaseClient.HBASE98_ROOT, key, HBaseClient.INFO); assertTrue(root_deferred != obj); final RegionClient rc = (RegionClient) obj.joinUninterruptibly(); assertCounters(1, 0, 0); assertEquals(1, client2regions.size()); assertNotNull(client2regions.get(rc)); } @Test public void locateRegionMetaSplitScanMetaLiveRootClient() throws Exception { clearCaches(); final RegionInfo ri = new RegionInfo(HBaseClient.HBASE98_ROOT, HBaseClient.HBASE98_ROOT_REGION, EMPTY_ARRAY); final byte[] meta_key = HBaseClient.createRegionSearchKey( HBaseClient.HBASE96_META, EMPTY_ARRAY, false); final byte[] key = HBaseClient.createRegionSearchKey( HBaseClient.HBASE96_META, meta_key); client.split_meta = true; Whitebox.setInternalState(client, "rootregion", rootclient); Whitebox.setInternalState(client, "scan_meta", true); when(rootclient.isAlive()).thenReturn(true); doReturn(Deferred.<ArrayList<KeyValue>>fromResult(metaRow())) .when(client).scanMeta(any(RegionClient.class), any(RegionInfo.class), any(byte[].class), any(byte[].class), any(byte[].class)); final Deferred<Object> obj = Whitebox.invokeMethod(client, "locateRegion", get, HBaseClient.HBASE96_META, EMPTY_ARRAY); verify(client, times(1)).scanMeta(rootclient, ri, HBaseClient.HBASE98_ROOT, key, HBaseClient.INFO); assertTrue(root_deferred != obj); final RegionClient rc = (RegionClient) obj.joinUninterruptibly(); assertCounters(1, 0, 0); assertEquals(1, client2regions.size()); assertNotNull(client2regions.get(rc)); } @Test public void locateRegionMetaLiveRootClientTableNotFound() throws Exception { Whitebox.setInternalState(client, "rootregion", rootclient); when(rootclient.isAlive()).thenReturn(true); when(rootclient.getClosestRowBefore(any(RegionInfo.class), any(byte[].class), any(byte[].class), any(byte[].class))) .thenReturn(Deferred.<ArrayList<KeyValue>>fromResult( new ArrayList<KeyValue>(0))); final Deferred<Object> obj = Whitebox.invokeMethod(client, "locateRegion", get, HBaseClient.META, EMPTY_ARRAY); assertTrue(root_deferred != obj); assertCounters(1, 0, 0); assertEquals(2, client2regions.size()); TableNotFoundException ex = null; try { obj.joinUninterruptibly(); fail("Expected a TableNotFoundException exception"); } catch (final TableNotFoundException e) { ex = e; } assertArrayEquals(HBaseClient.META, ex.getTable()); } @Test public void locateRegionMetaLiveRootClientRecoverableException() throws Exception { Whitebox.setInternalState(client, "rootregion", rootclient); when(rootclient.isAlive()).thenReturn(true); when(rootclient.getClosestRowBefore(any(RegionInfo.class), any(byte[].class), any(byte[].class), any(byte[].class))) .thenReturn(Deferred.<ArrayList<KeyValue>>fromError( new RegionOfflineException(EMPTY_ARRAY))) .thenReturn(Deferred.<ArrayList<KeyValue>>fromError( new RegionOfflineException(EMPTY_ARRAY))) .thenReturn(Deferred.<ArrayList<KeyValue>>fromError( new RegionOfflineException(EMPTY_ARRAY))) .thenReturn(Deferred.<ArrayList<KeyValue>>fromResult(metaRow())); final Deferred<Object> obj = Whitebox.invokeMethod(client, "locateRegion", get, HBaseClient.META, EMPTY_ARRAY); assertTrue(root_deferred != obj); assertCounters(4, 0, 0); assertEquals(3, client2regions.size()); final RegionClient rc = (RegionClient)obj.joinUninterruptibly(); assertNotNull(client2regions.get(rc)); } // This used to be a tight loop that would continue indefinitely since we // didn't track how many times we looped. @Test public void locateRegionMetaLiveRootClientTooManyAttempts() throws Exception { Whitebox.setInternalState(client, "rootregion", rootclient); when(rootclient.isAlive()).thenReturn(true); final Deferred<Object> deferred = get.getDeferred(); when(rootclient.getClosestRowBefore(any(RegionInfo.class), any(byte[].class), any(byte[].class), any(byte[].class))) .thenAnswer(new Answer<Deferred<ArrayList<KeyValue>>>() { @Override public Deferred<ArrayList<KeyValue>> answer(InvocationOnMock invocation) throws Throwable { return Deferred.<ArrayList<KeyValue>>fromError( new RegionOfflineException(EMPTY_ARRAY)); } }); final Deferred<Object> obj = Whitebox.invokeMethod(client, "locateRegion", get, HBaseClient.META, EMPTY_ARRAY); assertTrue(root_deferred != obj); assertCounters(12, 0, 0); assertEquals(2, client2regions.size()); try { obj.joinUninterruptibly(); fail("Expected a NonRecoverableException exception"); } catch (NonRecoverableException e) { } try { deferred.join(); fail("Expected a NonRecoverableException exception"); } catch (NonRecoverableException e) { } } @Test (expected = RuntimeException.class) public void locateRegionMetaLiveRootClientNonRecoverableException() throws Exception { Whitebox.setInternalState(client, "rootregion", rootclient); when(rootclient.isAlive()).thenReturn(true); when(rootclient.getClosestRowBefore(any(RegionInfo.class), any(byte[].class), any(byte[].class), any(byte[].class))) .thenReturn(Deferred.<ArrayList<KeyValue>>fromError( new RuntimeException("Boo!"))); final Deferred<Object> obj = Whitebox.invokeMethod(client, "locateRegion", get, HBaseClient.META, EMPTY_ARRAY); assertTrue(root_deferred != obj); assertCounters(1, 0, 0); assertEquals(2, client2regions.size()); obj.joinUninterruptibly(); } @Test public void locateRegionMetaLiveRootClientNSREdDueToSplit() throws Exception { Whitebox.setInternalState(client, "rootregion", rootclient); when(rootclient.isAlive()).thenReturn(true); final ArrayList<KeyValue> row = new ArrayList<KeyValue>(2); // Don't know if this is valid to be online and splitting. Prolly is row.add(metaRegionInfo(EMPTY_ARRAY, EMPTY_ARRAY, false, true, TABLE)); row.add(new KeyValue(meta.name(), INFO, SERVER, "localhost:54321".getBytes())); when(rootclient.getClosestRowBefore(any(RegionInfo.class), any(byte[].class), any(byte[].class), any(byte[].class))) .thenReturn(Deferred.<ArrayList<KeyValue>>fromResult(row)); final Deferred<Object> obj = Whitebox.invokeMethod(client, "locateRegion", get, HBaseClient.META, EMPTY_ARRAY); assertTrue(root_deferred != obj); assertCounters(1, 0, 0); assertEquals(2, client2regions.size()); assertNull(obj.joinUninterruptibly()); } @Test public void locateRegionMetaLiveRootClientOffline() throws Exception { Whitebox.setInternalState(client, "rootregion", rootclient); when(rootclient.isAlive()).thenReturn(true); final ArrayList<KeyValue> row = new ArrayList<KeyValue>(2); row.add(metaRegionInfo(EMPTY_ARRAY, EMPTY_ARRAY, true, false, TABLE)); row.add(new KeyValue(meta.name(), INFO, SERVER, "localhost:54321".getBytes())); when(rootclient.getClosestRowBefore(any(RegionInfo.class), any(byte[].class), any(byte[].class), any(byte[].class))) .thenReturn(Deferred.<ArrayList<KeyValue>>fromResult(row)) .thenReturn(Deferred.<ArrayList<KeyValue>>fromResult(metaRow())); final Deferred<Object> obj = Whitebox.invokeMethod(client, "locateRegion", get, HBaseClient.META, EMPTY_ARRAY); assertTrue(root_deferred != obj); assertCounters(2, 0, 0); assertEquals(3, client2regions.size()); final RegionClient rc = (RegionClient)obj.joinUninterruptibly(); assertNotNull(client2regions.get(rc)); } @Test (expected = BrokenMetaException.class) public void locateRegionMetaLiveRootClientBrokenMeta() throws Exception { Whitebox.setInternalState(client, "rootregion", rootclient); when(rootclient.isAlive()).thenReturn(true); final ArrayList<KeyValue> row = new ArrayList<KeyValue>(2); row.add(metaRegionInfo(EMPTY_ARRAY, EMPTY_ARRAY, false, false, TABLE)); row.add(new KeyValue(meta.name(), INFO, SERVER, "localhost:myport".getBytes())); when(rootclient.getClosestRowBefore(any(RegionInfo.class), any(byte[].class), any(byte[].class), any(byte[].class))) .thenReturn(Deferred.<ArrayList<KeyValue>>fromResult(row)); final Deferred<Object> obj = Whitebox.invokeMethod(client, "locateRegion", get, HBaseClient.META, EMPTY_ARRAY); assertTrue(root_deferred != obj); assertCounters(1, 0, 0); assertEquals(2, client2regions.size()); obj.joinUninterruptibly(); } // -------------- GENERAL LOOKUP ------------ @Test public void locateRegionLookupInZK() throws Exception { final Object obj = Whitebox.invokeMethod(client, "locateRegion", get, TABLE, EMPTY_ARRAY); assertTrue(root_deferred == obj); assertCounters(0, 0, 0); } //--------------- TABLE LOOKUP IN META -------------- @Test public void locateRegionInMeta() throws Exception { clearCaches(); Whitebox.setInternalState(client, "has_root", false); when(rootclient.isAlive()).thenReturn(true); when(rootclient.acquireMetaLookupPermit()).thenReturn(true); when(rootclient.getClosestRowBefore(any(RegionInfo.class), any(byte[].class), any(byte[].class), any(byte[].class))) .thenReturn(Deferred.<ArrayList<KeyValue>>fromResult(metaRow())); final Deferred<Object> obj = Whitebox.invokeMethod(client, "locateRegion", get, TABLE, KEY); assertTrue(root_deferred != obj); final RegionClient rc = (RegionClient) obj.join(1); assertCounters(0, 1, 0); assertEquals(1, client2regions.size()); assertNotNull(client2regions.get(rc)); } @Test public void locateRegionInMetaNoSuchTable() throws Exception { clearCaches(); Whitebox.setInternalState(client, "has_root", false); when(rootclient.isAlive()).thenReturn(true); when(rootclient.acquireMetaLookupPermit()).thenReturn(true); when(rootclient.getClosestRowBefore(any(RegionInfo.class), any(byte[].class), any(byte[].class), any(byte[].class))) .thenReturn(Deferred.<ArrayList<KeyValue>>fromResult(new ArrayList<KeyValue>(0))); final Deferred<Object> obj = Whitebox.invokeMethod(client, "locateRegion", get, HBaseClient.META, EMPTY_ARRAY); assertTrue(root_deferred != obj); try { obj.join(1); fail("Expected TableNotFoundException"); } catch (TableNotFoundException e) { } assertCounters(0, 1, 0); assertEquals(0, client2regions.size()); } @Test public void locateRegionInMetaScan() throws Exception { clearCaches(); Whitebox.setInternalState(client, "has_root", false); Whitebox.setInternalState(client, "scan_meta", true); when(rootclient.isAlive()).thenReturn(true); when(rootclient.acquireMetaLookupPermit()).thenReturn(true); doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) throws Throwable { final ArrayList<ArrayList<KeyValue>> rows = Lists.newArrayList(); rows.add(metaRow()); ((HBaseRpc) invocation.getArguments()[0]).getDeferred() .callback(new Response(0, rows, false, true)); return null; } }).when(rootclient).sendRpc(any(OpenScannerRequest.class)); final Deferred<Object> obj = Whitebox.invokeMethod(client, "locateRegion", get, TABLE, KEY); assertTrue(root_deferred != obj); final RegionClient rc = (RegionClient) obj.join(1); assertCounters(0, 1, 0); assertEquals(1, client2regions.size()); assertNotNull(client2regions.get(rc)); } @Test public void locateRegionInMetaSwitchToScan() throws Exception { clearCaches(); Whitebox.setInternalState(client, "has_root", false); Whitebox.setInternalState(client, "scan_meta", false); when(rootclient.isAlive()).thenReturn(true); when(rootclient.acquireMetaLookupPermit()).thenReturn(true); doAnswer(new Answer<Deferred<ArrayList<KeyValue>>>() { @Override public Deferred<ArrayList<KeyValue>> answer(InvocationOnMock invocation) throws Throwable { final Exception e = new UnknownProtocolException("", null); return Deferred.fromError(e); } }).when(rootclient).getClosestRowBefore(any(RegionInfo.class), any(byte[].class), any(byte[].class), any(byte[].class)); doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) throws Throwable { final ArrayList<ArrayList<KeyValue>> rows = Lists.newArrayList(); rows.add(metaRow()); ((HBaseRpc) invocation.getArguments()[0]).getDeferred() .callback(new Response(0, rows, false, true)); return null; } }).when(rootclient).sendRpc(any(OpenScannerRequest.class)); final Deferred<Object> obj = Whitebox.invokeMethod(client, "locateRegion", get, TABLE, KEY); assertTrue(root_deferred != obj); final RegionClient rc = (RegionClient) obj.join(1); assertCounters(0, 2, 0); assertEquals(1, client2regions.size()); assertNotNull(client2regions.get(rc)); assertTrue((boolean) (Boolean) Whitebox.getInternalState(client, "scan_meta")); } @Test public void locateRegionInMetaSwitchToScanDGE() throws Exception { clearCaches(); Whitebox.setInternalState(client, "has_root", false); Whitebox.setInternalState(client, "scan_meta", false); when(rootclient.isAlive()).thenReturn(true); when(rootclient.acquireMetaLookupPermit()).thenReturn(true); doAnswer(new Answer<Deferred<ArrayList<KeyValue>>>() { @Override public Deferred<ArrayList<KeyValue>> answer(InvocationOnMock invocation) throws Throwable { final Exception e = new UnknownProtocolException("", null); final DeferredGroupException dge = mock(DeferredGroupException.class); when(dge.getCause()).thenReturn(e); return Deferred.fromError(dge); } }).when(rootclient).getClosestRowBefore(any(RegionInfo.class), any(byte[].class), any(byte[].class), any(byte[].class)); doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) throws Throwable { final ArrayList<ArrayList<KeyValue>> rows = Lists.newArrayList(); rows.add(metaRow()); ((HBaseRpc) invocation.getArguments()[0]).getDeferred() .callback(new Response(0, rows, false, true)); return null; } }).when(rootclient).sendRpc(any(OpenScannerRequest.class)); final Deferred<Object> obj = Whitebox.invokeMethod(client, "locateRegion", get, TABLE, KEY); assertTrue(root_deferred != obj); final RegionClient rc = (RegionClient) obj.join(1); assertCounters(0, 2, 0); assertEquals(1, client2regions.size()); assertNotNull(client2regions.get(rc)); assertTrue((boolean) (Boolean) Whitebox.getInternalState(client, "scan_meta")); } @Test public void locateRegionInMetaSwitchToScanDiffError() throws Exception { clearCaches(); Whitebox.setInternalState(client, "has_root", false); Whitebox.setInternalState(client, "scan_meta", false); when(rootclient.isAlive()).thenReturn(true); when(rootclient.acquireMetaLookupPermit()).thenReturn(true); doAnswer(new Answer<Deferred<ArrayList<KeyValue>>>() { @Override public Deferred<ArrayList<KeyValue>> answer(InvocationOnMock invocation) throws Throwable { final Exception e = new TableNotFoundException(HBaseClient.ROOT); return Deferred.fromError(e); } }).when(rootclient).getClosestRowBefore(any(RegionInfo.class), any(byte[].class), any(byte[].class), any(byte[].class)); doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) throws Throwable { final ArrayList<ArrayList<KeyValue>> rows = Lists.newArrayList(); rows.add(metaRow()); ((HBaseRpc) invocation.getArguments()[0]).getDeferred() .callback(new Response(0, rows, false, true)); return null; } }).when(rootclient).sendRpc(any(OpenScannerRequest.class)); final Deferred<Object> obj = Whitebox.invokeMethod(client, "locateRegion", get, TABLE, KEY); assertTrue(root_deferred != obj); try { final RegionClient rc = (RegionClient) obj.join(1); fail("Expected TableNotFoundException"); } catch (TableNotFoundException e) { } assertCounters(0, 1, 0); assertEquals(0, client2regions.size()); assertFalse((boolean) (Boolean) Whitebox.getInternalState(client, "scan_meta")); } @Test public void locateRegionInMetaScanNoSuchTable() throws Exception { clearCaches(); Whitebox.setInternalState(client, "has_root", false); Whitebox.setInternalState(client, "scan_meta", true); when(rootclient.isAlive()).thenReturn(true); when(rootclient.acquireMetaLookupPermit()).thenReturn(true); doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) throws Throwable { ((HBaseRpc) invocation.getArguments()[0]).getDeferred() .callback(new Response(0, null, false, true)); return null; } }).when(rootclient).sendRpc(any(OpenScannerRequest.class)); final Deferred<Object> obj = Whitebox.invokeMethod(client, "locateRegion", get, TABLE, KEY); assertTrue(root_deferred != obj); try { obj.join(1); fail("Expected TableNotFoundException"); } catch (TableNotFoundException e) { } assertCounters(0, 1, 0); assertEquals(0, client2regions.size()); } @Test public void locateRegionInMetaScanException() throws Exception { clearCaches(); Whitebox.setInternalState(client, "has_root", false); Whitebox.setInternalState(client, "scan_meta", true); when(rootclient.isAlive()).thenReturn(true); when(rootclient.acquireMetaLookupPermit()).thenReturn(true); doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) throws Throwable { ((HBaseRpc) invocation.getArguments()[0]).getDeferred() .callback(new NonRecoverableException("Boo!")); return null; } }).when(rootclient).sendRpc(any(OpenScannerRequest.class)); final Deferred<Object> obj = Whitebox.invokeMethod(client, "locateRegion", get, TABLE, KEY); assertTrue(root_deferred != obj); try { obj.join(1); fail("Expected NonRecoverableException"); } catch (NonRecoverableException e) { } assertCounters(0, 1, 0); assertEquals(0, client2regions.size()); } // ---------- PARAMS ----------- @Test (expected = NullPointerException.class) public void locateRegionNullTable() throws Exception { Whitebox.invokeMethod(client, "locateRegion", get, (byte[])null, EMPTY_ARRAY); } @Test (expected = NullPointerException.class) public void locateRegionNullKey() throws Exception { Whitebox.invokeMethod(client, "locateRegion", get, TABLE, (byte[])null); } @Test public void locateRegionEmptyTable() throws Exception { final Deferred<Object> root_deferred = new Deferred<Object>(); when(zkclient.getDeferredRoot()).thenReturn(root_deferred); final Object obj = Whitebox.invokeMethod(client, "locateRegion", get, EMPTY_ARRAY, EMPTY_ARRAY); assertNotNull(obj); assertTrue(root_deferred == obj); } @Test public void locateRegionEmptyKey() throws Exception { final Deferred<Object> root_deferred = new Deferred<Object>(); when(zkclient.getDeferredRoot()).thenReturn(root_deferred); final Object obj = Whitebox.invokeMethod(client, "locateRegion", get, TABLE, EMPTY_ARRAY); assertNotNull(obj); assertTrue(root_deferred == obj); } // This one is OK because we only check the RPC we have an exception when // getting the closest row. @Test public void locateRegionNullRequest() throws Exception { final Deferred<Object> root_deferred = new Deferred<Object>(); when(zkclient.getDeferredRoot()).thenReturn(root_deferred); final Object obj = Whitebox.invokeMethod(client, "locateRegion", (HBaseRpc)null, TABLE, EMPTY_ARRAY); assertNotNull(obj); assertTrue(root_deferred == obj); } @Test (expected = NullPointerException.class) public void locateRegionNullRequestNPE() throws Exception { Whitebox.setInternalState(client, "rootregion", rootclient); when(rootclient.isAlive()).thenReturn(true); when(rootclient.getClosestRowBefore(any(RegionInfo.class), any(byte[].class), any(byte[].class), any(byte[].class))) .thenAnswer(new Answer<Deferred<ArrayList<KeyValue>>>() { @Override public Deferred<ArrayList<KeyValue>> answer(InvocationOnMock invocation) throws Throwable { return Deferred.<ArrayList<KeyValue>>fromError( new RegionOfflineException(EMPTY_ARRAY)); } }); final Deferred<Object> obj = Whitebox.invokeMethod(client, "locateRegion", (HBaseRpc)null, TABLE, EMPTY_ARRAY); obj.join(); } // ---------- HELPERS ----------- /** Simply sets the root region to the root client and mocks the alive call */ private void setLiveRootClient() { Whitebox.setInternalState(client, "rootregion", rootclient); when(rootclient.isAlive()).thenReturn(true); } /** * Helper to check our counters * @param root_lookups The number of root lookups expected * @param meta_lookups_with_permit The number of lookups with permits * @param meta_lookups_wo_permit The number of lookups without permits */ private void assertCounters(final int root_lookups, final int meta_lookups_with_permit, final int meta_lookups_wo_permit) { assertEquals(root_lookups, ((Counter)Whitebox.getInternalState(client, "root_lookups")).get()); assertEquals(meta_lookups_with_permit, ((Counter)Whitebox.getInternalState(client, "meta_lookups_with_permit")).get()); assertEquals(meta_lookups_wo_permit, ((Counter)Whitebox.getInternalState(client, "meta_lookups_wo_permit")).get()); } }
bsd-3-clause
edgarccohen/cnctool
gcodeparser/src/main/java/com/rvantwisk/gcodeparser/AbstractMachineValidator.java
3850
/* * Copyright (c) 2013, R. van Twisk * All rights reserved. * Licensed under the The BSD 3-Clause License; * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://opensource.org/licenses/BSD-3-Clause * * 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 aic-util nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.rvantwisk.gcodeparser; import com.rvantwisk.gcodeparser.exceptions.SimException; import java.util.Map; import java.util.Set; public abstract class AbstractMachineValidator { public abstract void preVerify(Map<String, ParsedWord> block) throws SimException; public abstract void postVerify(MachineStatus machineStatus) throws SimException; /** * Helper to find multiple words in teh same block * * @param block * @param enumClass * @param <T> * @return */ protected <T extends Enum<T>> boolean hasMultipleWords(Map<String, ParsedWord> block, Class<T> enumClass) { return wordCount(block, enumClass) > 1; } /** * Returns a word count within teh current block * This is usefull to find multiple the same words within a modal group in the current block * * @param block * @param enumClass * @param <T> * @return */ protected <T extends Enum<T>> int wordCount(Map<String, ParsedWord> block, Class<T> enumClass) { int wordCount = 0; T[] items = enumClass.getEnumConstants(); for (T item : items) { if (block.containsKey(item.toString())) { wordCount++; } } return wordCount; } /** * Returns true of the block contains any of hasAnyOfThis * @param block * @param hasAnyOfThis * @return */ protected boolean hasAny(Map<String, Object> block, final String[] hasAnyOfThis) { for (final String item : hasAnyOfThis) { if (block.containsKey(item)) { return true; } } return false; } /** * Returns true of the block contains any of hasAnyOfThis * @param block * @param hasAnyOfThis * @return */ protected boolean hasAny(Set<String> block, final String[] hasAnyOfThis) { for (final String item : hasAnyOfThis) { if (block.contains(item)) { return true; } } return false; } }
bsd-3-clause
aerofs/jssmp
src/main/java/com/aerofs/ssmp/SslHandlerFactory.java
357
/* * Copyright (c) 2015, Air Computing Inc. <oss@aerofs.com> * All rights reserved. */ package com.aerofs.ssmp; import org.jboss.netty.handler.ssl.SslHandler; import java.io.IOException; import java.security.GeneralSecurityException; public interface SslHandlerFactory { SslHandler newSslHandler() throws IOException, GeneralSecurityException; }
bsd-3-clause
jorenham/LifeTiles
lifetiles-core/src/main/java/nl/tudelft/lifetiles/core/util/IteratorUtils.java
603
package nl.tudelft.lifetiles.core.util; import java.util.Iterator; /** * Utilities for iterators and iterables. * * @author Joren Hammudoglu */ public final class IteratorUtils { /** * Uninstantiable. */ private IteratorUtils() { // noop } /** * Create an {@link Iterable} from an {@link Iterator}. * * @param iterator * the iterator * @param <T> * the type * @return the iterable */ public static <T> Iterable<T> toIterable(final Iterator<T> iterator) { return () -> iterator; } }
bsd-3-clause
ds-hwang/chromium-crosswalk
chrome/android/javatests/src/org/chromium/chrome/browser/tabmodel/RestoreMigrateTest.java
12956
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.tabmodel; import android.test.InstrumentationTestCase; import android.test.suitebuilder.annotation.SmallTest; import org.chromium.base.StreamUtil; import org.chromium.base.ThreadUtils; import org.chromium.base.annotations.SuppressFBWarnings; import org.chromium.base.metrics.RecordHistogram; import org.chromium.chrome.browser.TabState; import org.chromium.chrome.test.util.ApplicationData; import org.chromium.chrome.test.util.browser.tabmodel.MockTabModelSelector; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; /** * Test that migrating the old tab state folder structure to the new one works. */ public class RestoreMigrateTest extends InstrumentationTestCase { private void writeStateFile(final TabModelSelector selector, int index) throws IOException { byte[] data = ThreadUtils.runOnUiThreadBlockingNoException( new Callable<byte[]>() { @Override public byte[] call() throws Exception { return TabPersistentStore.serializeTabModelSelector(selector, null); } }); File f = TabPersistentStore.getStateDirectory( getInstrumentation().getTargetContext(), index); FileOutputStream fos = null; try { fos = new FileOutputStream(new File(f, TabPersistentStore.SAVED_STATE_FILE)); fos.write(data); } finally { StreamUtil.closeQuietly(fos); } } private int getMaxId(TabModelSelector selector) { int maxId = 0; for (TabList list : selector.getModels()) { for (int i = 0; i < list.getCount(); i++) { maxId = Math.max(maxId, list.getTabAt(i).getId()); } } return maxId; } /** * Test that normal migration of state files works. * @throws IOException * @throws InterruptedException * @throws ExecutionException */ @SuppressWarnings("unused") @SuppressFBWarnings("DLS_DEAD_LOCAL_STORE") @SmallTest public void testMigrateData() throws IOException, InterruptedException, ExecutionException { ApplicationData.clearAppData(getInstrumentation().getTargetContext()); // Write old state files. File filesDir = getInstrumentation().getTargetContext().getFilesDir(); File stateFile = new File(filesDir, TabPersistentStore.SAVED_STATE_FILE); File tab0 = new File(filesDir, TabState.SAVED_TAB_STATE_FILE_PREFIX + "0"); File tab1 = new File(filesDir, TabState.SAVED_TAB_STATE_FILE_PREFIX + "1"); File tab2 = new File(filesDir, TabState.SAVED_TAB_STATE_FILE_PREFIX_INCOGNITO + "2"); File tab3 = new File(filesDir, TabState.SAVED_TAB_STATE_FILE_PREFIX_INCOGNITO + "3"); assertTrue("Could not create state file", stateFile.createNewFile()); assertTrue("Could not create tab 0 file", tab0.createNewFile()); assertTrue("Could not create tab 1 file", tab1.createNewFile()); assertTrue("Could not create tab 2 file", tab2.createNewFile()); assertTrue("Could not create tab 3 file", tab3.createNewFile()); // Build the TabPersistentStore which will try to move the files. MockTabModelSelector selector = new MockTabModelSelector(0, 0, null); TabPersistentStore store = new TabPersistentStore(selector, 0, getInstrumentation().getTargetContext(), null, null); TabPersistentStore.waitForMigrationToFinish(); // Check that the files were moved. File newDir = TabPersistentStore.getStateDirectory(getInstrumentation().getTargetContext(), 0); File newStateFile = new File(newDir, TabPersistentStore.SAVED_STATE_FILE); File newTab0 = new File(newDir, TabState.SAVED_TAB_STATE_FILE_PREFIX + "0"); File newTab1 = new File(newDir, TabState.SAVED_TAB_STATE_FILE_PREFIX + "1"); File newTab2 = new File(newDir, TabState.SAVED_TAB_STATE_FILE_PREFIX_INCOGNITO + "2"); File newTab3 = new File(newDir, TabState.SAVED_TAB_STATE_FILE_PREFIX_INCOGNITO + "3"); assertTrue("Could not find new state file", newStateFile.exists()); assertTrue("Could not find new tab 0 file", newTab0.exists()); assertTrue("Could not find new tab 1 file", newTab1.exists()); assertTrue("Could not find new tab 2 file", newTab2.exists()); assertTrue("Could not find new tab 3 file", newTab3.exists()); assertFalse("Could still find old state file", stateFile.exists()); assertFalse("Could still find old tab 0 file", tab0.exists()); assertFalse("Could still find old tab 1 file", tab1.exists()); assertFalse("Could still find old tab 2 file", tab2.exists()); assertFalse("Could still find old tab 3 file", tab3.exists()); ApplicationData.clearAppData(getInstrumentation().getTargetContext()); } /** * Test that migration skips if it already has files in the new folder. * @throws IOException * @throws InterruptedException * @throws ExecutionException */ @SuppressWarnings("unused") @SuppressFBWarnings("DLS_DEAD_LOCAL_STORE") @SmallTest public void testSkipMigrateData() throws IOException, InterruptedException, ExecutionException { ApplicationData.clearAppData(getInstrumentation().getTargetContext()); // Write old state files. File filesDir = getInstrumentation().getTargetContext().getFilesDir(); File stateFile = new File(filesDir, TabPersistentStore.SAVED_STATE_FILE); File tab0 = new File(filesDir, TabState.SAVED_TAB_STATE_FILE_PREFIX + "0"); File tab1 = new File(filesDir, TabState.SAVED_TAB_STATE_FILE_PREFIX + "1"); File tab2 = new File(filesDir, TabState.SAVED_TAB_STATE_FILE_PREFIX_INCOGNITO + "2"); File tab3 = new File(filesDir, TabState.SAVED_TAB_STATE_FILE_PREFIX_INCOGNITO + "3"); assertTrue("Could not create state file", stateFile.createNewFile()); assertTrue("Could not create tab 0 file", tab0.createNewFile()); assertTrue("Could not create tab 1 file", tab1.createNewFile()); assertTrue("Could not create tab 2 file", tab2.createNewFile()); assertTrue("Could not create tab 3 file", tab3.createNewFile()); // Write new state files File newDir = TabPersistentStore.getStateDirectory(getInstrumentation().getTargetContext(), 0); File newStateFile = new File(newDir, TabPersistentStore.SAVED_STATE_FILE); File newTab4 = new File(newDir, TabState.SAVED_TAB_STATE_FILE_PREFIX + "4"); assertTrue("Could not create new tab 4 file", newTab4.createNewFile()); assertTrue("Could not create new state file", newStateFile.createNewFile()); // Build the TabPersistentStore which will try to move the files. MockTabModelSelector selector = new MockTabModelSelector(0, 0, null); TabPersistentStore store = new TabPersistentStore(selector, 0, getInstrumentation().getTargetContext(), null, null); TabPersistentStore.waitForMigrationToFinish(); assertTrue("Could not find new state file", newStateFile.exists()); assertTrue("Could not find new tab 4 file", newTab4.exists()); // Make sure the old files did not move File newTab0 = new File(newDir, TabState.SAVED_TAB_STATE_FILE_PREFIX + "0"); File newTab1 = new File(newDir, TabState.SAVED_TAB_STATE_FILE_PREFIX + "1"); File newTab2 = new File(newDir, TabState.SAVED_TAB_STATE_FILE_PREFIX_INCOGNITO + "2"); File newTab3 = new File(newDir, TabState.SAVED_TAB_STATE_FILE_PREFIX_INCOGNITO + "3"); assertFalse("Could find new tab 0 file", newTab0.exists()); assertFalse("Could find new tab 1 file", newTab1.exists()); assertFalse("Could find new tab 2 file", newTab2.exists()); assertFalse("Could find new tab 3 file", newTab3.exists()); ApplicationData.clearAppData(getInstrumentation().getTargetContext()); } /** * Test that the state file migration skips unrelated files. * @throws IOException * @throws InterruptedException * @throws ExecutionException */ @SuppressWarnings("unused") @SuppressFBWarnings("DLS_DEAD_LOCAL_STORE") @SmallTest public void testMigrationLeavesOtherFilesAlone() throws IOException, InterruptedException, ExecutionException { ApplicationData.clearAppData(getInstrumentation().getTargetContext()); // Write old state files. File filesDir = getInstrumentation().getTargetContext().getFilesDir(); File stateFile = new File(filesDir, TabPersistentStore.SAVED_STATE_FILE); File tab0 = new File(filesDir, TabState.SAVED_TAB_STATE_FILE_PREFIX + "0"); File otherFile = new File(filesDir, "other.file"); assertTrue("Could not create state file", stateFile.createNewFile()); assertTrue("Could not create tab 0 file", tab0.createNewFile()); assertTrue("Could not create other file", otherFile.createNewFile()); // Build the TabPersistentStore which will try to move the files. MockTabModelSelector selector = new MockTabModelSelector(0, 0, null); TabPersistentStore store = new TabPersistentStore(selector, 0, getInstrumentation().getTargetContext(), null, null); TabPersistentStore.waitForMigrationToFinish(); assertFalse("Could still find old state file", stateFile.exists()); assertFalse("Could still find old tab 0 file", tab0.exists()); assertTrue("Could not find other file", otherFile.exists()); // Check that the files were moved. File newDir = TabPersistentStore.getStateDirectory(getInstrumentation().getTargetContext(), 0); File newStateFile = new File(newDir, TabPersistentStore.SAVED_STATE_FILE); File newTab0 = new File(newDir, TabState.SAVED_TAB_STATE_FILE_PREFIX + "0"); File newOtherFile = new File(newDir, "other.file"); assertTrue("Could not find new state file", newStateFile.exists()); assertTrue("Could not find new tab 0 file", newTab0.exists()); assertFalse("Could find new other file", newOtherFile.exists()); ApplicationData.clearAppData(getInstrumentation().getTargetContext()); } /** * Tests that the max id returned is the max of all of the tab models. * @throws IOException */ @SmallTest public void testFindsMaxIdProperly() throws IOException { TabModelSelector selector0 = new MockTabModelSelector(1, 1, null); TabModelSelector selector1 = new MockTabModelSelector(1, 1, null); writeStateFile(selector0, 0); writeStateFile(selector1, 1); TabModelSelector selectorIn = new MockTabModelSelector(0, 0, null); TabPersistentStore storeIn = new TabPersistentStore(selectorIn, 0, getInstrumentation().getTargetContext(), null, null); int maxId = Math.max(getMaxId(selector0), getMaxId(selector1)); RecordHistogram.disableForTests(); assertEquals("Invalid next id", maxId + 1, storeIn.loadStateInternal()); } /** * Tests that each model loads the subset of tabs it is responsible for. In this case, just * check that the model has the expected number of tabs to load. Since each model is loading * a different number of tabs we can tell if they are each attempting to load their specific * set. * @throws IOException */ @SmallTest public void testOnlyLoadsSingleModel() throws IOException { TabModelSelector selector0 = new MockTabModelSelector(3, 3, null); TabModelSelector selector1 = new MockTabModelSelector(2, 1, null); writeStateFile(selector0, 0); writeStateFile(selector1, 1); TabModelSelector selectorIn0 = new MockTabModelSelector(0, 0, null); TabModelSelector selectorIn1 = new MockTabModelSelector(0, 0, null); TabPersistentStore storeIn0 = new TabPersistentStore(selectorIn0, 0, getInstrumentation().getTargetContext(), null, null); TabPersistentStore storeIn1 = new TabPersistentStore(selectorIn1, 1, getInstrumentation().getTargetContext(), null, null); RecordHistogram.disableForTests(); storeIn0.loadStateInternal(); storeIn1.loadStateInternal(); assertEquals("Unexpected number of tabs to load", 6, storeIn0.getRestoredTabCount()); assertEquals("Unexpected number of tabst o load", 3, storeIn1.getRestoredTabCount()); } }
bsd-3-clause
ksclarke/basex
basex-api/src/main/java/org/basex/http/restxq/RestXqModule.java
3641
package org.basex.http.restxq; import static org.basex.query.QueryError.*; import static org.basex.util.Token.*; import java.io.*; import java.util.*; import org.basex.core.*; import org.basex.http.*; import org.basex.io.*; import org.basex.query.*; import org.basex.query.func.*; /** * This class caches information on a single XQuery module with RESTXQ annotations. * * @author BaseX Team 2005-15, BSD License * @author Christian Gruen */ final class RestXqModule { /** Supported methods. */ private final ArrayList<RestXqFunction> functions = new ArrayList<>(); /** File reference. */ private final IOFile file; /** Parsing timestamp. */ private long time; /** * Constructor. * @param file xquery file */ RestXqModule(final IOFile file) { this.file = file; time = file.timeStamp(); } /** * Checks the module for RESTXQ annotations. * @param http HTTP context * @return {@code true} if module contains relevant annotations * @throws Exception exception (including unexpected ones) */ boolean parse(final HTTPContext http) throws Exception { functions.clear(); // loop through all functions final Context ctx = http.context(false); try(final QueryContext qc = qc(ctx)) { // loop through all functions final String name = file.name(); for(final StaticFunc uf : qc.funcs.funcs()) { // only add functions that are defined in the same module (file) if(name.equals(new IOFile(uf.info.path()).name())) { final RestXqFunction rxf = new RestXqFunction(uf, qc, this); if(rxf.parse(ctx)) functions.add(rxf); } } } return !functions.isEmpty(); } /** * Checks if the timestamp is still up-to-date. * @return result of check */ boolean uptodate() { return time == file.timeStamp(); } /** * Updates the timestamp. */ void touch() { time = file.timeStamp(); } /** * Returns all functions. * @return functions */ ArrayList<RestXqFunction> functions() { return functions; } /** * Processes the HTTP request. * @param http HTTP context * @param func function to be processed * @param error optional error reference * @throws Exception exception */ void process(final HTTPContext http, final RestXqFunction func, final QueryException error) throws Exception { // create new XQuery instance final Context ctx = http.context(false); try(final QueryContext qc = qc(ctx)) { final RestXqFunction rxf = new RestXqFunction(find(qc, func.function), qc, this); rxf.parse(ctx); RestXqResponse.create(rxf, qc, http, error); } } // PRIVATE METHODS ==================================================================== /** * Retrieves a query context for the given module. * @param ctx database context * @return query context * @throws Exception exception */ private QueryContext qc(final Context ctx) throws Exception { final QueryContext qc = new QueryContext(ctx); try { qc.parse(string(file.read()), file.path(), null); return qc; } catch(final IOException ex) { // may be triggered when reading the file throw IOERR_X.get(null, ex); } } /** * Returns the specified function from the given query context. * @param qctx query context. * @param func function to be found * @return function */ private static StaticFunc find(final QueryContext qctx, final StaticFunc func) { for(final StaticFunc sf : qctx.funcs.funcs()) { if(func.info.equals(sf.info)) return sf; } return null; } }
bsd-3-clause
UrielCh/ovh-java-sdk
ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/complextype/OvhRange.java
269
package net.minidev.ovh.api.complextype; /** * Start and end points (inclusive) of a range */ public class OvhRange<T> { /** * Start point of the range * * canBeNull */ public T from; /** * End point of the range * * canBeNull */ public T to; }
bsd-3-clause
delkyd/Oracle-Cloud
PaaS_SaaS_Accelerator_RESTFulFacade/XJC_Beans/src/com/oracle/xmlns/apps/marketing/leadmgmt/leads/leadservice/types/ScoreLead.java
1639
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2013.10.24 at 02:08:17 PM BST // package com.oracle.xmlns.apps.marketing.leadmgmt.leads.leadservice.types; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="leadId" type="{http://www.w3.org/2001/XMLSchema}long"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "leadId" }) @XmlRootElement(name = "scoreLead") public class ScoreLead { protected long leadId; /** * Gets the value of the leadId property. * */ public long getLeadId() { return leadId; } /** * Sets the value of the leadId property. * */ public void setLeadId(long value) { this.leadId = value; } }
bsd-3-clause
tuura/workcraft
workcraft/DfsPlugin/src/org/workcraft/plugins/dfs/tools/Cycle.java
5972
package org.workcraft.plugins.dfs.tools; import org.workcraft.dom.visual.VisualComponent; import org.workcraft.dom.visual.VisualNode; import org.workcraft.plugins.dfs.*; import java.util.*; public class Cycle implements Comparable<Cycle> { // Right arrow symbol in UTF-8 encoding (avoid inserting UTF symbols directly in the source code). public static final String RIGHT_ARROW_SYMBOL = Character.toString((char) 0x2192); public final VisualDfs dfs; public final LinkedHashSet<VisualDelayComponent> components; public final int tokenCount; public final double totalDelay; public final double throughput; public final double minDelay; public final double maxDelay; public Cycle(VisualDfs dfs, LinkedHashSet<VisualDelayComponent> components) { this.dfs = dfs; this.components = components; this.tokenCount = getTokenCount(); this.totalDelay = getTotalDelay(); this.throughput = getThroughput(); this.minDelay = getMinDelay(); this.maxDelay = getMaxDelay(); } private int getTokenCount() { Integer result = 0; boolean spreadTokenDetected = false; boolean isMarkedFirstRegister = false; boolean isMarkedLastRegister = false; boolean isFirstRegister = true; for (VisualComponent c : components) { if (c instanceof VisualRegister || c instanceof VisualBinaryRegister) { boolean hasToken = false; if (c instanceof VisualRegister) { hasToken = ((VisualRegister) c).getReferencedComponent().isMarked(); } if (c instanceof VisualBinaryRegister) { BinaryRegister ref = ((VisualBinaryRegister) c).getReferencedComponent(); hasToken = ref.isTrueMarked() || ref.isFalseMarked(); } if (!hasToken) { spreadTokenDetected = false; } else { if (!spreadTokenDetected) { result++; spreadTokenDetected = true; } } if (isFirstRegister) { isMarkedFirstRegister = hasToken; isFirstRegister = false; } isMarkedLastRegister = hasToken; } } if (isMarkedFirstRegister && isMarkedLastRegister && (result > 1)) { result--; } return result; } private double getTotalDelay() { double result = 0.0; for (VisualDelayComponent component : components) { result += getEffectiveDelay(component); } return result; } private Set<VisualPushRegister> getPushPreset(VisualNode node) { HashSet<VisualPushRegister> result = new HashSet<>(); HashSet<VisualNode> visited = new HashSet<>(); Queue<VisualNode> queue = new LinkedList<>(); queue.add(node); while (!queue.isEmpty()) { VisualNode cur = queue.remove(); if (visited.contains(cur) || !components.contains(cur)) continue; visited.add(cur); for (VisualNode pred : dfs.getPreset(cur)) { if (!(pred instanceof VisualComponent)) continue; if (pred instanceof VisualPushRegister) { result.add((VisualPushRegister) pred); } else if (!(pred instanceof VisualPopRegister)) { queue.add(pred); } } } return result; } private double getMinDelay() { double result = 0.0; boolean first = true; for (VisualDelayComponent component : components) { double delay = getEffectiveDelay(component); if (first || delay < result) { result = delay; first = false; } } return result; } private double getMaxDelay() { double result = 0.0; boolean first = true; for (VisualDelayComponent component : components) { double delay = getEffectiveDelay(component); if (first || delay > result) { result = delay; first = false; } } return result; } private Double getThroughput() { double delay = getTotalDelay(); if (delay == 0.0) { return Double.MAX_VALUE; } return getTokenCount() / delay; } public final double getEffectiveDelay(VisualDelayComponent component) { HashSet<VisualControlRegister> controls = new HashSet<>(); for (VisualPushRegister push : getPushPreset(component)) { controls.addAll(dfs.getPreset(push, VisualControlRegister.class)); } double probability = 1.0; for (VisualControlRegister control : controls) { probability *= control.getReferencedComponent().getProbability(); } double delay = ((MathDelayNode) component.getReferencedComponent()).getDelay(); return delay * probability; } @Override public int compareTo(Cycle other) { double thisThroughput = this.getThroughput(); double otherThroughput = other.getThroughput(); if (thisThroughput > otherThroughput) { return 1; } else if (thisThroughput < otherThroughput) { return -1; } return 0; } @Override public String toString() { String result = ""; if ((components != null) && (dfs != null)) { for (VisualDelayComponent component : components) { if (result.length() > 0) { result += RIGHT_ARROW_SYMBOL; } result += dfs.getMathModel().getNodeReference(component.getReferencedComponent()); } } return result; } }
mit
facebook/infer
infer/models/java/src/java/util/zip/GZIPInputStream.java
700
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package java.util.zip; import com.facebook.infer.builtins.InferBuiltins; import com.facebook.infer.builtins.InferUndefined; import java.io.IOException; import java.io.InputStream; public class GZIPInputStream { public GZIPInputStream(InputStream in) throws IOException { InferUndefined.can_throw_ioexception_void(); InferBuiltins.__set_mem_attribute(in); InferBuiltins.__set_file_attribute(this); } public GZIPInputStream(InputStream in, int size) throws IOException { this(in); } }
mit
open-keychain/spongycastle
core/src/main/java/org/spongycastle/math/ec/custom/sec/SecT131Field.java
8704
package org.spongycastle.math.ec.custom.sec; import java.math.BigInteger; import org.spongycastle.math.raw.Interleave; import org.spongycastle.math.raw.Nat; import org.spongycastle.math.raw.Nat192; public class SecT131Field { private static final long M03 = -1L >>> 61; private static final long M44 = -1L >>> 20; private static final long[] ROOT_Z = new long[]{ 0x26BC4D789AF13523L, 0x26BC4D789AF135E2L, 0x6L }; public static void add(long[] x, long[] y, long[] z) { z[0] = x[0] ^ y[0]; z[1] = x[1] ^ y[1]; z[2] = x[2] ^ y[2]; } public static void addExt(long[] xx, long[] yy, long[] zz) { zz[0] = xx[0] ^ yy[0]; zz[1] = xx[1] ^ yy[1]; zz[2] = xx[2] ^ yy[2]; zz[3] = xx[3] ^ yy[3]; zz[4] = xx[4] ^ yy[4]; } public static void addOne(long[] x, long[] z) { z[0] = x[0] ^ 1L; z[1] = x[1]; z[2] = x[2]; } public static long[] fromBigInteger(BigInteger x) { long[] z = Nat192.fromBigInteger64(x); reduce61(z, 0); return z; } public static void invert(long[] x, long[] z) { if (Nat192.isZero64(x)) { throw new IllegalStateException(); } // Itoh-Tsujii inversion long[] t0 = Nat192.create64(); long[] t1 = Nat192.create64(); square(x, t0); multiply(t0, x, t0); squareN(t0, 2, t1); multiply(t1, t0, t1); squareN(t1, 4, t0); multiply(t0, t1, t0); squareN(t0, 8, t1); multiply(t1, t0, t1); squareN(t1, 16, t0); multiply(t0, t1, t0); squareN(t0, 32, t1); multiply(t1, t0, t1); square(t1, t1); multiply(t1, x, t1); squareN(t1, 65, t0); multiply(t0, t1, t0); square(t0, z); } public static void multiply(long[] x, long[] y, long[] z) { long[] tt = Nat192.createExt64(); implMultiply(x, y, tt); reduce(tt, z); } public static void multiplyAddToExt(long[] x, long[] y, long[] zz) { long[] tt = Nat192.createExt64(); implMultiply(x, y, tt); addExt(zz, tt, zz); } public static void reduce(long[] xx, long[] z) { long x0 = xx[0], x1 = xx[1], x2 = xx[2], x3 = xx[3], x4 = xx[4]; x1 ^= (x4 << 61) ^ (x4 << 63); x2 ^= (x4 >>> 3) ^ (x4 >>> 1) ^ x4 ^ (x4 << 5); x3 ^= (x4 >>> 59); x0 ^= (x3 << 61) ^ (x3 << 63); x1 ^= (x3 >>> 3) ^ (x3 >>> 1) ^ x3 ^ (x3 << 5); x2 ^= (x3 >>> 59); long t = x2 >>> 3; z[0] = x0 ^ t ^ (t << 2) ^ (t << 3) ^ (t << 8); z[1] = x1 ^ (t >>> 56); z[2] = x2 & M03; } public static void reduce61(long[] z, int zOff) { long z2 = z[zOff + 2], t = z2 >>> 3; z[zOff ] ^= t ^ (t << 2) ^ (t << 3) ^ (t << 8); z[zOff + 1] ^= (t >>> 56); z[zOff + 2] = z2 & M03; } public static void sqrt(long[] x, long[] z) { long[] odd = Nat192.create64(); long u0, u1; u0 = Interleave.unshuffle(x[0]); u1 = Interleave.unshuffle(x[1]); long e0 = (u0 & 0x00000000FFFFFFFFL) | (u1 << 32); odd[0] = (u0 >>> 32) | (u1 & 0xFFFFFFFF00000000L); u0 = Interleave.unshuffle(x[2]); long e1 = (u0 & 0x00000000FFFFFFFFL); odd[1] = (u0 >>> 32); multiply(odd, ROOT_Z, z); z[0] ^= e0; z[1] ^= e1; } public static void square(long[] x, long[] z) { long[] tt = Nat.create64(5); implSquare(x, tt); reduce(tt, z); } public static void squareAddToExt(long[] x, long[] zz) { long[] tt = Nat.create64(5); implSquare(x, tt); addExt(zz, tt, zz); } public static void squareN(long[] x, int n, long[] z) { // assert n > 0; long[] tt = Nat.create64(5); implSquare(x, tt); reduce(tt, z); while (--n > 0) { implSquare(z, tt); reduce(tt, z); } } public static int trace(long[] x) { // Non-zero-trace bits: 0, 123, 129 return (int)(x[0] ^ (x[1] >>> 59) ^ (x[2] >>> 1)) & 1; } protected static void implCompactExt(long[] zz) { long z0 = zz[0], z1 = zz[1], z2 = zz[2], z3 = zz[3], z4 = zz[4], z5 = zz[5]; zz[0] = z0 ^ (z1 << 44); zz[1] = (z1 >>> 20) ^ (z2 << 24); zz[2] = (z2 >>> 40) ^ (z3 << 4) ^ (z4 << 48); zz[3] = (z3 >>> 60) ^ (z5 << 28) ^ (z4 >>> 16); zz[4] = (z5 >>> 36); zz[5] = 0; } protected static void implMultiply(long[] x, long[] y, long[] zz) { /* * "Five-way recursion" as described in "Batch binary Edwards", Daniel J. Bernstein. */ long f0 = x[0], f1 = x[1], f2 = x[2]; f2 = ((f1 >>> 24) ^ (f2 << 40)) & M44; f1 = ((f0 >>> 44) ^ (f1 << 20)) & M44; f0 &= M44; long g0 = y[0], g1 = y[1], g2 = y[2]; g2 = ((g1 >>> 24) ^ (g2 << 40)) & M44; g1 = ((g0 >>> 44) ^ (g1 << 20)) & M44; g0 &= M44; long[] H = new long[10]; implMulw(f0, g0, H, 0); // H(0) 44/43 bits implMulw(f2, g2, H, 2); // H(INF) 44/41 bits long t0 = f0 ^ f1 ^ f2; long t1 = g0 ^ g1 ^ g2; implMulw(t0, t1, H, 4); // H(1) 44/43 bits long t2 = (f1 << 1) ^ (f2 << 2); long t3 = (g1 << 1) ^ (g2 << 2); implMulw(f0 ^ t2, g0 ^ t3, H, 6); // H(t) 44/45 bits implMulw(t0 ^ t2, t1 ^ t3, H, 8); // H(t + 1) 44/45 bits long t4 = H[6] ^ H[8]; long t5 = H[7] ^ H[9]; // assert t5 >>> 44 == 0; // Calculate V long v0 = (t4 << 1) ^ H[6]; long v1 = t4 ^ (t5 << 1) ^ H[7]; long v2 = t5; // Calculate U long u0 = H[0]; long u1 = H[1] ^ H[0] ^ H[4]; long u2 = H[1] ^ H[5]; // Calculate W long w0 = u0 ^ v0 ^ (H[2] << 4) ^ (H[2] << 1); long w1 = u1 ^ v1 ^ (H[3] << 4) ^ (H[3] << 1); long w2 = u2 ^ v2; // Propagate carries w1 ^= (w0 >>> 44); w0 &= M44; w2 ^= (w1 >>> 44); w1 &= M44; // assert (w0 & 1L) == 0; // Divide W by t w0 = (w0 >>> 1) ^ ((w1 & 1L) << 43); w1 = (w1 >>> 1) ^ ((w2 & 1L) << 43); w2 = (w2 >>> 1); // Divide W by (t + 1) w0 ^= (w0 << 1); w0 ^= (w0 << 2); w0 ^= (w0 << 4); w0 ^= (w0 << 8); w0 ^= (w0 << 16); w0 ^= (w0 << 32); w0 &= M44; w1 ^= (w0 >>> 43); w1 ^= (w1 << 1); w1 ^= (w1 << 2); w1 ^= (w1 << 4); w1 ^= (w1 << 8); w1 ^= (w1 << 16); w1 ^= (w1 << 32); w1 &= M44; w2 ^= (w1 >>> 43); w2 ^= (w2 << 1); w2 ^= (w2 << 2); w2 ^= (w2 << 4); w2 ^= (w2 << 8); w2 ^= (w2 << 16); w2 ^= (w2 << 32); // assert w2 >>> 42 == 0; zz[0] = u0; zz[1] = u1 ^ w0 ^ H[2]; zz[2] = u2 ^ w1 ^ w0 ^ H[3]; zz[3] = w2 ^ w1; zz[4] = w2 ^ H[2]; zz[5] = H[3]; implCompactExt(zz); } protected static void implMulw(long x, long y, long[] z, int zOff) { // assert x >>> 45 == 0; // assert y >>> 45 == 0; long[] u = new long[8]; // u[0] = 0; u[1] = y; u[2] = u[1] << 1; u[3] = u[2] ^ y; u[4] = u[2] << 1; u[5] = u[4] ^ y; u[6] = u[3] << 1; u[7] = u[6] ^ y; int j = (int)x; long g, h = 0, l = u[j & 7] ^ u[(j >>> 3) & 7] << 3 ^ u[(j >>> 6) & 7] << 6; int k = 33; do { j = (int)(x >>> k); g = u[j & 7] ^ u[(j >>> 3) & 7] << 3 ^ u[(j >>> 6) & 7] << 6 ^ u[(j >>> 9) & 7] << 9; l ^= (g << k); h ^= (g >>> -k); } while ((k -= 12) > 0); // assert h >>> 25 == 0; z[zOff ] = l & M44; z[zOff + 1] = (l >>> 44) ^ (h << 20); } protected static void implSquare(long[] x, long[] zz) { Interleave.expand64To128(x[0], zz, 0); Interleave.expand64To128(x[1], zz, 2); zz[4] = Interleave.expand8to16((int)x[2]) & 0xFFFFFFFFL; } }
mit
selfpoised/6.830
6.830-lab5/test/simpledb/HeapFileWriteTest.java
1441
package simpledb; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; import junit.framework.JUnit4TestAdapter; public class HeapFileWriteTest extends TestUtil.CreateHeapFile { private TransactionId tid; /** * Set up initial resources for each unit test. */ @Before public void setUp() throws Exception { super.setUp(); tid = new TransactionId(); } @After public void tearDown() throws Exception { Database.getBufferPool().transactionComplete(tid); } /** * Unit test for HeapFile.addTuple() */ @Test public void addTuple() throws Exception { // we should be able to add 504 tuples on an empty page. for (int i = 0; i < 504; ++i) { empty.insertTuple(tid, Utility.getHeapTuple(i, 2)); assertEquals(1, empty.numPages()); } // the next 512 additions should live on a new page for (int i = 0; i < 504; ++i) { empty.insertTuple(tid, Utility.getHeapTuple(i, 2)); assertEquals(2, empty.numPages()); } // and one more, just for fun... empty.insertTuple(tid, Utility.getHeapTuple(0, 2)); assertEquals(3, empty.numPages()); } /** * JUnit suite target */ public static junit.framework.Test suite() { return new JUnit4TestAdapter(HeapFileWriteTest.class); } }
mit
akochurov/mxcache
mxcache-runtime/src/main/java/com/maxifier/mxcache/caches/CharacterObjectCalculatable.java
464
/* * Copyright (c) 2008-2014 Maxifier Ltd. All Rights Reserved. */ package com.maxifier.mxcache.caches; /** * THIS IS GENERATED CLASS! DON'T EDIT IT MANUALLY! * * GENERATED FROM P2PCalculatable.template * * @author Andrey Yakoushin (andrey.yakoushin@maxifier.com) * @author Alexander Kochurov (alexander.kochurov@maxifier.com) */ public interface CharacterObjectCalculatable<F> extends Calculable { F calculate(Object owner, char o); }
mit
zzhoujay/RichText
richtext/src/main/java/com/zzhoujay/richtext/callback/ImageLoadNotify.java
242
package com.zzhoujay.richtext.callback; /** * Created by zhou on 16-10-24. * Image Load Notify */ public interface ImageLoadNotify { /** * 图片加载完成 * * @param from Object */ void done(Object from); }
mit
changjiashuai/JelloToggle
app/src/main/java/me/fichardu/jellotoggle/EaseOutElasticInterpolator.java
1628
package me.fichardu.jellotoggle; import android.animation.TimeInterpolator; /** * The MIT License (MIT) * * Copyright (c) 2015 fichardu * * 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 NON INFRINGEMENT. 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 EaseOutElasticInterpolator implements TimeInterpolator{ @Override public float getInterpolation(float input) { if (input == 0f) { return 0f; } if (input == 1.0f) { return 1.0f; } float p = 0.3f; float s = p / 4; return (float) (Math.pow(2, -10*input) * Math.sin((input - s)*(2*Math.PI/p)) + 1); } }
mit
navalev/azure-sdk-for-java
sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/RecognizePrintedTextInStreamOptionalParameter.java
2121
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.cognitiveservices.vision.computervision.models; /** * The RecognizePrintedTextInStreamOptionalParameter model. */ public class RecognizePrintedTextInStreamOptionalParameter { /** * The BCP-47 language code of the text to be detected in the image. The * default value is 'unk'. Possible values include: 'unk', 'zh-Hans', * 'zh-Hant', 'cs', 'da', 'nl', 'en', 'fi', 'fr', 'de', 'el', 'hu', 'it', * 'ja', 'ko', 'nb', 'pl', 'pt', 'ru', 'es', 'sv', 'tr', 'ar', 'ro', * 'sr-Cyrl', 'sr-Latn', 'sk'. */ private OcrLanguages language; /** * Gets or sets the preferred language for the response. */ private String thisclientacceptLanguage; /** * Get the language value. * * @return the language value */ public OcrLanguages language() { return this.language; } /** * Set the language value. * * @param language the language value to set * @return the RecognizePrintedTextInStreamOptionalParameter object itself. */ public RecognizePrintedTextInStreamOptionalParameter withLanguage(OcrLanguages language) { this.language = language; return this; } /** * Get the thisclientacceptLanguage value. * * @return the thisclientacceptLanguage value */ public String thisclientacceptLanguage() { return this.thisclientacceptLanguage; } /** * Set the thisclientacceptLanguage value. * * @param thisclientacceptLanguage the thisclientacceptLanguage value to set * @return the RecognizePrintedTextInStreamOptionalParameter object itself. */ public RecognizePrintedTextInStreamOptionalParameter withThisclientacceptLanguage(String thisclientacceptLanguage) { this.thisclientacceptLanguage = thisclientacceptLanguage; return this; } }
mit
selvasingh/azure-sdk-for-java
sdk/containerregistry/mgmt-v2017_10_01/src/main/java/com/microsoft/azure/management/containerregistry/v2017_10_01/RegistryUsageUnit.java
1322
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.containerregistry.v2017_10_01; import java.util.Collection; import com.fasterxml.jackson.annotation.JsonCreator; import com.microsoft.rest.ExpandableStringEnum; /** * Defines values for RegistryUsageUnit. */ public final class RegistryUsageUnit extends ExpandableStringEnum<RegistryUsageUnit> { /** Static value Count for RegistryUsageUnit. */ public static final RegistryUsageUnit COUNT = fromString("Count"); /** Static value Bytes for RegistryUsageUnit. */ public static final RegistryUsageUnit BYTES = fromString("Bytes"); /** * Creates or finds a RegistryUsageUnit from its string representation. * @param name a name to look for * @return the corresponding RegistryUsageUnit */ @JsonCreator public static RegistryUsageUnit fromString(String name) { return fromString(name, RegistryUsageUnit.class); } /** * @return known RegistryUsageUnit values */ public static Collection<RegistryUsageUnit> values() { return values(RegistryUsageUnit.class); } }
mit
witcxc/jedis
src/main/java/redis/clients/jedis/ScanParams.java
1057
package redis.clients.jedis; import static redis.clients.jedis.Protocol.Keyword.COUNT; import static redis.clients.jedis.Protocol.Keyword.MATCH; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import redis.clients.util.SafeEncoder; public class ScanParams { private List<byte[]> params = new ArrayList<byte[]>(); public final static String SCAN_POINTER_START = String.valueOf(0); public final static byte[] SCAN_POINTER_START_BINARY = SafeEncoder.encode(SCAN_POINTER_START); public ScanParams match(final byte[] pattern) { params.add(MATCH.raw); params.add(pattern); return this; } public ScanParams match(final String pattern) { params.add(MATCH.raw); params.add(SafeEncoder.encode(pattern)); return this; } public ScanParams count(final int count) { params.add(COUNT.raw); params.add(Protocol.toByteArray(count)); return this; } public Collection<byte[]> getParams() { return Collections.unmodifiableCollection(params); } }
mit
balazspete/NaturalComputing
ColoursEvaluatorNNTrainer/src/org/encog/engine/opencl/kernels/KernelNetworkTrain.java
13720
/* * Encog(tm) Core v2.5 - Java Version * http://www.heatonresearch.com/encog/ * http://code.google.com/p/encog-java/ * Copyright 2008-2010 Heaton Research, 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. * * For more information on Heaton Research copyrights, licenses * and trademarks visit: * http://www.heatonresearch.com/copyright */ package org.encog.engine.opencl.kernels; import java.util.Map; import org.encog.engine.data.BasicEngineData; import org.encog.engine.data.EngineData; import org.encog.engine.data.EngineIndexableSet; import org.encog.engine.network.activation.ActivationFunction; import org.encog.engine.network.flat.FlatNetwork; import org.encog.engine.network.train.prop.OpenCLTrainingProfile; import org.encog.engine.opencl.EncogCLDevice; import org.encog.engine.opencl.EncogCLQueue; import org.encog.engine.opencl.exceptions.OpenCLError; import org.encog.engine.opencl.exceptions.OutOfOpenCLResources; import org.encog.engine.util.EngineArray; import org.encog.engine.util.ResourceLoader; import org.jocl.CLException; import org.jocl.cl_mem; /** * An OpenCL kernel that is designed to calculate gradients and help train a * neural network. */ public class KernelNetworkTrain extends EncogKernel { /** * The input count. */ public static final int PARRAY_INPUT_COUNT = 0; /** * The output count. */ public static final int PARRAY_OUTPUT_COUNT = 1; /** * The layer count. */ public static final int PARRAY_LAYER_COUNT = 2; /** * Are we learning? 0=no, 1 =yes. */ public static final int PARRAY_LEARN = 3; /** * What is the starting index to train at. */ public static final int PARRAY_START = 4; /** * Items to train per call. */ public static final int PARRAY_ITEMS_PER = 5; /** * Items to train per call. */ public static final int PARRAY_ITERATIONS = 6; /** * A buffer to communicate weights to the kernel. */ private cl_mem weightInArrayBuffer; /** * A buffer to communicate weights from the kernel. */ private cl_mem weightOutArrayBuffer; /** * A buffer to hold the layer index. */ private cl_mem layerIndexBuffer; /** * A buffer to hold the layer counts. */ private cl_mem layerCountBuffer; /** * A buffer to hold the layer feed counts. */ private cl_mem layerFeedCountBuffer; /** * A buffer to hold the weight indexes. */ private cl_mem weightIndexBuffer; /** * A buffer to hold the activations for each of the layers. */ private cl_mem activationTypeBuffer; /** * The temp data in buffer. Temp data that is used while training. */ private cl_mem tempDataInBuffer; /** * The temp data out buffer. Temp data that is used while training. */ private cl_mem tempDataOutBuffer; /** * The weight and bias array for the network. */ private final float[] weightInArray; /** * The weight output array. */ private final float[] weightOutArray; /** * The temp data array. Temp data that is used while training. */ private float[] tempDataArray; /** * The size of all layer deltas. */ private int layerDeltaSize; /** * An array to hold the input to the neural network. */ private final float[] inputArray; /** * An array to hold the ideal values expected from the network. */ private final float[] idealArray; /** * The input buffer. */ private cl_mem inputBuffer; /** * The ideal buffer. */ private cl_mem idealBuffer; /** * Holds parameters passed to the kernel. */ private final int[] paramArray; /** * A buffer to hold the parameters. */ private cl_mem paramBuffer; /** * A buffer to hold the errors. */ private cl_mem errorBuffer; /** * A buffer to hold the gradients. */ private cl_mem gradientOutBuffer; /** * The gradient input buffer. */ private cl_mem gradientInBuffer; /** * The network to train. */ private final FlatNetwork flat; /** * The training errors for this workload. */ private float[] errors; /** * The gradients. */ private final float[] gradients; /** * The training data to use. */ private final EngineIndexableSet training; /** * The device to train with. */ private final EncogCLDevice device; /** * The length of the training data. */ private final int trainingLength; /** * Construct a kernel to train the network. * * @param device * The OpenCL device to use. * @param flat * The network to train. * @param training * The training data. * @param tempDataSize * How much temp data. */ public KernelNetworkTrain(final EncogCLDevice device, final FlatNetwork flat, final EngineIndexableSet training, final int tempDataSize) { super(device, "org/encog/engine/resources/KernelNetTrain.txt", "NetworkTrain"); this.training = training; this.trainingLength = (int) this.training.getRecordCount(); this.device = device; this.flat = flat; this.weightInArray = new float[flat.getWeights().length]; this.weightOutArray = new float[flat.getWeights().length]; this.tempDataArray = new float[tempDataSize]; this.gradients = new float[flat.getWeights().length]; this.layerDeltaSize = 0; for (int i = 0; i < flat.getLayerCounts().length; i++) { this.layerDeltaSize += flat.getLayerCounts()[i]; } final int inputSize = flat.getInputCount(); final int idealSize = flat.getOutputCount(); this.inputArray = new float[inputSize * this.trainingLength]; this.idealArray = new float[idealSize * this.trainingLength]; this.paramArray = new int[10]; final EngineData pair = BasicEngineData.createPair( flat.getInputCount(), flat.getOutputCount()); int inputIndex = 0; int idealIndex = 0; for (int i = 0; i < this.trainingLength; i++) { training.getRecord(i, pair); for (int col = 0; col < flat.getInputCount(); col++) { this.inputArray[inputIndex++] = (float) pair.getInputArray()[col]; } for (int col = 0; col < flat.getOutputCount(); col++) { this.idealArray[idealIndex++] = (float) pair.getIdealArray()[col]; } } } /** * Assign the workgroup sizes based on the training set size. * * @param trainingSize * The training set size. * @param requestedGlobalSize * The requested global size. */ public void assignWorkgroupSizes(final int trainingSize, final int requestedGlobalSize) { // Calculate the work-item dimensions final int threads = Math.min(trainingSize, requestedGlobalSize); setLocalWork(Math.min(getMaxWorkGroupSize(), threads)); setGlobalWork(threads); } /** * Calculate one iteration over the specified range. * * @param start * The starting position to calculate for. * @param size * The ending position to calculate for. * @param iterations * The number of iterations to execute. * @param learn * True, if we should learn. */ public void calculate(final int start, final int size, final boolean learn, final int iterations) { prepareKernel(); this.paramArray[KernelNetworkTrain.PARRAY_LEARN] = learn ? 1 : 0; this.paramArray[KernelNetworkTrain.PARRAY_START] = start; this.paramArray[KernelNetworkTrain.PARRAY_ITEMS_PER] = size; this.paramArray[KernelNetworkTrain.PARRAY_ITERATIONS] = iterations; EngineArray.arrayCopy(this.flat.getWeights(), this.weightInArray); setArg(0, this.paramBuffer); setArg(1, this.errorBuffer); setArg(2, this.layerIndexBuffer); setArg(3, this.layerCountBuffer); setArg(4, this.layerFeedCountBuffer); setArg(5, this.weightIndexBuffer); setArg(6, this.inputBuffer); setArg(7, this.idealBuffer); setArg(8, this.weightInArrayBuffer); setArg(9, this.weightOutArrayBuffer); setArg(10, this.gradientOutBuffer); setArg(11, this.activationTypeBuffer); setArg(12, this.tempDataInBuffer); setArg(13, this.tempDataOutBuffer); setArg(14, this.gradientInBuffer); try { final EncogCLQueue queue = this.device.getQueue(); EngineArray.fill(this.gradients, 0); if (learn) { this.paramArray[3] = 1; } else { this.paramArray[3] = 0; } this.paramArray[4] = start; queue.array2Buffer(this.weightInArray, this.weightInArrayBuffer); queue.array2Buffer(this.tempDataArray, this.tempDataInBuffer); queue.array2Buffer(this.gradients, this.gradientInBuffer); queue.array2Buffer(this.paramArray, this.paramBuffer); // Execute the kernel queue.execute(this); queue.waitFinish(); // Read the results queue.buffer2Array(this.errorBuffer, this.errors); queue.buffer2Array(this.weightOutArrayBuffer, this.weightOutArray); queue.buffer2Array(this.tempDataOutBuffer, this.tempDataArray); queue.buffer2Array(this.gradientOutBuffer, this.gradients); } catch (final CLException e) { if (e.getMessage().equals("CL_OUT_OF_RESOURCES")) { throw new OutOfOpenCLResources(e); } else { throw new OpenCLError(e); } } catch (final Exception e) { throw new OpenCLError(e); } } /** * Compile the kernel. * * @param options * The options. * @param profile * The OpenCL training profile. * @param network * The network to compile for. */ public void compile(final Map<String, String> options, final OpenCLTrainingProfile profile, final FlatNetwork network) { final ActivationFunction activation = network.getActivationFunctions()[0]; final StringBuilder source = new StringBuilder(); source.append("#define ACTIVATION(x,slope)"); source.append(activation.getOpenCLExpression(false)); source.append("\r\n"); source.append("#define DERIVATIVE(x,slope)"); source.append(activation.getOpenCLExpression(true)); source.append("\r\n"); source.append(ResourceLoader.loadString(getSourceName())); setCLSource(source.toString()); compile(options); profile.calculateKernelParams(this, this.training); // setup init(profile); } /** * @return the errors */ public float[] getErrors() { return this.errors; } /** * @return the tempDataArray */ public float[] getTempDataArray() { return this.tempDataArray; } /** * @return the weightOutArray */ public float[] getWeightOutArray() { return this.weightOutArray; } /** * Setup the kernel. * @param profile The OpenCL training profile. */ public void init(final OpenCLTrainingProfile profile) { final int errorSize = profile.getKernelGlobalWorkgroup(); final int gradientSize = profile.getKernelGlobalWorkgroup() * this.flat.getWeights().length; this.errors = new float[errorSize]; this.paramArray[0] = this.flat.getInputCount(); this.paramArray[1] = this.flat.getOutputCount(); this.paramArray[2] = this.flat.getLayerCounts().length; // create the buffers this.inputBuffer = createArrayReadOnly(this.inputArray); this.idealBuffer = createArrayReadOnly(this.idealArray); this.errorBuffer = createFloatArrayWriteOnly(errorSize); this.gradientOutBuffer = createFloatArrayWriteOnly(gradientSize); this.gradientInBuffer = createArrayReadOnly(this.gradients); this.paramBuffer = createArrayReadOnly(this.paramArray); this.layerIndexBuffer = createArrayReadOnly(this.flat.getLayerIndex()); this.layerCountBuffer = createArrayReadOnly(this.flat.getLayerCounts()); this.layerFeedCountBuffer = createArrayReadOnly(this.flat .getLayerFeedCounts()); this.weightInArrayBuffer = createArrayReadOnly(this.weightInArray); this.weightOutArrayBuffer = createFloatArrayWriteOnly(this.weightInArray.length); this.weightIndexBuffer = createArrayReadOnly(this.flat.getWeightIndex()); this.activationTypeBuffer = createArrayReadOnly(this.flat .getLayerCounts()); this.tempDataInBuffer = createArrayReadOnly(this.tempDataArray); this.tempDataOutBuffer = createFloatArrayWriteOnly(this.tempDataArray.length); } /** * Release the kernel and all buffers. */ @Override public void release() { super.release(); releaseBuffer(this.activationTypeBuffer); releaseBuffer(this.errorBuffer); releaseBuffer(this.gradientOutBuffer); releaseBuffer(this.gradientInBuffer); releaseBuffer(this.idealBuffer); releaseBuffer(this.inputBuffer); releaseBuffer(this.layerCountBuffer); releaseBuffer(this.layerFeedCountBuffer); releaseBuffer(this.layerIndexBuffer); releaseBuffer(this.paramBuffer); releaseBuffer(this.tempDataInBuffer); releaseBuffer(this.tempDataOutBuffer); releaseBuffer(this.weightInArrayBuffer); releaseBuffer(this.weightIndexBuffer); releaseBuffer(this.weightOutArrayBuffer); } /** * @param tempDataArray * the tempDataArray to set */ public void setTempDataArray(final float[] tempDataArray) { this.tempDataArray = tempDataArray; } }
mit
selvasingh/azure-sdk-for-java
sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/GenerateThumbnailOptionalParameter.java
1812
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.cognitiveservices.vision.computervision.models; /** * The GenerateThumbnailOptionalParameter model. */ public class GenerateThumbnailOptionalParameter { /** * Boolean flag for enabling smart cropping. */ private Boolean smartCropping; /** * Gets or sets the preferred language for the response. */ private String thisclientacceptLanguage; /** * Get the smartCropping value. * * @return the smartCropping value */ public Boolean smartCropping() { return this.smartCropping; } /** * Set the smartCropping value. * * @param smartCropping the smartCropping value to set * @return the GenerateThumbnailOptionalParameter object itself. */ public GenerateThumbnailOptionalParameter withSmartCropping(Boolean smartCropping) { this.smartCropping = smartCropping; return this; } /** * Get the thisclientacceptLanguage value. * * @return the thisclientacceptLanguage value */ public String thisclientacceptLanguage() { return this.thisclientacceptLanguage; } /** * Set the thisclientacceptLanguage value. * * @param thisclientacceptLanguage the thisclientacceptLanguage value to set * @return the GenerateThumbnailOptionalParameter object itself. */ public GenerateThumbnailOptionalParameter withThisclientacceptLanguage(String thisclientacceptLanguage) { this.thisclientacceptLanguage = thisclientacceptLanguage; return this; } }
mit
PetrF0X/podio-java
src/test/java/com/podio/item/map/BugMap3.java
1113
package com.podio.item.map; import java.util.Collection; public class BugMap3 { private String externalId; private Collection<String> statuses; private double amount; private float importance; public BugMap3() { super(); } public BugMap3(String externalId, Collection<String> statuses, double amount, float importance) { super(); this.externalId = externalId; this.statuses = statuses; this.amount = amount; this.importance = importance; } @ExternalId public String getExternalId() { return externalId; } public void setExternalId(String externalId) { this.externalId = externalId; } @Field("is-hired") public Collection<String> getStatuses() { return statuses; } public void setStatuses(Collection<String> statuses) { this.statuses = statuses; } @MoneyField(currency = "EUR") @Field("alotta-cash") public double getAmount() { return amount; } public void setAmount(double amount) { this.amount = amount; } public float getImportance() { return importance; } public void setImportance(float importance) { this.importance = importance; } }
mit
selvasingh/azure-sdk-for-java
sdk/storage/microsoft-azure-storage-blob/src/main/java/com/microsoft/azure/storage/blob/models/LeaseStateType.java
1550
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator package com.microsoft.azure.storage.blob.models; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; /** * Defines values for LeaseStateType. */ public enum LeaseStateType { /** * Enum value available. */ AVAILABLE("available"), /** * Enum value leased. */ LEASED("leased"), /** * Enum value expired. */ EXPIRED("expired"), /** * Enum value breaking. */ BREAKING("breaking"), /** * Enum value broken. */ BROKEN("broken"); /** * The actual serialized value for a LeaseStateType instance. */ private final String value; private LeaseStateType(String value) { this.value = value; } /** * Parses a serialized value to a LeaseStateType instance. * * @param value the serialized value to parse. * @return the parsed LeaseStateType object, or null if unable to parse. */ @JsonCreator public static LeaseStateType fromString(String value) { LeaseStateType[] items = LeaseStateType.values(); for (LeaseStateType item : items) { if (item.toString().equalsIgnoreCase(value)) { return item; } } return null; } @JsonValue @Override public String toString() { return this.value; } }
mit
selfpoised/6.830
6.830-lab5/src/java/simpledb/HeapPage.java
11394
package simpledb; import java.util.*; import java.io.*; /** * Each instance of HeapPage stores data for one page of HeapFiles and * implements the Page interface that is used by BufferPool. * * @see HeapFile * @see BufferPool * */ public class HeapPage implements Page { final HeapPageId pid; final TupleDesc td; final byte header[]; final Tuple tuples[]; final int numSlots; byte[] oldData; private final Byte oldDataLock=new Byte((byte)0); private boolean dirty=false; private TransactionId tid=null; /** * Create a HeapPage from a set of bytes of data read from disk. * The format of a HeapPage is a set of header bytes indicating * the slots of the page that are in use, some number of tuple slots. * Specifically, the number of tuples is equal to: <p> * floor((BufferPool.getPageSize()*8) / (tuple size * 8 + 1)) * <p> where tuple size is the size of tuples in this * database table, which can be determined via {@link Catalog#getTupleDesc}. * The number of 8-bit header words is equal to: * <p> * ceiling(no. tuple slots / 8) * <p> * @see Database#getCatalog * @see Catalog#getTupleDesc * @see BufferPool#getPageSize() */ public HeapPage(HeapPageId id, byte[] data) throws IOException { this.pid = id; this.td = Database.getCatalog().getTupleDesc(id.getTableId()); this.numSlots = getNumTuples(); DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data)); // allocate and read the header slots of this page header = new byte[getHeaderSize()]; for (int i=0; i<header.length; i++) header[i] = dis.readByte(); tuples = new Tuple[numSlots]; try{ // allocate and read the actual records of this page for (int i=0; i<tuples.length; i++) tuples[i] = readNextTuple(dis,i); }catch(NoSuchElementException e){ e.printStackTrace(); } dis.close(); setBeforeImage(); } /** Retrieve the number of tuples on this page. @return the number of tuples on this page */ private int getNumTuples() { // some code goes here int num = (int)Math.floor((BufferPool.getPageSize()*8*1.0) / (td.getSize() * 8 + 1)); return num; } /** * Computes the number of bytes in the header of a page in a HeapFile with each tuple occupying tupleSize bytes * @return the number of bytes in the header of a page in a HeapFile with each tuple occupying tupleSize bytes */ private int getHeaderSize() { // some code goes here return (int)Math.ceil(getNumTuples()*1.0 / 8); } /** Return a view of this page before it was modified -- used by recovery */ public HeapPage getBeforeImage(){ try { byte[] oldDataRef = null; synchronized(oldDataLock) { oldDataRef = oldData; } return new HeapPage(pid,oldDataRef); } catch (IOException e) { e.printStackTrace(); //should never happen -- we parsed it OK before! System.exit(1); } return null; } public void setBeforeImage() { synchronized(oldDataLock) { oldData = getPageData().clone(); } } /** * @return the PageId associated with this page. */ public HeapPageId getId() { // some code goes here return pid; } /** * Suck up tuples from the source file. */ private Tuple readNextTuple(DataInputStream dis, int slotId) throws NoSuchElementException { // if associated bit is not set, read forward to the next tuple, and // return null. if (!isSlotUsed(slotId)) { for (int i=0; i<td.getSize(); i++) { try { dis.readByte(); } catch (IOException e) { throw new NoSuchElementException("error reading empty tuple"); } } return null; } // read fields in the tuple Tuple t = new Tuple(td); RecordId rid = new RecordId(pid, slotId); t.setRecordId(rid); try { for (int j=0; j<td.numFields(); j++) { Field f = td.getFieldType(j).parse(dis); t.setField(j, f); } } catch (java.text.ParseException e) { e.printStackTrace(); throw new NoSuchElementException("parsing error!"); } return t; } /** * Generates a byte array representing the contents of this page. * Used to serialize this page to disk. * <p> * The invariant here is that it should be possible to pass the byte * array generated by getPageData to the HeapPage constructor and * have it produce an identical HeapPage object. * * @see #HeapPage * @return A byte array correspond to the bytes of this page. */ public byte[] getPageData() { int len = BufferPool.getPageSize(); ByteArrayOutputStream baos = new ByteArrayOutputStream(len); DataOutputStream dos = new DataOutputStream(baos); // create the header of the page for (int i=0; i<header.length; i++) { try { dos.writeByte(header[i]); } catch (IOException e) { // this really shouldn't happen e.printStackTrace(); } } // create the tuples for (int i=0; i<tuples.length; i++) { // empty slot if (!isSlotUsed(i)) { for (int j=0; j<td.getSize(); j++) { try { dos.writeByte(0); } catch (IOException e) { e.printStackTrace(); } } continue; } // non-empty slot for (int j=0; j<td.numFields(); j++) { Field f = tuples[i].getField(j); try { f.serialize(dos); } catch (IOException e) { e.printStackTrace(); } } } // padding int zerolen = BufferPool.getPageSize() - (header.length + td.getSize() * tuples.length); //- numSlots * td.getSize(); byte[] zeroes = new byte[zerolen]; try { dos.write(zeroes, 0, zerolen); } catch (IOException e) { e.printStackTrace(); } try { dos.flush(); } catch (IOException e) { e.printStackTrace(); } return baos.toByteArray(); } /** * Static method to generate a byte array corresponding to an empty * HeapPage. * Used to add new, empty pages to the file. Passing the results of * this method to the HeapPage constructor will create a HeapPage with * no valid tuples in it. * * @return The returned ByteArray. */ public static byte[] createEmptyPageData() { int len = BufferPool.getPageSize(); return new byte[len]; //all 0 } /** * Delete the specified tuple from the page; the tuple should be updated to reflect * that it is no longer stored on any page. * @throws DbException if this tuple is not on this page, or tuple slot is * already empty. * @param t The tuple to delete */ public void deleteTuple(Tuple t) throws DbException { // some code goes here // not necessary for lab1 for(int i=0;i<numSlots;i++){ Tuple it = tuples[i]; if(isSlotUsed(i) && it.getRecordId() != null && it.getRecordId().equals(t.getRecordId())){ markSlotUsed(i,false); t.setRecordId(null); return; } } throw new DbException("deleteTuple " + t); } /** * Adds the specified tuple to the page; the tuple should be updated to reflect * that it is now stored on this page. * @throws DbException if the page is full (no empty slots) or tupledesc * is mismatch. * @param t The tuple to add. */ public void insertTuple(Tuple t) throws DbException { // some code goes here // not necessary for lab1 if(getNumEmptySlots() == 0){ throw new DbException("this page is full"); } if(!td.equals(t.getTupleDesc())){ throw new DbException("tupledesc mismatch"); } for(int i=0;i<numSlots;i++){ if(!isSlotUsed(i)){ tuples[i] = t; markSlotUsed(i,true); RecordId rid = new RecordId(pid,i); t.setRecordId(rid); return; } } throw new DbException("insertTuple " + t); } /** * Marks this page as dirty/not dirty and record that transaction * that did the dirtying */ public void markDirty(boolean dirty, TransactionId tid) { // some code goes here // not necessary for lab1 this.dirty = dirty; this.tid = tid; } /** * Returns the tid of the transaction that last dirtied this page, or null if the page is not dirty */ public TransactionId isDirty() { // some code goes here // Not necessary for lab1 if(dirty){ return tid; } return null; } /** * Returns the number of empty slots on this page. */ public int getNumEmptySlots() { // some code goes here int num = 0; for(int i=0;i<numSlots;i++){ if(!isSlotUsed(i)){ num++; } } return num; } /** * Returns true if associated slot on this page is filled. */ public boolean isSlotUsed(int i) { // some code goes here int quot = i / 8; int remainder = i % 8; int mark = header[quot]; int bit = (mark >> remainder) & 0x01; return bit == 1; } /** * Abstraction to fill or clear a slot on this page. */ private void markSlotUsed(int i, boolean value) { // some code goes here // not necessary for lab1 if(i < 0 || i >= numSlots){ throw new IndexOutOfBoundsException(String.format("%d is out of bound with %d slots", i,numSlots)); } int quot = i / 8; int remainder = i % 8; int oldByte = header[quot]; int markBitByte = (1 << remainder) & 0x00ff; int newByte = 0; if(value){ newByte = oldByte | markBitByte; }else{ markBitByte = markBitByte ^ 0x00ff; newByte = oldByte & markBitByte; } header[quot] = (byte)newByte; } /** * @return an iterator over all tuples on this page (calling remove on this iterator throws an UnsupportedOperationException) * (note that this iterator shouldn't return tuples in empty slots!) */ public Iterator<Tuple> iterator() { // some code goes here ArrayList<Tuple> filledTuples = new ArrayList<Tuple>(); for(int i=0;i<numSlots;i++){ if(isSlotUsed(i)){ filledTuples.add(tuples[i]); } } return filledTuples.iterator(); } }
mit
Carboni/the-train-destination
src/main/java/com/github/onsdigital/thetrain/json/request/FileCopy.java
263
package com.github.onsdigital.thetrain.json.request; public class FileCopy { public String source; public String target; public FileCopy(String sourceUri, String targetUri) { this.source = sourceUri; this.target = targetUri; } }
mit
jonathangizmo/HadoopDistJ
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/protocol/ClientDatanodeProtocol.java
5680
/** * 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.hdfs.protocol; import java.io.IOException; import java.util.List; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability; import org.apache.hadoop.hdfs.DFSConfigKeys; import org.apache.hadoop.hdfs.security.token.block.BlockTokenIdentifier; import org.apache.hadoop.hdfs.security.token.block.BlockTokenSelector; import org.apache.hadoop.security.KerberosInfo; import org.apache.hadoop.security.token.Token; import org.apache.hadoop.security.token.TokenInfo; /** An client-datanode protocol for block recovery */ @InterfaceAudience.Private @InterfaceStability.Evolving @KerberosInfo( serverPrincipal = DFSConfigKeys.DFS_DATANODE_KERBEROS_PRINCIPAL_KEY) @TokenInfo(BlockTokenSelector.class) public interface ClientDatanodeProtocol { /** * Until version 9, this class ClientDatanodeProtocol served as both * the client interface to the DN AND the RPC protocol used to * communicate with the NN. * * This class is used by both the DFSClient and the * DN server side to insulate from the protocol serialization. * * If you are adding/changing DN's interface then you need to * change both this class and ALSO related protocol buffer * wire protocol definition in ClientDatanodeProtocol.proto. * * For more details on protocol buffer wire protocol, please see * .../org/apache/hadoop/hdfs/protocolPB/overview.html * * The log of historical changes can be retrieved from the svn). * 9: Added deleteBlockPool method * * 9 is the last version id when this class was used for protocols * serialization. DO not update this version any further. */ public static final long versionID = 9L; /** Return the visible length of a replica. */ long getReplicaVisibleLength(ExtendedBlock b) throws IOException; /** * Refresh the list of federated namenodes from updated configuration * Adds new namenodes and stops the deleted namenodes. * * @throws IOException on error **/ void refreshNamenodes() throws IOException; /** * Delete the block pool directory. If force is false it is deleted only if * it is empty, otherwise it is deleted along with its contents. * * @param bpid Blockpool id to be deleted. * @param force If false blockpool directory is deleted only if it is empty * i.e. if it doesn't contain any block files, otherwise it is * deleted along with its contents. * @throws IOException */ void deleteBlockPool(String bpid, boolean force) throws IOException; /** * Retrieves the path names of the block file and metadata file stored on the * local file system. * * In order for this method to work, one of the following should be satisfied: * <ul> * <li> * The client user must be configured at the datanode to be able to use this * method.</li> * <li> * When security is enabled, kerberos authentication must be used to connect * to the datanode.</li> * </ul> * * @param block * the specified block on the local datanode * @param token * the block access token. * @return the BlockLocalPathInfo of a block * @throws IOException * on error */ BlockLocalPathInfo getBlockLocalPathInfo(ExtendedBlock block, Token<BlockTokenIdentifier> token) throws IOException; /** * Retrieves volume location information about a list of blocks on a datanode. * This is in the form of an opaque {@link org.apache.hadoop.fs.VolumeId} * for each configured data directory, which is not guaranteed to be * the same across DN restarts. * * @param blockPoolId the pool to query * @param blockIds * list of blocks on the local datanode * @param tokens * block access tokens corresponding to the requested blocks * @return an HdfsBlocksMetadata that associates {@link ExtendedBlock}s with * data directories * @throws IOException * if datanode is unreachable, or replica is not found on datanode */ HdfsBlocksMetadata getHdfsBlocksMetadata(String blockPoolId, long []blockIds, List<Token<BlockTokenIdentifier>> tokens) throws IOException; /** * Shuts down a datanode. * * @param forUpgrade If true, data node does extra prep work before shutting * down. The work includes advising clients to wait and saving * certain states for quick restart. This should only be used when * the stored data will remain the same during upgrade/restart. * @throws IOException */ void shutdownDatanode(boolean forUpgrade) throws IOException; /** * Obtains datanode info * * @return software/config version and uptime of the datanode */ DatanodeLocalInfo getDatanodeInfo() throws IOException; }
mit
selvasingh/azure-sdk-for-java
sdk/network/mgmt-v2018_06_01/src/main/java/com/microsoft/azure/management/network/v2018_06_01/implementation/NetworkSecurityGroupInner.java
6011
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.network.v2018_06_01.implementation; import java.util.List; import com.fasterxml.jackson.annotation.JsonProperty; import com.microsoft.rest.serializer.JsonFlatten; import com.microsoft.rest.SkipParentValidation; import com.microsoft.azure.Resource; /** * NetworkSecurityGroup resource. */ @JsonFlatten @SkipParentValidation public class NetworkSecurityGroupInner extends Resource { /** * A collection of security rules of the network security group. */ @JsonProperty(value = "properties.securityRules") private List<SecurityRuleInner> securityRules; /** * The default security rules of network security group. */ @JsonProperty(value = "properties.defaultSecurityRules") private List<SecurityRuleInner> defaultSecurityRules; /** * A collection of references to network interfaces. */ @JsonProperty(value = "properties.networkInterfaces", access = JsonProperty.Access.WRITE_ONLY) private List<NetworkInterfaceInner> networkInterfaces; /** * A collection of references to subnets. */ @JsonProperty(value = "properties.subnets", access = JsonProperty.Access.WRITE_ONLY) private List<SubnetInner> subnets; /** * The resource GUID property of the network security group resource. */ @JsonProperty(value = "properties.resourceGuid") private String resourceGuid; /** * The provisioning state of the public IP resource. Possible values are: * 'Updating', 'Deleting', and 'Failed'. */ @JsonProperty(value = "properties.provisioningState") private String provisioningState; /** * A unique read-only string that changes whenever the resource is updated. */ @JsonProperty(value = "etag") private String etag; /** * Resource ID. */ @JsonProperty(value = "id") private String id; /** * Get a collection of security rules of the network security group. * * @return the securityRules value */ public List<SecurityRuleInner> securityRules() { return this.securityRules; } /** * Set a collection of security rules of the network security group. * * @param securityRules the securityRules value to set * @return the NetworkSecurityGroupInner object itself. */ public NetworkSecurityGroupInner withSecurityRules(List<SecurityRuleInner> securityRules) { this.securityRules = securityRules; return this; } /** * Get the default security rules of network security group. * * @return the defaultSecurityRules value */ public List<SecurityRuleInner> defaultSecurityRules() { return this.defaultSecurityRules; } /** * Set the default security rules of network security group. * * @param defaultSecurityRules the defaultSecurityRules value to set * @return the NetworkSecurityGroupInner object itself. */ public NetworkSecurityGroupInner withDefaultSecurityRules(List<SecurityRuleInner> defaultSecurityRules) { this.defaultSecurityRules = defaultSecurityRules; return this; } /** * Get a collection of references to network interfaces. * * @return the networkInterfaces value */ public List<NetworkInterfaceInner> networkInterfaces() { return this.networkInterfaces; } /** * Get a collection of references to subnets. * * @return the subnets value */ public List<SubnetInner> subnets() { return this.subnets; } /** * Get the resource GUID property of the network security group resource. * * @return the resourceGuid value */ public String resourceGuid() { return this.resourceGuid; } /** * Set the resource GUID property of the network security group resource. * * @param resourceGuid the resourceGuid value to set * @return the NetworkSecurityGroupInner object itself. */ public NetworkSecurityGroupInner withResourceGuid(String resourceGuid) { this.resourceGuid = resourceGuid; return this; } /** * Get the provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. * * @return the provisioningState value */ public String provisioningState() { return this.provisioningState; } /** * Set the provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. * * @param provisioningState the provisioningState value to set * @return the NetworkSecurityGroupInner object itself. */ public NetworkSecurityGroupInner withProvisioningState(String provisioningState) { this.provisioningState = provisioningState; return this; } /** * Get a unique read-only string that changes whenever the resource is updated. * * @return the etag value */ public String etag() { return this.etag; } /** * Set a unique read-only string that changes whenever the resource is updated. * * @param etag the etag value to set * @return the NetworkSecurityGroupInner object itself. */ public NetworkSecurityGroupInner withEtag(String etag) { this.etag = etag; return this; } /** * Get resource ID. * * @return the id value */ public String id() { return this.id; } /** * Set resource ID. * * @param id the id value to set * @return the NetworkSecurityGroupInner object itself. */ public NetworkSecurityGroupInner withId(String id) { this.id = id; return this; } }
mit
jon-hanson/funcj
codec/core/src/main/java/org/typemeta/funcj/codec/utils/CodecRef.java
2536
package org.typemeta.funcj.codec.utils; import org.typemeta.funcj.codec.*; import org.typemeta.funcj.functions.Functions; import java.util.Objects; /** * A reference to a {@link Codec}. * {@code CodecRef} implements the {@link Codec} interface. * Used when looking up a codec for a recursive type. * @param <T> the raw type to be encoded/decoded * @param <IN> the encoded input type * @param <OUT> the encoded output type */ public class CodecRef<T, IN, OUT, CFG extends CodecConfig> implements Codec<T, IN, OUT, CFG> { private enum Uninitialised implements Codec { INSTANCE; @Override public Class<Object> type() { throw error(); } @Override public Object encode( CodecCoreEx core, Object value, Object output) { throw error(); } @Override public Object decode( CodecCoreEx core, Object input) { throw error(); } private static RuntimeException error() { return new RuntimeException("Uninitialised lazy Codec reference"); } static Codec of() { return INSTANCE; } } private volatile Codec<T, IN, OUT, CFG> impl; @SuppressWarnings("unchecked") public CodecRef() { this.impl = Uninitialised.of(); } /** * Initialise this reference. * @param impl the codec * @return this codec */ public Codec<T, IN, OUT, CFG> set(Codec<T, IN, OUT, CFG> impl) { if (this.impl != Uninitialised.INSTANCE) { throw new IllegalStateException("CodecRef is already initialised"); } else { this.impl = Objects.requireNonNull(impl); return this; } } public synchronized Codec<T, IN, OUT, CFG> setIfUninitialised(Functions.F0<Codec<T, IN, OUT, CFG>> implSupp) { if (this.impl == Uninitialised.INSTANCE) { this.impl = Objects.requireNonNull(implSupp.apply()); } return impl; } public Codec<T, IN, OUT, CFG> get() { return impl; } @Override public Class<T> type() { return impl.type(); } @Override public OUT encode(CodecCoreEx<IN, OUT, CFG> core, T value, OUT out) { return impl.encode(core, value, out); } @Override public T decode(CodecCoreEx<IN, OUT, CFG> core, IN in) { return impl.decode(core, in); } }
mit
itenente/igv
src/org/broad/igv/track/GisticTrack.java
11111
/* * 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. */ /* * GisticScoreList.java * * Created on June 21, 2007, 8:29 AM * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package org.broad.igv.track; //~--- non-JDK imports -------------------------------------------------------- import org.apache.log4j.Logger; import org.broad.igv.feature.IGVFeature; import org.broad.igv.feature.FeatureUtils; import org.broad.igv.feature.GisticScore; import org.broad.igv.feature.LocusScore; import org.broad.igv.renderer.DataRange; import org.broad.igv.renderer.GisticTrackRenderer; import org.broad.igv.renderer.Renderer; import org.broad.igv.ui.panel.ReferenceFrame; import org.broad.igv.util.ResourceLocator; import java.awt.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author jrobinso */ public class GisticTrack extends AbstractTrack { private static Logger log = Logger.getLogger(GisticTrack.class); private static final int DEFAULT_HEIGHT = 50; private double maxQValue = 0; private double maxGScore = 0; /** * Map of chromosome -> sorted list of scores */ Map<String, List<GisticScore>> ampScoreMap; Map<String, List<GisticScore>> delScoreMap; GisticTrackRenderer renderer; public GisticTrack(ResourceLocator locator) { super(locator); ampScoreMap = new HashMap<String, List<GisticScore>>(); delScoreMap = new HashMap<String, List<GisticScore>>(); renderer = new GisticTrackRenderer(); setHeight(DEFAULT_HEIGHT); renderer = new GisticTrackRenderer(); setSortable(false); } @Override public int getMinimumHeight() { return 25; } /** * Method description * * @param scores */ public void setScores(List<GisticScore> scores) { for (GisticScore score : scores) { String chr = score.getChromosome(); if (score.getType() == GisticScore.Type.AMP) { addScore(score, chr, ampScoreMap); } else { addScore(score, chr, delScoreMap); } } updateMaxValues(scores); } protected void addScore(GisticScore score, String chr, Map<String, List<GisticScore>> map) { List<GisticScore> scoreList = map.get(chr); if (scoreList == null) { scoreList = new ArrayList(); map.put(chr, scoreList); } scoreList.add(score); } private void updateMaxValues(List<GisticScore> scores) { for (GisticScore score : scores) { if (!Double.isInfinite(maxGScore) && score.getGScore() > maxGScore) { maxGScore = score.getGScore(); } if (!Double.isInfinite(maxQValue) && score.getQValue() > maxQValue) { maxQValue = score.getQValue(); } } setDataRange(new DataRange(0, 0, (float) maxQValue)); } /** * Method description * * @param chr * @return */ public List<GisticScore> getAmpScores(String chr) { return ampScoreMap.get(chr); } /** * Method description * * @param chr * @return */ public List<GisticScore> getDelScores(String chr) { return delScoreMap.get(chr); } /** * Return the score with the maximum "G Score" over the specified region. * Assumes the scores are sorted by location * * @param chr * @param start * @param end * @return */ public GisticScore getMaxForRegion(String chr, long start, long end) { List<GisticScore> scores = ampScoreMap.get(chr); if ((scores == null) || scores.isEmpty()) { return null; } GisticScore maxScore = null; for (GisticScore score : scores) { if (maxScore == null) { if ((score.getStart() >= start) || ((start >= score.getStart()) && (start <= score.getEnd()))) { maxScore = score; } } else if (score.getStart() > end) { break; } else { if (score.getGScore() > maxScore.getGScore()) { maxScore = score; } } } // If we haven't found bounding scores yet the region is to the right off the last // score. Use the last score for the region. This should be a rare case and should // probably be logged. return (maxScore == null) ? ((GisticScore) scores.get(scores.size() - 1)) : maxScore; } /** * Method description * * @return */ public double getMaxQValue() { return maxQValue; } /** * Method description * * @return */ public double getMaxGScore() { return maxGScore; } /** * Method description * * @param context * @param rect */ public void render(RenderContext context, Rectangle rect) { if (renderer == null) { log.error("Null renderer !!"); } else { renderer.render(this, context, rect); } } double dataMax = -1; /** * Method description * * @return */ public double getDataMax() { if (dataMax < 0) { dataMax = getMaxGScore(); } return dataMax; } /** * Method description * * @param type */ public void setWindowFunction(WindowFunction type) { // ignored } /** * Method description * * @return */ public WindowFunction getWindowFunction() { return WindowFunction.median; } /** * Method description * * @param chr * @return */ public double getMedian(String chr) { return 1.0; } /** * Method description * * @return */ public boolean isLogNormalized() { return true; } /** * This method is required for the interface, but will not be called. * * @param chr * @param startLocation * @param endLocation * @return */ public List<IGVFeature> getFeatures(String chr, int startLocation, int endLocation) { return null; } /** * This method is required for the interface, but will not be called. * * @param chr * @param startLocation * @param endLocation * @param zoom * @return */ public List<LocusScore> getSummaryScores(String chr, int startLocation, int endLocation, int zoom) { List<LocusScore> ss = new ArrayList(); List<GisticScore> ampScores = ampScoreMap.get(chr); if (ampScores != null) { ss.addAll(ampScores); } List<GisticScore> delScores = delScoreMap.get(chr); if (delScores != null) { ss.addAll(delScores); } return ss; // return getFeatures(chr, startLocation, endLocation); } /** * This method is required for the interface, but will not be called. * * @param chr * @param start * @param end * @param zoom * @param type * @param frameName * @return */ public float getRegionScore(String chr, int start, int end, int zoom, RegionScoreType type, String frameName) { return 0; } /** * Method description * * @param chr * @param position * @param ignore * @return */ public String getValueStringAt(String chr, double position, int ignore, ReferenceFrame frame) { // give a 2 pixel window, otherwise very narrow features will be missed. double bpPerPixel = frame.getScale(); double minWidth = 2 * bpPerPixel; /* */ LocusScore amp = null; List<GisticScore> ampScores = ampScoreMap.get(chr); if (ampScores != null) { amp = (LocusScore) FeatureUtils.getFeatureAt(position, 0, ampScores); } LocusScore del = null; List<GisticScore> delScores = delScoreMap.get(chr); if (delScores != null) { del = (LocusScore) FeatureUtils.getFeatureAt(position, 0, delScores); } if ((amp == null) && (del == null)) { return ""; } else { StringBuffer buf = new StringBuffer(); if (amp != null) { buf.append("Amplification score: " + amp.getScore()); } if (del != null) { buf.append("<br>Deletion score: " + del.getScore()); } return buf.toString(); } } /** * Method description * * @param chr * @param startLocation * @param endLocation * @return */ public List<List<IGVFeature>> getFeaturesByLevels(String chr, int startLocation, int endLocation) { throw new UnsupportedOperationException("Not supported yet."); } /** * Method description * * @return */ public int getNumberOfFeatureLevels() { return 1; } /** * Method description * * @param isMultiLevel */ public void setMultiLevelFeatures(boolean isMultiLevel) { // ignore } /** * Method description * * @return */ public boolean isMuliLevelFeatures() { throw new UnsupportedOperationException("Not supported yet."); } public Color getColor() { return null; } public void setColor(Color color) { // Not used } public Color getAltColor() { return null; } public void setAltColor(Color color) { // Not used } // GisticTrack does not expose its renderer public Renderer getRenderer() { return null; } }
mit
gtBailly/iot_cloud
parent_sso/src/main/java/com/iot/nero/parent_sso/exception/DeveloperUpdateFailedException.java
464
package com.iot.nero.parent_sso.exception; import com.iot.nero.exception.BaseException; /** * Author neroyang * Email nerosoft@outlook.com * Date 2017/7/24 * Time 下午1:44 */ public class DeveloperUpdateFailedException extends BaseException { public DeveloperUpdateFailedException(String message) { super(message); } public DeveloperUpdateFailedException(String message, Throwable cause) { super(message, cause); } }
mit
riuvshin/che-plugins
plugin-docker/che-plugin-docker-client/src/main/java/org/eclipse/che/plugin/docker/client/json/ImageConfig.java
7313
/******************************************************************************* * Copyright (c) 2012-2015 Codenvy, S.A. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Codenvy, S.A. - initial API and implementation *******************************************************************************/ package org.eclipse.che.plugin.docker.client.json; import java.util.Arrays; import java.util.HashMap; import java.util.Map; /** * @author andrew00x */ public class ImageConfig { private boolean attachStderr; private boolean attachStdin; private boolean attachStdout; private String[] cmd; private int cpuShares; private String cpuset; private String domainname; private String[] entrypoint; private String[] env; private Map<String, ExposedPort> exposedPorts; private String hostname; private String image; private long memory; private long memorySwap; private boolean networkDisabled; private String[] onBuild; private boolean openStdin; // From docker code: // We will receive port specs in the format of ip:public:private/proto private String[] portSpecs; private boolean stdinOnce; private boolean tty; private String user; private String macAddress; private Map<String, String> labels = new HashMap<>(); private Map<String, Volume> volumes = new HashMap<>(); private String workingDir = ""; public boolean isAttachStderr() { return attachStderr; } public void setAttachStderr(boolean attachStderr) { this.attachStderr = attachStderr; } public boolean isAttachStdin() { return attachStdin; } public void setAttachStdin(boolean attachStdin) { this.attachStdin = attachStdin; } public boolean isAttachStdout() { return attachStdout; } public void setAttachStdout(boolean attachStdout) { this.attachStdout = attachStdout; } public String[] getCmd() { return cmd; } public void setCmd(String[] cmd) { this.cmd = cmd; } public int getCpuShares() { return cpuShares; } public void setCpuShares(int cpuShares) { this.cpuShares = cpuShares; } public String getCpuset() { return cpuset; } public void setCpuset(String cpuset) { this.cpuset = cpuset; } public String getDomainname() { return domainname; } public void setDomainname(String domainname) { this.domainname = domainname; } public String[] getEntrypoint() { return entrypoint; } public void setEntrypoint(String[] entrypoint) { this.entrypoint = entrypoint; } public String[] getEnv() { return env; } public void setEnv(String[] env) { this.env = env; } public Map<String, ExposedPort> getExposedPorts() { return exposedPorts; } public void setExposedPorts(Map<String, ExposedPort> exposedPorts) { this.exposedPorts = exposedPorts; } public String getHostname() { return hostname; } public void setHostname(String hostname) { this.hostname = hostname; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public long getMemory() { return memory; } public void setMemory(long memory) { this.memory = memory; } public long getMemorySwap() { return memorySwap; } public void setMemorySwap(long memorySwap) { this.memorySwap = memorySwap; } public boolean isNetworkDisabled() { return networkDisabled; } public void setNetworkDisabled(boolean networkDisabled) { this.networkDisabled = networkDisabled; } public String[] getOnBuild() { return onBuild; } public void setOnBuild(String[] onBuild) { this.onBuild = onBuild; } public boolean isOpenStdin() { return openStdin; } public void setOpenStdin(boolean openStdin) { this.openStdin = openStdin; } public String[] getPortSpecs() { return portSpecs; } public void setPortSpecs(String[] portSpecs) { this.portSpecs = portSpecs; } public boolean isStdinOnce() { return stdinOnce; } public void setStdinOnce(boolean stdinOnce) { this.stdinOnce = stdinOnce; } public boolean isTty() { return tty; } public void setTty(boolean tty) { this.tty = tty; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public Map<String, Volume> getVolumes() { return volumes; } public void setVolumes(Map<String, Volume> volumes) { this.volumes = volumes; } public String getWorkingDir() { return workingDir; } public void setWorkingDir(String workingDir) { this.workingDir = workingDir; } public String getMacAddress() { return macAddress; } public void setMacAddress(String macAddress) { this.macAddress = macAddress; } public Map<String, String> getLabels() { return labels; } public void setLabels(Map<String, String> labels) { this.labels = labels; } @Override public String toString() { return "ImageConfig{" + "attachStderr=" + attachStderr + ", attachStdin=" + attachStdin + ", attachStdout=" + attachStdout + ", cmd=" + Arrays.toString(cmd) + ", cpuShares=" + cpuShares + ", cpuset='" + cpuset + '\'' + ", domainname='" + domainname + '\'' + ", entrypoint=" + Arrays.toString(entrypoint) + ", env=" + Arrays.toString(env) + ", exposedPorts=" + exposedPorts + ", hostname='" + hostname + '\'' + ", image='" + image + '\'' + ", memory=" + memory + ", memorySwap=" + memorySwap + ", networkDisabled=" + networkDisabled + ", onBuild=" + Arrays.toString(onBuild) + ", openStdin=" + openStdin + ", portSpecs=" + Arrays.toString(portSpecs) + ", stdinOnce=" + stdinOnce + ", tty=" + tty + ", user='" + user + '\'' + ", macAddress='" + macAddress + '\'' + ", labels=" + labels + ", volumes=" + volumes + ", workingDir='" + workingDir + '\'' + '}'; } }
epl-1.0
alastrina123/debrief
org.mwc.asset.core/src/org/mwc/asset/core/property_support/unused/OldTargetTypeCellEditor.java
4173
/* * Debrief - the Open Source Maritime Analysis Application * http://debrief.info * * (C) 2000-2014, PlanetMayo Ltd * * This library is free software; you can redistribute it and/or * modify it under the terms of the Eclipse Public License v1.0 * (http://www.eclipse.org/legal/epl-v10.html) * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ package org.mwc.asset.core.property_support.unused; import java.util.*; import org.eclipse.jface.viewers.CellEditor; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.RowLayout; import org.eclipse.swt.widgets.*; import org.eclipse.swt.widgets.List; import ASSET.Models.Decision.TargetType; import ASSET.Participants.Category; public class OldTargetTypeCellEditor extends CellEditor { /** * and the drop-down units bit */ Combo _myForce; /** * and the drop-down units bit */ List _myEnvironment; /** * and the drop-down units bit */ Combo _myType; /** * our tooltip */ final private String _forceTip = "the force of the subject participant(s)"; final private String _environmentTip = "the environment of the subject participant(s)"; final private String _typeTip = "the type of the subject participant(s)"; public OldTargetTypeCellEditor(final Composite parent) { super(parent); } protected Control createControl(final Composite parent) { final Composite holder = new Composite(parent, SWT.NONE); final RowLayout rows = new RowLayout(); rows.marginLeft = rows.marginRight = 0; rows.marginTop = rows.marginBottom = 0; rows.fill = false; rows.spacing = 0; rows.pack = false; holder.setLayout(rows); _myForce = new Combo(holder, SWT.DROP_DOWN); _myForce.setToolTipText(_forceTip); _myForce.setItems(getForces()); _myEnvironment = new List(holder, SWT.DROP_DOWN); _myEnvironment.setToolTipText(_environmentTip); _myEnvironment.setItems(getEnvironments()); _myType = new Combo(holder, SWT.DROP_DOWN); _myType.setToolTipText(_typeTip); _myType.setItems(getTypes()); return holder; } /** * @return our list of values */ protected String[] getForces() { String[] res = new String[] { null }; res = (String[]) Category.getForces().toArray(res); return res; } /** * @return our list of values */ protected String[] getEnvironments() { String[] res = new String[] { null }; res = (String[]) Category.getEnvironments().toArray(res); return res; } /** * @return our list of values */ protected String[] getTypes() { String[] res = new String[] { null }; res = (String[]) Category.getTypes().toArray(res); return res; } protected Object doGetValue() { final TargetType tt = new TargetType(); if (_myForce.getSelectionIndex() != -1) tt.addTargetType(_myForce.getItem(_myForce.getSelectionIndex())); if (_myEnvironment.getSelectionIndex() != -1) tt.addTargetType(_myEnvironment.getItem(_myEnvironment.getSelectionIndex())); if (_myType.getSelectionIndex() != -1) tt.addTargetType(_myType.getItem(_myType.getSelectionIndex())); return tt; } protected void doSetFocus() { } protected void doSetValue(final Object value) { final TargetType _myCat = (TargetType) value; // ok, sort out the forces final Collection<String> types = _myCat.getTargets(); for (final Iterator<String> iter = types.iterator(); iter.hasNext();) { final String type = (String) iter.next(); // is this a force? if (Category.getForces().contains(type)) { _myForce.select(_myForce.indexOf(type)); } else if (Category.getTypes().contains(type)) { _myType.select(_myType.indexOf(type)); } else if (Category.getEnvironments().contains(type)) { _myEnvironment.select(_myEnvironment.indexOf(type)); } } // ok, set the values // _myForce.select(1); // _myEnvironment.select(2); // _myType.select(3); } }
epl-1.0
snjeza/che
wsagent/che-core-api-debug/src/main/java/org/eclipse/che/api/debugger/server/DebuggerWebSocketMessenger.java
2336
/******************************************************************************* * Copyright (c) 2012-2017 Codenvy, S.A. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Codenvy, S.A. - initial API and implementation *******************************************************************************/ package org.eclipse.che.api.debugger.server; import org.eclipse.che.api.core.notification.EventService; import org.eclipse.che.api.core.notification.EventSubscriber; import org.eclipse.che.dto.server.DtoFactory; import org.everrest.websockets.WSConnectionContext; import org.everrest.websockets.message.ChannelBroadcastMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.inject.Inject; import javax.inject.Singleton; import static org.eclipse.che.api.debugger.server.DtoConverter.asDto; /** * @deprecated As of release 5.8.0, replaced by {@link DebuggerJsonRpcMessenger} */ @Singleton @Deprecated public class DebuggerWebSocketMessenger implements EventSubscriber<DebuggerMessage> { private static final Logger LOG = LoggerFactory.getLogger(DebuggerWebSocketMessenger.class); private static final String CHANNEL = "%s:events:"; private final EventService eventService; @Inject public DebuggerWebSocketMessenger(EventService eventService) { this.eventService = eventService; } @PostConstruct private void subscribe() { eventService.subscribe(this); } @PreDestroy private void unsubscribe() { eventService.unsubscribe(this); } @Override public void onEvent(DebuggerMessage msg) { try { final ChannelBroadcastMessage bm = new ChannelBroadcastMessage(); final String channel = String.format(CHANNEL, msg.getDebuggerType()); bm.setChannel(channel); bm.setBody(DtoFactory.getInstance().toJson(asDto(msg.getDebuggerEvent()))); WSConnectionContext.sendMessage(bm); } catch (Exception e) { LOG.error(e.getMessage(), e); } } }
epl-1.0
boniatillo-com/PhaserEditor
source/thirdparty/jsdt/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/dom/fragments/ASTFragmentFactory.java
8006
/******************************************************************************* * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.wst.jsdt.internal.corext.dom.fragments; import org.eclipse.core.runtime.Assert; import org.eclipse.wst.jsdt.core.IJavaScriptUnit; import org.eclipse.wst.jsdt.core.JavaScriptModelException; import org.eclipse.wst.jsdt.core.dom.ASTNode; import org.eclipse.wst.jsdt.core.dom.Expression; import org.eclipse.wst.jsdt.core.dom.InfixExpression; import org.eclipse.wst.jsdt.internal.corext.SourceRange; import org.eclipse.wst.jsdt.internal.corext.dom.HierarchicalASTVisitor; import org.eclipse.wst.jsdt.internal.corext.dom.Selection; import org.eclipse.wst.jsdt.internal.corext.dom.SelectionAnalyzer; /** * Creates various differing kinds of IASTFragments, all through * a very narrow interface. The kind of IASTFragment produced will depend * on properties of the parameters supplied to the factory methods, such * as the types and characteristics of AST nodes, or the location of * source ranges. * * In general, the client will not be aware of exactly what kind of * fragment is obtained from these methods. Beyond the functionality * provided by the IASTFragment interface, the client can know, however, * based on the parameters passed, some things about the created fragment. * See the documentation of the factory methods. * * @see IASTFragment * */ public class ASTFragmentFactory { // Factory Methods: ///////////////////////////////////////////////////////////////////////// /** * Creates and returns a fragment representing the entire subtree * rooted at <code>node</code>. It is not true in general that * the node to which the produced IASTFragment maps (see {@link org.eclipse.wst.jsdt.internal.corext.dom.fragments.IASTFragment IASTFragment}) * will be <code>node</code>. * * XXX: more doc (current assertions about input vs. output) */ public static IASTFragment createFragmentForFullSubtree(ASTNode node) { IASTFragment result= FragmentForFullSubtreeFactory.createFragmentFor(node); Assert.isNotNull(result); return result; } /** * If possible, this method creates a fragment whose source code * range is <code>range</code> within compilation unit <code>cu</code>, * and which resides somewhere within the subtree identified by * <code>scope</code>. * * XXX: more doc (current assertions about input vs. output) * * @param range The source range which the create fragment must have. * @param scope A node identifying the AST subtree in which the fragment must lie. * @param cu The compilation unit to which the source range applies, and to which the AST corresponds. * @return IASTFragment A fragment whose source range is <code>range</code> within * compilation unit <code>cu</code>, residing somewhere within the * AST subtree identified by <code>scope</code>. * @throws JavaScriptModelException */ public static IASTFragment createFragmentForSourceRange(SourceRange range, ASTNode scope, IJavaScriptUnit cu) throws JavaScriptModelException { SelectionAnalyzer sa= new SelectionAnalyzer(Selection.createFromStartLength(range.getOffset(), range.getLength()), false); scope.accept(sa); if (isSingleNodeSelected(sa, range, cu)) return ASTFragmentFactory.createFragmentForFullSubtree(sa.getFirstSelectedNode()); if (isEmptySelectionCoveredByANode(range, sa)) return ASTFragmentFactory.createFragmentForFullSubtree(sa.getLastCoveringNode()); return ASTFragmentFactory.createFragmentForSubPartBySourceRange(sa.getLastCoveringNode(), range, cu); } ///////////////////////////////////////////////////////////////////////////////////////////////////// private static boolean isEmptySelectionCoveredByANode(SourceRange range, SelectionAnalyzer sa) { return range.getLength() == 0 && sa.getFirstSelectedNode() == null && sa.getLastCoveringNode() != null; } private static boolean isSingleNodeSelected(SelectionAnalyzer sa, SourceRange range, IJavaScriptUnit cu) throws JavaScriptModelException { return sa.getSelectedNodes().length == 1 && !rangeIncludesNonWhitespaceOutsideNode(range, sa.getFirstSelectedNode(), cu); } private static boolean rangeIncludesNonWhitespaceOutsideNode(SourceRange range, ASTNode node, IJavaScriptUnit cu) throws JavaScriptModelException { return Util.rangeIncludesNonWhitespaceOutsideRange(range, new SourceRange(node), cu.getBuffer()); } /** * Returns <code>null</code> if the indices, taken with respect to * the node, do not correspond to a valid node-sub-part * fragment. */ private static IASTFragment createFragmentForSubPartBySourceRange(ASTNode node, SourceRange range, IJavaScriptUnit cu) throws JavaScriptModelException { return FragmentForSubPartBySourceRangeFactory.createFragmentFor(node, range, cu); } private static class FragmentForFullSubtreeFactory extends FragmentFactory { public static IASTFragment createFragmentFor(ASTNode node) { return new FragmentForFullSubtreeFactory().createFragment(node); } public boolean visit(InfixExpression node) { /* Try creating an associative infix expression fragment /* for the full subtree. If this is not applicable, * try something more generic. */ IASTFragment fragment= AssociativeInfixExpressionFragment.createFragmentForFullSubtree(node); if(fragment == null) return visit((Expression) node); setFragment(fragment); return false; } public boolean visit(Expression node) { setFragment(new SimpleExpressionFragment(node)); return false; } public boolean visit(ASTNode node) { setFragment(new SimpleFragment(node)); return false; } } private static class FragmentForSubPartBySourceRangeFactory extends FragmentFactory { private SourceRange fRange; private IJavaScriptUnit fCu; private JavaScriptModelException javaModelException= null; public static IASTFragment createFragmentFor(ASTNode node, SourceRange range, IJavaScriptUnit cu) throws JavaScriptModelException { return new FragmentForSubPartBySourceRangeFactory().createFragment(node, range, cu); } public boolean visit(InfixExpression node) { try { setFragment(createInfixExpressionSubPartFragmentBySourceRange(node, fRange, fCu)); } catch(JavaScriptModelException e) { javaModelException= e; } return false; } public boolean visit(ASTNode node) { //let fragment be null return false; } protected IASTFragment createFragment(ASTNode node, SourceRange range, IJavaScriptUnit cu) throws JavaScriptModelException { fRange= range; fCu= cu; IASTFragment result= createFragment(node); if(javaModelException != null) throw javaModelException; return result; } private static IExpressionFragment createInfixExpressionSubPartFragmentBySourceRange(InfixExpression node, SourceRange range, IJavaScriptUnit cu) throws JavaScriptModelException { return AssociativeInfixExpressionFragment.createSubPartFragmentBySourceRange(node, range, cu); } } private static abstract class FragmentFactory extends HierarchicalASTVisitor { private IASTFragment fFragment; protected IASTFragment createFragment(ASTNode node) { fFragment= null; node.accept(this); return fFragment; } protected final IASTFragment getFragment() { return fFragment; } protected final void setFragment(IASTFragment fragment) { Assert.isTrue(!isFragmentSet()); fFragment= fragment; } protected final boolean isFragmentSet() { return getFragment() != null; } } }
epl-1.0
xiaohanz/softcontroller
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/mapping/attributes/toxml/RuntimeBeanEntryWritingStrategy.java
2339
/* * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.toxml; import java.util.Map; import java.util.Map.Entry; import org.opendaylight.controller.netconf.confignetconfconnector.util.Util; import org.w3c.dom.Document; import org.w3c.dom.Element; public class RuntimeBeanEntryWritingStrategy extends CompositeAttributeWritingStrategy { public RuntimeBeanEntryWritingStrategy(Document document, String key, Map<String, AttributeWritingStrategy> innerStrats) { super(document, key, innerStrats); } /* * (non-Javadoc) * * @see org.opendaylight.controller.config.netconf.mapping.attributes.toxml. * AttributeWritingStrategy#writeElement(org.w3c.dom.Element, * java.lang.Object) */ @Override public void writeElement(Element parentElement, String namespace, Object value) { Util.checkType(value, Map.class); Element innerNode = document.createElement(key); Map<?, ?> map = (Map<?, ?>) value; for (Entry<?, ?> runtimeBeanInstanceMappingEntry : map.entrySet()) { // wrap runtime attributes with number assigned to current runtime // bean Util.checkType(runtimeBeanInstanceMappingEntry.getValue(), Map.class); Map<?, ?> innerMap = (Map<?, ?>) runtimeBeanInstanceMappingEntry.getValue(); Element runtimeInstanceNode = document.createElement("_" + (String) runtimeBeanInstanceMappingEntry.getKey()); innerNode.appendChild(runtimeInstanceNode); for (Entry<?, ?> innerObjectEntry : innerMap.entrySet()) { Util.checkType(innerObjectEntry.getKey(), String.class); String innerKey = (String) innerObjectEntry.getKey(); Object innerValue = innerObjectEntry.getValue(); innerStrats.get(innerKey).writeElement(runtimeInstanceNode, namespace, innerValue); } } parentElement.appendChild(innerNode); } }
epl-1.0
sguan-actuate/birt
chart/org.eclipse.birt.chart.examples/src/org/eclipse/birt/chart/examples/view/models/LegendFormat.java
6113
/*********************************************************************** * Copyright (c) 2004, 2005 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation ***********************************************************************/ package org.eclipse.birt.chart.examples.view.models; import org.eclipse.birt.chart.model.Chart; import org.eclipse.birt.chart.model.ChartWithAxes; import org.eclipse.birt.chart.model.attribute.Anchor; import org.eclipse.birt.chart.model.attribute.AxisType; import org.eclipse.birt.chart.model.attribute.IntersectionType; import org.eclipse.birt.chart.model.attribute.LegendItemType; import org.eclipse.birt.chart.model.attribute.LineStyle; import org.eclipse.birt.chart.model.attribute.Position; import org.eclipse.birt.chart.model.attribute.TickStyle; import org.eclipse.birt.chart.model.attribute.impl.ColorDefinitionImpl; import org.eclipse.birt.chart.model.attribute.impl.GradientImpl; import org.eclipse.birt.chart.model.component.Axis; import org.eclipse.birt.chart.model.component.Series; import org.eclipse.birt.chart.model.component.impl.SeriesImpl; import org.eclipse.birt.chart.model.data.BaseSampleData; import org.eclipse.birt.chart.model.data.DataFactory; import org.eclipse.birt.chart.model.data.NumberDataSet; import org.eclipse.birt.chart.model.data.OrthogonalSampleData; import org.eclipse.birt.chart.model.data.SampleData; import org.eclipse.birt.chart.model.data.SeriesDefinition; import org.eclipse.birt.chart.model.data.TextDataSet; import org.eclipse.birt.chart.model.data.impl.NumberDataSetImpl; import org.eclipse.birt.chart.model.data.impl.SeriesDefinitionImpl; import org.eclipse.birt.chart.model.data.impl.TextDataSetImpl; import org.eclipse.birt.chart.model.impl.ChartWithAxesImpl; import org.eclipse.birt.chart.model.layout.Legend; import org.eclipse.birt.chart.model.layout.TitleBlock; import org.eclipse.birt.chart.model.type.BarSeries; import org.eclipse.birt.chart.model.type.impl.BarSeriesImpl; public class LegendFormat { public static final Chart createLegendFormat( ) { ChartWithAxes cwaBar = ChartWithAxesImpl.create( ); cwaBar.setType( "Bar Chart" ); //$NON-NLS-1$ cwaBar.setSubType( "Side-by-side" ); //$NON-NLS-1$ // Plot cwaBar.getBlock( ).setBackground( ColorDefinitionImpl.WHITE( ) ); cwaBar.getBlock( ).getOutline( ).setVisible( true ); // Title TitleBlock tb = cwaBar.getTitle( ); tb.setBackground( GradientImpl.create( ColorDefinitionImpl.create( 200, 200, 244 ), ColorDefinitionImpl.create( 250, 122, 253 ), 0, false ) ); tb.getOutline( ).setStyle( LineStyle.DASHED_LITERAL ); tb.getOutline( ).setColor( ColorDefinitionImpl.create( 0, 100, 245 ) ); tb.getOutline( ).setThickness( 1 ); tb.getOutline( ).setVisible( true ); tb.getLabel( ) .getCaption( ) .setValue( "Formatted Legend and Title Chart" ); //$NON-NLS-1$ tb.getLabel( ).getCaption( ).setColor( ColorDefinitionImpl.GREEN( ) ); tb.getLabel( ).setShadowColor( ColorDefinitionImpl.YELLOW( ) ); tb.getLabel( ).getOutline( ).setVisible( true ); // Legend Legend lg = cwaBar.getLegend( ); lg.getText( ).getFont( ).setSize( 10 ); lg.getText( ).getFont( ).setBold( true ); lg.getInsets( ).set( 10, 5, 0, 0 ); lg.getOutline( ).setStyle( LineStyle.DASH_DOTTED_LITERAL ); lg.getOutline( ).setColor( ColorDefinitionImpl.create( 214, 100, 12 ) ); lg.getOutline( ).setVisible( true ); lg.setBackground( GradientImpl.create( ColorDefinitionImpl.create( 225, 225, 255 ), ColorDefinitionImpl.create( 255, 255, 225 ), -35, false ) ); lg.setAnchor( Anchor.NORTH_LITERAL ); lg.setItemType( LegendItemType.CATEGORIES_LITERAL ); lg.getClientArea( ).setBackground( ColorDefinitionImpl.ORANGE( ) ); lg.setPosition( Position.LEFT_LITERAL ); // X-Axis Axis xAxisPrimary = cwaBar.getPrimaryBaseAxes( )[0]; xAxisPrimary.setType( AxisType.TEXT_LITERAL ); xAxisPrimary.getMajorGrid( ).setTickStyle( TickStyle.BELOW_LITERAL ); xAxisPrimary.getOrigin( ).setType( IntersectionType.MIN_LITERAL ); // Y-Axis Axis yAxisPrimary = cwaBar.getPrimaryOrthogonalAxis( xAxisPrimary ); yAxisPrimary.getMajorGrid( ).setTickStyle( TickStyle.LEFT_LITERAL ); yAxisPrimary.setType( AxisType.LINEAR_LITERAL ); yAxisPrimary.getLabel( ).getCaption( ).getFont( ).setRotation( 90 ); // Data Set TextDataSet categoryValues = TextDataSetImpl.create( new String[]{ "Item 1", "Item 2", "Item 3", "Item 4", "Item 5"} );//$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ NumberDataSet orthoValues = NumberDataSetImpl.create( new double[]{ 14.3, 20.9, 7.6, -2.0, 9.5 } ); SampleData sd = DataFactory.eINSTANCE.createSampleData( ); BaseSampleData sdBase = DataFactory.eINSTANCE.createBaseSampleData( ); sdBase.setDataSetRepresentation( "" );//$NON-NLS-1$ sd.getBaseSampleData( ).add( sdBase ); OrthogonalSampleData sdOrthogonal = DataFactory.eINSTANCE.createOrthogonalSampleData( ); sdOrthogonal.setDataSetRepresentation( "" );//$NON-NLS-1$ sdOrthogonal.setSeriesDefinitionIndex( 0 ); sd.getOrthogonalSampleData( ).add( sdOrthogonal ); cwaBar.setSampleData( sd ); // X-Series Series seCategory = SeriesImpl.create( ); seCategory.setDataSet( categoryValues ); SeriesDefinition sdX = SeriesDefinitionImpl.create( ); sdX.getSeriesPalette( ).shift( -4 ); xAxisPrimary.getSeriesDefinitions( ).add( sdX ); sdX.getSeries( ).add( seCategory ); // Y-Series BarSeries bs = (BarSeries) BarSeriesImpl.create( ); bs.setDataSet( orthoValues ); bs.getLabel( ).setVisible( true ); bs.setTranslucent( true ); bs.setLabelPosition( Position.INSIDE_LITERAL ); SeriesDefinition sdY = SeriesDefinitionImpl.create( ); sdY.getSeriesPalette( ).shift( -1 ); yAxisPrimary.getSeriesDefinitions( ).add( sdY ); sdY.getSeries( ).add( bs ); return cwaBar; } }
epl-1.0
pleacu/jbosstools-fuse-extras
jboss-fuse-sap-tool-suite/plugins/org.fusesource.ide.sap.ui/src/org/fusesource/ide/sap/ui/validator/ClientNumberValidator.java
1565
/******************************************************************************* * Copyright (c) 2014 Red Hat, Inc. * Distributed under license by Red Hat, Inc. All rights reserved. * This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Red Hat, Inc. - initial API and implementation * William Collins punkhornsw@gmail.com ******************************************************************************/ package org.fusesource.ide.sap.ui.validator; import org.eclipse.core.databinding.validation.IValidator; import org.eclipse.core.databinding.validation.ValidationStatus; import org.eclipse.core.runtime.IStatus; import org.fusesource.ide.sap.ui.Messages; public class ClientNumberValidator implements IValidator { @Override public IStatus validate(Object value) { if (value instanceof String) { String strValue = (String) value; if (strValue == null || strValue.length() == 0) return ValidationStatus.ok(); if (strValue.length() != 3) { return ValidationStatus.error(Messages.ClientNumberValidator_SapClientMustBeAThreeDigitNumericString); } try { Integer.parseInt(strValue); return ValidationStatus.ok(); } catch (NumberFormatException e) { return ValidationStatus.error(Messages.ClientNumberValidator_SapClientMustBeAThreeDigitNumericString); } } return ValidationStatus.error(Messages.ClientNumberValidator_SapClientMustBeAThreeDigitNumericString); } }
epl-1.0
akervern/che
ide/che-core-ide-ui/src/main/java/org/eclipse/che/ide/ui/button/ConsoleButtonFactory.java
907
/* * Copyright (c) 2012-2018 Red Hat, Inc. * This program and the accompanying materials are made * available under the terms of the Eclipse Public License 2.0 * which is available at https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * Red Hat, Inc. - initial API and implementation */ package org.eclipse.che.ide.ui.button; import javax.validation.constraints.NotNull; import org.vectomatic.dom.svg.ui.SVGResource; /** @author Igor Vinokur */ public interface ConsoleButtonFactory { /** * Creates console button widget with special icon. * * @param prompt prompt for current button which is displayed on special popup widget * @param resource icon which need set to button * @return an instance of {@link ConsoleButton} */ @NotNull ConsoleButton createConsoleButton(@NotNull String prompt, @NotNull SVGResource resource); }
epl-1.0
viatra/VIATRA-Generator
Solvers/VIATRA-Solver/org.eclipse.viatra.dse/src/org/eclipse/viatra/dse/visualizer/DesignSpaceVisualizerOptions.java
1775
/******************************************************************************* * Copyright (c) 2010-2014, Miklos Foldenyi, Andras Szabolcs Nagy, Abel Hegedus, Akos Horvath, Zoltan Ujhelyi and Daniel Varro * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0 which is available at * http://www.eclipse.org/legal/epl-v20.html. * * SPDX-License-Identifier: EPL-2.0 *******************************************************************************/ package org.eclipse.viatra.dse.visualizer; public class DesignSpaceVisualizerOptions { public boolean showExplorationTrace = true; public boolean showStateCodes = true; public boolean showTransitionCodes = true; public DesignSpaceVisualizerOptions withOutExploraionTrace() { showExplorationTrace = false; return this; } public DesignSpaceVisualizerOptions withOutstateCodes() { showStateCodes = false; return this; } public DesignSpaceVisualizerOptions withOutTransitionCodes() { showTransitionCodes = false; return this; } public boolean isShowExplorationTrace() { return showExplorationTrace; } public void setShowExplorationTrace(boolean showExplorationTrace) { this.showExplorationTrace = showExplorationTrace; } public boolean isShowStateCodes() { return showStateCodes; } public void setShowStateCodes(boolean showStateCodes) { this.showStateCodes = showStateCodes; } public boolean isShowTransitionCodes() { return showTransitionCodes; } public void setShowTransitionCodes(boolean showTransitionCodes) { this.showTransitionCodes = showTransitionCodes; } }
epl-1.0
jon-bell/junit
src/test/java/org/junit/runners/model/FrameworkFieldTest.java
1033
package org.junit.runners.model; import static org.junit.Assert.assertTrue; import static org.junit.rules.ExpectedException.none; import java.lang.reflect.Field; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; public class FrameworkFieldTest { @Rule public final ExpectedException thrown = none(); @Test public void cannotBeCreatedWithoutUnderlyingField() { thrown.expect(NullPointerException.class); thrown.expectMessage("FrameworkField cannot be created without an underlying field."); new FrameworkField(null); } @Test public void hasToStringWhichPrintsFieldName() throws Exception { Field field = ClassWithDummyField.class.getField("dummyField"); FrameworkField frameworkField = new FrameworkField(field); assertTrue(frameworkField.toString().contains("dummyField")); } private static class ClassWithDummyField { @SuppressWarnings("unused") public final int dummyField = 0; } }
epl-1.0
ControlSystemStudio/cs-studio
applications/scan/scan-plugins/org.csstudio.scan/src/org/csstudio/scan/data/ScanSampleFactory.java
3346
/******************************************************************************* * Copyright (c) 2011 Oak Ridge National Laboratory. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * The scan engine idea is based on the "ScanEngine" developed * by the Software Services Group (SSG), Advanced Photon Source, * Argonne National Laboratory, * Copyright (c) 2011 , UChicago Argonne, LLC. * * This implementation, however, contains no SSG "ScanEngine" source code * and is not endorsed by the SSG authors. ******************************************************************************/ package org.csstudio.scan.data; import java.time.Instant; /** Factory for {@link ScanSample} instances * @author Kay Kasemir */ @SuppressWarnings("nls") public class ScanSampleFactory { /** Create ScanSample for plain number * @param timestamp Time stamp * @param serial Serial to identify when the sample was taken * @param numbers {@link Number}s * @return {@link ScanSample} * @throws IllegalArgumentException if the value type is not handled */ public static ScanSample createSample(final Instant timestamp, final long serial, final Number... numbers) throws IllegalArgumentException { if (numbers.length <= 0) throw new IllegalArgumentException("Missing values"); return new NumberScanSample(timestamp, serial, numbers); } /** Create ScanSample for strings * @param timestamp Time stamp * @param serial Serial to identify when the sample was taken * @param values {@link String}s * @return {@link ScanSample} * @throws IllegalArgumentException if the value type is not handled */ public static ScanSample createSample(final Instant timestamp, final long serial, final String... values) throws IllegalArgumentException { if (values.length <= 0) throw new IllegalArgumentException("Missing values"); return new StringScanSample(timestamp, serial, values); } /** Create ScanSample for plain number or text value * @param timestamp Time stamp * @param serial Serial to identify when the sample was taken * @param values Values, must all have the same type * @return {@link ScanSample} * @throws IllegalArgumentException if the value type is not handled */ public static ScanSample createSample(final Instant timestamp, final long serial, final Object... values) throws IllegalArgumentException { if (values.length <= 0) throw new IllegalArgumentException("Missing values"); if (values instanceof Number[]) return new NumberScanSample(timestamp, serial, (Number[]) values); else if (values instanceof String[]) return new StringScanSample(timestamp, serial, (String[]) values); else if (values.length == 1 && values[0] instanceof Double) return new NumberScanSample(timestamp, serial, (Double) values[0]); throw new IllegalArgumentException("Cannot handle values of type " + values[0].getClass().getName()); } }
epl-1.0
Charling-Huang/birt
model/org.eclipse.birt.report.model/src/org/eclipse/birt/report/model/api/simpleapi/IAction.java
5545
/******************************************************************************* * Copyright (c) 2005 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.report.model.api.simpleapi; import org.eclipse.birt.report.model.api.activity.SemanticException; import org.eclipse.birt.report.model.api.core.IStructure; /** * Script wrapper of <code>ActionHandle</code> * */ public interface IAction { /** * Gets the identifier of the hyperlink if the link type is * <code>ACTION_LINK_TYPE_HYPERLINK</code>. Otherwise, return null. * * @return the URI link expression in a string */ public String getURI( ); /** * Gets the name of the target browser window for the link. (Optional.) Used * only for the Hyperlink and Drill Through options. Otherwise, return null. * * @return the window name */ public String getTargetWindow( ); /** * Gets the link type of the action. The link type are defined in * DesignChoiceConstants and can be one of the following: * <p> * <ul> * <li><code>ACTION_LINK_TYPE_NONE</code> * <li><code>ACTION_LINK_TYPE_HYPERLINK</code> * <li><code>ACTION_LINK_TYPE_DRILLTHROUGH</code> * <li><code>ACTION_LINK_TYPE_BOOKMARK_LINK</code> * </ul> * * @return the string value of the link type * * @see org.eclipse.birt.report.model.api.elements.DesignChoiceConstants */ public String getLinkType( ); /** * Sets the link type of the action. The link type are defined in * DesignChoiceConstants and can be one of the following: * <p> * <ul> * <li><code>ACTION_LINK_TYPE_NONE</code> * <li><code>ACTION_LINK_TYPE_HYPERLINK</code> * <li><code>ACTION_LINK_TYPE_DRILLTHROUGH</code> * <li><code>ACTION_LINK_TYPE_BOOKMARK_LINK</code> * </ul> * * @param type * type of the action. * @throws SemanticException * if the <code>type</code> is not one of the above. */ public void setLinkType( String type ) throws SemanticException; /** * Sets the format type of the action. The format type for action are * defined in DesignChoiceConstants and can be one of the following: * * <p> * <ul> * <li><code>ACTION_FORMAT_TYPE_HTML</code> * <li><code>ACTION_FORMAT_TYPE_PDF</code> * </ul> * * @param type * the type of the action * @throws SemanticException */ public void setFormatType( String type ) throws SemanticException; /** * Gets the format type of the action. The format type for action are * defined in DesignChoiceConstants and can be one of the following: * * <p> * <ul> * <li><code>ACTION_FORMAT_TYPE_HTML</code> * <li><code>ACTION_FORMAT_TYPE_PDF</code> * </ul> * * @return the format type of the action */ public String getFormatType( ); /** * Sets the target window of the action. * * @param window * the target window name * @throws SemanticException * if this property is locked. */ public void setTargetWindow( String window ) throws SemanticException; /** * * Sets the hyperlink of this action. The link type will be changed to * <code>ACTION_LINK_TYPE_HYPERLINK</code>. * * @param uri * the hyperlink to set * @throws SemanticException * if the property is locked. */ public void setURI( String uri ) throws SemanticException; /** * Gets the name of the target report document if the link type is * <code>ACTION_LINK_TYPE_DRILLTHROUGH</code>. Otherwise, return null. * * @return the name of the target report document * @see #setReportName(String) */ public String getReportName( ); /** * Sets target report name for a drill-though link. The link type will be * changed to <code>ACTION_LINK_TYPE_DRILLTHROUGH</code>. The report name * can include relative or absolute names. If the suffix is omitted, it is * computed on the server by looking for a matching report. BIRT reports are * searched in the following order: 1) a BIRT report document or 2) a BIRT * report design. * * @param reportName * the name of the target report * @throws SemanticException * if the property is locked. * @see #getReportName() */ public void setReportName( String reportName ) throws SemanticException; /** * Gets the bookmark link if the link type is * <code>ACTION_LINK_TYPE_BOOKMARK_LINK</code>. Otherwise, return null. * * @return the bookmark link */ public String getTargetBookmark( ); /** * Sets the target bookmark defined within this same report, or another * report for a drill-though link. Call {@link #setLinkType(String)}to do * the link type change, it can either be * <code>ACTION_LINK_TYPE_DRILLTHROUGH</code> or * <code>ACTION_LINK_TYPE_BOOKMARK_LINK</code>. * * * @param bookmark * the bookmark value. * @throws SemanticException * if the property is locked. * @see #getTargetBookmark() */ public void setTargetBookmark( String bookmark ) throws SemanticException; /** * Gets the internal structure instance of this action. * * @return Action structure instance. */ public IStructure getStructure( ); }
epl-1.0
gavinying/kura
kura/org.eclipse.kura.wire.component.provider/src/main/java/org/eclipse/kura/internal/wire/asset/WireAssetOCD.java
3932
/******************************************************************************* * Copyright (c) 2018 Eurotech and/or its affiliates and others * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * *******************************************************************************/ package org.eclipse.kura.internal.wire.asset; import java.util.List; import org.eclipse.kura.asset.provider.BaseAssetOCD; import org.eclipse.kura.configuration.metatype.Option; import org.eclipse.kura.core.configuration.metatype.Tad; import org.eclipse.kura.core.configuration.metatype.Toption; import org.eclipse.kura.core.configuration.metatype.Tscalar; public class WireAssetOCD extends BaseAssetOCD { private static final String EMIT_ALL_CHANNELS_DESCRIPTION = "Specifies wheter the values of all READ or READ_WRITE channels should be emitted in case of a channel event." + " If set to true, the values for all channels will be read and emitted," + " if set to false, only the value for the channel related to the event will be emitted."; private static final String TIMESTAMP_MODE_DESCRIPTION = "If set to PER_CHANNEL, the component will emit a driver-generated timestamp per channel property." + " If set to SINGLE_ASSET_GENERATED, the component will emit a single timestamp per request, generated by the Asset itself before emitting the envelope. " + "If set to SINGLE_DRIVER_GENERATED_MAX or SINGLE_DRIVER_GENERATED_MIN, the component will emit a single driver generated timestamp being respectively" + " the max (most recent) or min (oldest) among the timestamps of the channels."; private static final String EMIT_ERRORS_DESCRIPTION = "Specifies wheter errors should be included or not in the emitted envelope"; private static void addOptions(Tad target, Enum<?>[] values) { final List<Option> options = target.getOption(); for (Enum<?> value : values) { final String name = value.name(); final Toption option = new Toption(); option.setLabel(name); option.setValue(name); options.add(option); } } public WireAssetOCD() { super(); final Tad emitAllChannelsAd = new Tad(); emitAllChannelsAd.setId(WireAssetOptions.EMIT_ALL_CHANNELS_PROP_NAME); emitAllChannelsAd.setName(WireAssetOptions.EMIT_ALL_CHANNELS_PROP_NAME); emitAllChannelsAd.setCardinality(0); emitAllChannelsAd.setType(Tscalar.BOOLEAN); emitAllChannelsAd.setDescription(EMIT_ALL_CHANNELS_DESCRIPTION); emitAllChannelsAd.setRequired(true); emitAllChannelsAd.setDefault("false"); addAD(emitAllChannelsAd); final Tad timestampModeAd = new Tad(); timestampModeAd.setId(WireAssetOptions.TIMESTAMP_MODE_PROP_NAME); timestampModeAd.setName(WireAssetOptions.TIMESTAMP_MODE_PROP_NAME); timestampModeAd.setCardinality(0); timestampModeAd.setType(Tscalar.STRING); timestampModeAd.setDescription(TIMESTAMP_MODE_DESCRIPTION); timestampModeAd.setRequired(true); timestampModeAd.setDefault(TimestampMode.PER_CHANNEL.name()); addOptions(timestampModeAd, TimestampMode.values()); addAD(timestampModeAd); final Tad emitErrorsAd = new Tad(); emitErrorsAd.setId(WireAssetOptions.EMIT_ERRORS_PROP_NAME); emitErrorsAd.setName(WireAssetOptions.EMIT_ERRORS_PROP_NAME); emitErrorsAd.setCardinality(0); emitErrorsAd.setType(Tscalar.BOOLEAN); emitErrorsAd.setDescription(EMIT_ERRORS_DESCRIPTION); emitErrorsAd.setRequired(true); emitErrorsAd.setDefault("false"); addAD(emitErrorsAd); } }
epl-1.0
ControlSystemStudio/cs-studio
applications/snl/snl-plugins/de.desy.language.snl.diagram.ui/src/de/desy/language/snl/diagram/ui/DiagramCreator.java
8778
package de.desy.language.snl.diagram.ui; import java.util.HashMap; import java.util.List; import java.util.Map; import org.eclipse.draw2d.geometry.Dimension; import org.eclipse.draw2d.geometry.Point; import de.desy.language.editor.core.parser.Node; import de.desy.language.snl.diagram.model.ModelElement; import de.desy.language.snl.diagram.model.SNLDiagram; import de.desy.language.snl.diagram.model.SNLElement; import de.desy.language.snl.diagram.model.SNLModel; import de.desy.language.snl.diagram.model.StateModel; import de.desy.language.snl.diagram.model.StateSetModel; import de.desy.language.snl.diagram.model.WhenConnection; import de.desy.language.snl.diagram.persistence.StateLayoutData; import de.desy.language.snl.parser.nodes.StateNode; import de.desy.language.snl.parser.nodes.StateSetNode; import de.desy.language.snl.parser.nodes.WhenNode; /** * Creates a SNL diagram based on the root node of the AST and the given layout * data. * * @author Kai Meyer, Sebastian Middeke (C1 WPS) * */ public class DiagramCreator { private static final int START_X = 50; private static final int START_Y = 50; private static final int DISTANCE_X = 300; private static final int DISTANCE_Y = 200; private static final int STATE_WIDTH = 100; private static final int STATE_HEIGHT = 50; private static final int STATESET_HEIGHT = 180; private static DiagramCreator _instance; private final Map<StateSetModel, HashMap<String, StateModel>> _stateSetMap; private final Map<WhenConnectionAnchors, Integer> _anchorMap; private final ConnectionBendPointCreator _bendPointCreator; private SNLDiagram _diagram; /** * Constructor. */ private DiagramCreator() { _stateSetMap = new HashMap<StateSetModel, HashMap<String, StateModel>>(); _anchorMap = new HashMap<WhenConnectionAnchors, Integer>(); _bendPointCreator = new ConnectionBendPointCreator(); _bendPointCreator.setSeparation(20); } public static DiagramCreator getInstance() { if (_instance == null) { _instance = new DiagramCreator(); } return _instance; } public SNLDiagram createDefaultDiagram() { final SNLDiagram diagram = new SNLDiagram(); return diagram; } public SNLDiagram createDiagram(final Node rootNode, Map<String, StateLayoutData> stateData, Map<String, List<Point>> connectionData, int separation) { assert stateData != null : "stateData != null"; assert connectionData != null : "connectionData != null"; resetContainer(); _bendPointCreator.setSeparation(separation); _diagram = new SNLDiagram(); addStateNodes(_diagram, rootNode, stateData); addWhenNodes(connectionData); return _diagram; } private void resetContainer() { _stateSetMap.clear(); _anchorMap.clear(); } private void addStateNodes(final SNLElement parentModel, final Node node, Map<String, StateLayoutData> stateData) { for (final Node child : node.getChildrenNodes()) { if (child instanceof StateNode) { final HashMap<String, StateModel> stateMap = _stateSetMap .get(parentModel); final int size = stateMap.size(); final StateNode stateNode = (StateNode) child; final StateModel state = new StateModel(); state.setStateNode(stateNode); state.setPropertyValue(SNLModel.PARENT, parentModel .getIdentifier()); String name = assembleMapKey(parentModel, state); StateLayoutData data = stateData.get(name); if (data == null) { int x = 2 * START_X + size * DISTANCE_X; int y = START_Y + (_stateSetMap.size() - 1) * DISTANCE_Y + (STATESET_HEIGHT - STATE_HEIGHT) / 2; state.setLocation(new Point(x, y)); state.setSize(new Dimension(STATE_WIDTH, STATE_HEIGHT)); } else { state.setLocation(data.getPoint()); state.setSize(data.getDimension()); } stateMap.put(stateNode.getSourceIdentifier(), state); parentModel.addChild(state); _diagram.addChild(state); } else if (child instanceof StateSetNode) { StateSetModel setModel = new StateSetModel(); setModel.setStateSetNode((StateSetNode) child); parentModel.addChild(setModel); if (!_stateSetMap.containsKey(setModel)) { _stateSetMap.put(setModel, new HashMap<String, StateModel>()); } if (child.hasChildren()) { addStateNodes(setModel, child, stateData); } String name = setModel.getIdentifier(); StateLayoutData data = stateData.get(name); if (data == null) { int childCount = _stateSetMap.get(setModel).size(); int setWidth = 2 * START_X + (childCount - 1) * DISTANCE_X + STATE_WIDTH; setModel.setSize(new Dimension(setWidth, STATESET_HEIGHT)); int y = START_Y + (_stateSetMap.size() - 1) * DISTANCE_Y; setModel.setLocation(new Point(START_X, y)); } else { setModel.setLocation(data.getPoint()); setModel.setSize(data.getDimension()); } } else { if (child.hasChildren()) { addStateNodes(parentModel, child, stateData); } } } } private void addWhenNodes(Map<String, List<Point>> connectionData) { for (StateSetModel parentModel : _stateSetMap.keySet()) { Map<String, StateModel> map = _stateSetMap.get(parentModel); for (final StateModel stateModel : map.values()) { final StateNode stateNode = stateModel.getStateNode(); if (stateNode.hasChildren()) { for (final Node child : stateNode.getChildrenNodes()) { addWhenNodes(parentModel, stateModel, map, child, connectionData); } } } } } private void addWhenNodes(final StateSetModel parentModel, final StateModel stateModel, final Map<String, StateModel> map, final Node node, Map<String, List<Point>> connectionData) { if (node instanceof WhenNode) { final WhenNode when = (WhenNode) node; final String followingState = when.getFollowingState(); final StateModel destination = map.get(followingState); if (destination != null && !destination.equals(stateModel)) { final WhenConnection whenCon = new WhenConnection(stateModel, destination); whenCon.setWhenNode(when); whenCon.setPropertyValue(SNLModel.PARENT, parentModel .getIdentifier()); String name = assembleMapKey(parentModel, stateModel).concat( ".(" + whenCon.getIdentifier() + ")"); List<Point> list = connectionData.get(name); if (list == null) { final WhenConnectionAnchors anchors = new WhenConnectionAnchors( stateModel, destination); final WhenConnectionAnchors reversAnchors = new WhenConnectionAnchors( destination, stateModel); if (_anchorMap.containsKey(anchors)) { int count = _anchorMap.get(anchors); count++; _bendPointCreator.create(whenCon, count); _anchorMap.put(anchors, new Integer(count)); } else { _anchorMap.put(anchors, new Integer(0)); _anchorMap.put(reversAnchors, new Integer(0)); } } else { int index = 0; for (Point bendPoint : list) { whenCon.addBendPoint(bendPoint, index); index++; } } } } } private String assembleMapKey(ModelElement parent, ModelElement child) { return parent.getIdentifier() + "." + child.getIdentifier(); } }
epl-1.0
clinique/openhab
bundles/binding/org.openhab.binding.zwave/src/main/java/org/openhab/binding/zwave/internal/protocol/commandclass/ZWaveVersionCommandClass.java
10898
/** * Copyright (c) 2010-2015, openHAB.org and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.openhab.binding.zwave.internal.protocol.commandclass; import java.util.HashMap; import java.util.Map; import org.openhab.binding.zwave.internal.protocol.SerialMessage; import org.openhab.binding.zwave.internal.protocol.ZWaveController; import org.openhab.binding.zwave.internal.protocol.ZWaveEndpoint; import org.openhab.binding.zwave.internal.protocol.ZWaveNode; import org.openhab.binding.zwave.internal.protocol.SerialMessage.SerialMessageClass; import org.openhab.binding.zwave.internal.protocol.SerialMessage.SerialMessagePriority; import org.openhab.binding.zwave.internal.protocol.SerialMessage.SerialMessageType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.thoughtworks.xstream.annotations.XStreamAlias; import com.thoughtworks.xstream.annotations.XStreamOmitField; /** * Handles the Version command class. The Version Command Class is * used to obtain the library type, the protocol version * used by the node, the individual command class versions * used by the node and the vendor specific application * version from a device. * @author Jan-Willem Spuij * @since 1.3.0 */ @XStreamAlias("versionCommandClass") public class ZWaveVersionCommandClass extends ZWaveCommandClass { @XStreamOmitField private static final Logger logger = LoggerFactory.getLogger(ZWaveVersionCommandClass.class); public static final int VERSION_GET = 0x11; public static final int VERSION_REPORT = 0x12; public static final int VERSION_COMMAND_CLASS_GET = 0x13; public static final int VERSION_COMMAND_CLASS_REPORT = 0x14; private LibraryType libraryType = LibraryType.LIB_UNKNOWN; private Double protocolVersion; private Double applicationVersion; /** * Creates a new instance of the ZWaveVersionCommandClass class. * @param node the node this command class belongs to * @param controller the controller to use * @param endpoint the endpoint this Command class belongs to */ public ZWaveVersionCommandClass(ZWaveNode node, ZWaveController controller, ZWaveEndpoint endpoint) { super(node, controller, endpoint); } /** * {@inheritDoc} */ @Override public CommandClass getCommandClass() { return CommandClass.VERSION; } /** * {@inheritDoc} */ @Override public void handleApplicationCommandRequest(SerialMessage serialMessage, int offset, int endpoint) { logger.trace("Handle Message Version Request"); logger.debug("NODE {}: Received Version Request", this.getNode().getNodeId()); int command = serialMessage.getMessagePayloadByte(offset); switch (command) { case VERSION_GET: case VERSION_COMMAND_CLASS_GET: logger.warn("Command {} not implemented.", command); return; case VERSION_REPORT: logger.debug("NODE {}: Process Version Report", this.getNode().getNodeId()); libraryType = LibraryType.getLibraryType(serialMessage.getMessagePayloadByte(offset + 1)); protocolVersion = (double)serialMessage.getMessagePayloadByte(offset + 2) + ((double)serialMessage.getMessagePayloadByte(offset + 3) / 10); applicationVersion = serialMessage.getMessagePayloadByte(offset + 4) + ((double)serialMessage.getMessagePayloadByte(offset + 5) / 10); logger.debug(String.format("NODE %d: Library Type = 0x%02x", this.getNode().getNodeId(), libraryType.key)); logger.debug(String.format("NODE %d: Protocol Version = %.1f", this.getNode().getNodeId(), protocolVersion)); logger.debug(String.format("NODE %d: Application Version = %.1f", this.getNode().getNodeId(), applicationVersion)); break; case VERSION_COMMAND_CLASS_REPORT: logger.debug("NODE {}: Process Version Command Class Report", this.getNode().getNodeId()); int commandClassCode = serialMessage.getMessagePayloadByte(offset + 1); int commandClassVersion = serialMessage.getMessagePayloadByte(offset + 2); CommandClass commandClass = CommandClass.getCommandClass(commandClassCode); if (commandClass == null) { logger.error(String.format("NODE %d: Unsupported command class 0x%02x", this.getNode().getNodeId(), commandClassCode)); return; } logger.debug("NODE {}: Requested Command Class = {}, Version = {}", this.getNode().getNodeId(), commandClass.getLabel(), commandClassVersion); // The version is set on the command class for this node. By updating the version, extra functionality is unlocked in the command class. // The messages are backwards compatible, so it's not a problem that there is a slight delay when the command class version is queried on the // node. ZWaveCommandClass zwaveCommandClass = this.getNode().getCommandClass(commandClass); if (zwaveCommandClass == null) { logger.error(String.format("NODE %d: Unsupported command class %s (0x%02x)", this.getNode().getNodeId(), commandClass.getLabel(), commandClassCode)); return; } // If the device reports version 0, it means it doesn't support this command class! if(commandClassVersion == 0) { logger.info("NODE {}: Command Class {} has version 0!", this.getNode().getNodeId(), commandClass.getLabel()); // TODO: We should remove the class // For now, just set the version to 1 to avoid a loop on initialisation commandClassVersion = 1; // this.getNode().removeCommandClass(zwaveCommandClass); } if (commandClassVersion > zwaveCommandClass.getMaxVersion()) { zwaveCommandClass.setVersion( zwaveCommandClass.getMaxVersion() ); logger.debug("NODE {}: Version = {}, version set to maximum supported by the binding. Enabling extra functionality.", this.getNode().getNodeId(), zwaveCommandClass.getMaxVersion()); } else { zwaveCommandClass.setVersion( commandClassVersion ); logger.debug("NODE {}: Version = {}, version set. Enabling extra functionality.", this.getNode().getNodeId(), commandClassVersion); } break; default: logger.warn(String.format("Unsupported Command 0x%02X for command class %s (0x%02X).", command, this.getCommandClass().getLabel(), this.getCommandClass().getKey())); } } /** * Gets a SerialMessage with the VERSION_GET command * @return the serial message */ public SerialMessage getVersionMessage() { logger.debug("NODE {}: Creating new message for command VERSION_GET", this.getNode().getNodeId()); SerialMessage result = new SerialMessage(this.getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.ApplicationCommandHandler, SerialMessagePriority.Config); byte[] newPayload = { (byte) this.getNode().getNodeId(), 2, (byte) getCommandClass().getKey(), (byte) VERSION_GET }; result.setMessagePayload(newPayload); return result; } /** * Gets a SerialMessage with the VERSION COMMAND CLASS GET command. * This version is used to differentiate between multiple versions of a command * and to enable extra functionality. * @param commandClass The command class to get the version for. * @return the serial message */ public SerialMessage getCommandClassVersionMessage(CommandClass commandClass) { logger.debug("NODE {}: Creating new message for application command VERSION_COMMAND_CLASS_GET command class {}", this.getNode().getNodeId(), commandClass.getLabel()); SerialMessage result = new SerialMessage(this.getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.ApplicationCommandHandler, SerialMessagePriority.Config); byte[] newPayload = { (byte) this.getNode().getNodeId(), 3, (byte) getCommandClass().getKey(), (byte) VERSION_COMMAND_CLASS_GET, (byte) commandClass.getKey() }; result.setMessagePayload(newPayload); return result; } /** * Check the version of a command class by sending a VERSION_COMMAND_CLASS_GET message to the node. * @param commandClass the command class to check the version for. * @return serial message to be sent */ public SerialMessage checkVersion(ZWaveCommandClass commandClass) { ZWaveVersionCommandClass versionCommandClass = (ZWaveVersionCommandClass)this.getNode().getCommandClass(CommandClass.VERSION); if (versionCommandClass == null) { logger.error(String.format("NODE %d: Version command class not supported," + "reverting to version 1 for command class %s (0x%02x)", this.getNode().getNodeId(), commandClass.getCommandClass().getLabel(), commandClass.getCommandClass().getKey())); return null; } return versionCommandClass.getCommandClassVersionMessage(commandClass.getCommandClass()); }; /** * Returns the current ZWave library type */ public LibraryType getLibraryType() { return libraryType; } /** * Returns the version of the protocol used by the device * @return Protocol version as double (version . subversion) */ public Double getProtocolVersion() { return protocolVersion; } /** * Returns the version of the firmware used by the device * @return Application version as double (version . subversion) */ public Double getApplicationVersion() { return applicationVersion; } public enum LibraryType { LIB_UNKNOWN(0,"Unknown"), LIB_CONTROLLER_STATIC(1,"Static Controller"), LIB_CONTROLLER(2,"Controller"), LIB_SLAVE_ENHANCED(3,"Slave Enhanced"), LIB_SLAVE(4,"Static Controller"), LIB_INSTALLER(5,"Static Controller"), LIB_SLAVE_ROUTING(5,"Static Controller"), LIB_CONTROLLER_BRIDGE(6,"Static Controller"), LIB_TEST(7,"Test"); /** * A mapping between the integer code and its corresponding Library type * to facilitate lookup by code. */ private static Map<Integer, LibraryType> libraryMapping; private int key; private String label; private LibraryType(int key, String label) { this.key = key; this.label = label; } private static void initMapping() { libraryMapping = new HashMap<Integer, LibraryType>(); for (LibraryType s : values()) { libraryMapping.put(s.key, s); } } /** * Lookup function based on the sensor type code. * Returns null if the code does not exist. * @param i the code to lookup * @return enumeration value of the sensor type. */ public static LibraryType getLibraryType(int i) { if (libraryMapping == null) { initMapping(); } if(libraryMapping.get(i) == null) return LIB_UNKNOWN; return libraryMapping.get(i); } /** * @return the key */ public int getKey() { return key; } /** * @return the label */ public String getLabel() { return label; } } }
epl-1.0
nickstanish/ice
org.eclipse.ice.viz.service.geometry/src/org/eclipse/ice/viz/service/geometry/shapes/AbstractShape.java
10203
/******************************************************************************* * Copyright (c) 2012, 2014 UT-Battelle, LLC. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Initial API and implementation and/or initial documentation - Jay Jay Billings, * Jordan H. Deyton, Dasha Gorin, Alexander J. McCaskey, Taylor Patterson, * Claire Saunders, Matthew Wang, Anna Wojtowicz *******************************************************************************/ package org.eclipse.ice.viz.service.geometry.shapes; import java.util.ArrayList; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.bind.annotation.XmlTransient; import org.eclipse.ice.viz.service.datastructures.VizObject.VizObject; import org.eclipse.ice.viz.service.datastructures.VizObject.IVizUpdateableListener; /** * <p> * Implements a number of operations shared between the components in the Shape * composite pattern * </p> * * @author Jay Jay Billings */ @XmlSeeAlso({ PrimitiveShape.class, ComplexShape.class }) @XmlAccessorType(XmlAccessType.FIELD) public abstract class AbstractShape extends VizObject implements IShape { /** * <p> * Stores the list of keys for the property list * </p> * */ @XmlElement(name = "Keys") private ArrayList<String> keys; /** * <p> * Stores the list of values for the property list * </p> * */ @XmlElement(name = "Values") private ArrayList<String> values; /** * <p> * The matrix transformation applied to the shape * </p> * <p> * In the case of a ComplexShape, each transformation affects its child * shapes, so in order to calculate the final transformation of an * individual PrimitiveShape, you must take the matrix product of all of the * ancestors' transformations. * </p> * <p> * The transformation matrix applied to this node in the CSG tree * </p> * */ @XmlElement(name = "Transformation") protected Transformation transformation; /** * <p> * If applicable, the parent of the shape in the CSG tree * </p> * */ @XmlTransient private IShape parent; /** * <p> * Initializes the transformation matrix, creates the array containing the * key/value property pairs, and creates a listeners list * </p> * */ public AbstractShape() { // Initialize transformation transformation = new Transformation(); // Create properties lists keys = new ArrayList<String>(); values = new ArrayList<String>(); // Create listeners list listeners = new ArrayList<IVizUpdateableListener>(); } /** * <p> * Returns a copy of the transformation matrix associated with this shape * node * </p> * * @return <p> * The transformation matrix applied to this node in the CSG tree * </p> */ @Override public Transformation getTransformation() { return this.transformation; } /** * <p> * Replaces the transformation matrix with a copy of the given Matrix4x4 * </p> * <p> * Returns whether the setting was successful * </p> * * @param transformation * <p> * The transformation matrix to be applied to the shape * </p> * @return <p> * True if setting the transformation was successful, false * otherwise * </p> */ @Override public boolean setTransformation(Transformation transformation) { // Fail if null and return false if (transformation == null) { return false; } // Otherwise set and return true this.transformation = transformation; // Notify listeners and return success notifyListeners(); return true; } /** * <p> * Returns the value associated with the property key * </p> * <p> * If the key does not exist, this operation returns null. * </p> * * @param key * <p> * The key corresponding to the desired value * </p> * @return <p> * The value associated with the property key * </p> */ @Override public String getProperty(String key) { if (key == null || "".equals(key)) { return null; } // Get index of key int index = keys.indexOf(key); if (index < 0) { return null; } // Return the value try { return values.get(index); } catch (IndexOutOfBoundsException e) { return null; } } /** * <p> * Sets the property value associated with the key string * </p> * <p> * If the key does not yet exist, append the key/value pair to the end of * the property list. If it exists, find and replace the property value with * the new one. * </p> * * @param key * <p> * The new key * </p> * @param value * <p> * The new value * </p> * @return <p> * True if the property setting is valid, false otherwise * </p> */ @Override public boolean setProperty(String key, String value) { // Validate parameters if (key == null || "".equals(key) || value == null) { return false; } // Find index of key int index = keys.indexOf(key); // Update if (index < 0) { // Insert new value keys.add(key); values.add(value); } else { // Modify the value values.set(index, value); } // Notify listeners and return success notifyListeners(); return true; } /** * <p> * Removes the value associated with the key in the properties list * </p> * <p> * This operation returns whether the key was found and removed. * </p> * * @param key * <p> * The key associated with the value to remove * </p> * @return <p> * True if the value was found and removed, false otherwise * </p> */ @Override public boolean removeProperty(String key) { // Validate parameters if (key == null) { return false; } // Get index of key int index = keys.indexOf(key); if (index < 0) { return false; } keys.remove(index); values.remove(index); // Notify listeners and return success notifyListeners(); return true; } /** * <p> * This operation returns the hashcode value of the shape. * </p> * * @return <p> * The hashcode of the object * </p> */ @Override public int hashCode() { // Get initial hash code int hash = super.hashCode(); // Hash the transformation hash = 31 * hash + transformation.hashCode(); // Hash the properties hash = 31 * hash + keys.hashCode(); hash = 31 * hash + values.hashCode(); return hash; } /** * <p> * This operation is used to check equality between this shape and another * shape. It returns true if the shape are equal and false if they are not. * </p> * * @param otherObject * <p> * The other ICEObject that should be compared with this one. * </p> * @return <p> * True if the ICEObjects are equal, false otherwise. * </p> */ @Override public boolean equals(Object otherObject) { // Check if a similar reference if (this == otherObject) { return true; } // Check that the other object is not null and an instance of the // PrimitiveShape if (otherObject == null || !(otherObject instanceof AbstractShape)) { return false; } // Check that these objects have the same ICEObject data if (!super.equals(otherObject)) { return false; } // At this point, other object must be a PrimitiveShape, so cast it AbstractShape abstractShape = (AbstractShape) otherObject; // Check for unequal transformation if (!transformation.equals(abstractShape.transformation)) { return false; } // Check for unequal properties if (!keys.equals(abstractShape.keys) || !values.equals(abstractShape.values)) { return false; } // The two objects are equal return true; } /** * <p> * Copies the contents of a shape into the current object using a deep copy * </p> * * @param iceObject * <p> * The ICEObject from which the values should be copied * </p> */ public void copy(AbstractShape iceObject) { // Return if object is null if (iceObject == null) { return; } // Copy the ICEObject data super.copy(iceObject); // Copy transformation this.transformation = (Transformation) iceObject.transformation.clone(); // Copy properties this.keys.clear(); this.values.clear(); for (String key : iceObject.keys) { this.keys.add(key); } for (String value : iceObject.values) { this.values.add(value); } this.notifyListeners(); } /** * <p> * This operation directs the Component to call back to an IComponentVisitor * so that the visitor can perform its required actions for the exact type * of the Component. * </p> * * @param visitor * <p> * The visitor querying the type of the object * </p> */ public void accept(IShapeVisitor visitor) { } /** * <p> * Notifies all IUpdateableListeners in the listener list that an event has * occurred which has changed the state of the shape * </p> * */ @Override protected void notifyListeners() { // Let the base class handle most of the notifications super.notifyListeners(); // Notify the parent's listeners if (parent != null) { ((AbstractShape) parent).notifyListeners(); } } /** * <p> * Returns the parent associated with this shape, or null if the shape does * not have a parent * </p> * * @return <p> * The parent of the shape * </p> */ @Override public IShape getParent() { return parent; } /** * <p> * Sets the parent of the IShape * </p> * * @param parent * <p> * The parent of the IShape * </p> */ public void setParent(IShape parent) { this.parent = parent; } }
epl-1.0
jesusaplsoft/FindAllBugs
findbugs/src/java/edu/umd/cs/findbugs/graph/GraphVertex.java
1242
/* * Generic graph library * Copyright (C) 2000,2003,2004 University of Maryland * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ // $Revision: 1.8 $ package edu.umd.cs.findbugs.graph; /** * GraphVertex interface; represents a vertex in a graph. */ public interface GraphVertex<ActualVertexType> extends Comparable<ActualVertexType> { /** * Get the numeric label for this vertex. */ public int getLabel(); /** * Set the numeric label for this vertex. */ public void setLabel(int label); } // vim:ts=4
gpl-2.0
ianopolous/JPC
src/org/jpc/emulator/execution/opcodes/pm/inc_Ew_mem.java
2099
/* JPC: An x86 PC Hardware Emulator for a pure Java Virtual Machine Copyright (C) 2012-2013 Ian Preston This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Details (including contact information) can be found at: jpc.sourceforge.net or the developer website sourceforge.net/projects/jpc/ End of licence header */ package org.jpc.emulator.execution.opcodes.pm; import org.jpc.emulator.execution.*; import org.jpc.emulator.execution.decoder.*; import org.jpc.emulator.processor.*; import org.jpc.emulator.processor.fpu64.*; import static org.jpc.emulator.processor.Processor.*; public class inc_Ew_mem extends Executable { final Pointer op1; public inc_Ew_mem(int blockStart, int eip, int prefices, PeekableInputStream input) { super(blockStart, eip); int modrm = input.readU8(); op1 = Modrm.getPointer(prefices, modrm, input); } public Branch execute(Processor cpu) { cpu.cf = Processor.getCarryFlag(cpu.flagStatus, cpu.cf, cpu.flagOp1, cpu.flagOp2, cpu.flagResult, cpu.flagIns); cpu.flagOp1 = (short)op1.get16(cpu); cpu.flagOp2 = 1; cpu.flagResult = (short)(cpu.flagOp1 + 1); op1.set16(cpu, (short)cpu.flagResult); cpu.flagIns = UCodes.ADD16; cpu.flagStatus = NCF; return Branch.None; } public boolean isBranch() { return false; } public String toString() { return this.getClass().getName(); } }
gpl-2.0
b-cuts/esper
esper/src/test/java/com/espertech/esper/regression/db/TestDatabaseNoJoinIterate.java
7991
/* * ************************************************************************************* * Copyright (C) 2006-2015 EsperTech, Inc. All rights reserved. * * http://www.espertech.com/esper * * http://www.espertech.com * * ---------------------------------------------------------------------------------- * * The software in this package is published under the terms of the GPL license * * a copy of which has been included with this distribution in the license.txt file. * * ************************************************************************************* */ package com.espertech.esper.regression.db; import com.espertech.esper.client.*; import com.espertech.esper.client.scopetest.EPAssertionUtil; import com.espertech.esper.client.scopetest.SupportUpdateListener; import com.espertech.esper.core.service.EPStatementSPI; import com.espertech.esper.metrics.instrumentation.InstrumentationHelper; import com.espertech.esper.support.bean.SupportBean; import com.espertech.esper.support.client.SupportConfigFactory; import com.espertech.esper.support.epl.SupportDatabaseService; import junit.framework.TestCase; import java.util.Properties; public class TestDatabaseNoJoinIterate extends TestCase { private EPServiceProvider epService; private SupportUpdateListener listener; public void setUp() { ConfigurationDBRef configDB = new ConfigurationDBRef(); configDB.setDriverManagerConnection(SupportDatabaseService.DRIVER, SupportDatabaseService.FULLURL, new Properties()); configDB.setConnectionLifecycleEnum(ConfigurationDBRef.ConnectionLifecycleEnum.RETAIN); configDB.setConnectionCatalog("test"); configDB.setConnectionReadOnly(true); configDB.setConnectionTransactionIsolation(1); configDB.setConnectionAutoCommit(true); Configuration configuration = SupportConfigFactory.getConfiguration(); configuration.addDatabaseReference("MyDB", configDB); epService = EPServiceProviderManager.getProvider("TestDatabaseJoinRetained", configuration); epService.initialize(); if (InstrumentationHelper.ENABLED) { InstrumentationHelper.startTest(epService, this.getClass(), getName());} } protected void tearDown() throws Exception { if (InstrumentationHelper.ENABLED) { InstrumentationHelper.endTest();} listener = null; epService.destroy(); } public void testExpressionPoll() { epService.getEPAdministrator().getConfiguration().addEventType("SupportBean", SupportBean.class); epService.getEPAdministrator().createEPL("create variable boolean queryvar_bool"); epService.getEPAdministrator().createEPL("create variable int queryvar_int"); epService.getEPAdministrator().createEPL("create variable int lower"); epService.getEPAdministrator().createEPL("create variable int upper"); epService.getEPAdministrator().createEPL("on SupportBean set queryvar_int=intPrimitive, queryvar_bool=boolPrimitive, lower=intPrimitive,upper=intBoxed"); // Test int and singlerow String stmtText = "select myint from sql:MyDB ['select myint from mytesttable where ${queryvar_int -2} = mytesttable.mybigint']"; EPStatementSPI stmt = (EPStatementSPI) epService.getEPAdministrator().createEPL(stmtText); assertFalse(stmt.getStatementContext().isStatelessSelect()); listener = new SupportUpdateListener(); stmt.addListener(listener); EPAssertionUtil.assertPropsPerRowAnyOrder(stmt.iterator(), new String[]{"myint"}, null); sendSupportBeanEvent(5); EPAssertionUtil.assertPropsPerRowAnyOrder(stmt.iterator(), new String[]{"myint"}, new Object[][]{{30}}); stmt.destroy(); assertFalse(listener.isInvoked()); // Test multi-parameter and multi-row stmtText = "select myint from sql:MyDB ['select myint from mytesttable where mytesttable.mybigint between ${queryvar_int-2} and ${queryvar_int+2}'] order by myint"; stmt = (EPStatementSPI) epService.getEPAdministrator().createEPL(stmtText); EPAssertionUtil.assertPropsPerRowAnyOrder(stmt.iterator(), new String[]{"myint"}, new Object[][]{{30}, {40}, {50}, {60}, {70}}); stmt.destroy(); // Test substitution parameters try { stmtText = "select myint from sql:MyDB ['select myint from mytesttable where mytesttable.mybigint between ${?} and ${queryvar_int+?}'] order by myint"; epService.getEPAdministrator().prepareEPL(stmtText); fail(); } catch (EPStatementException ex) { assertEquals("EPL substitution parameters are not allowed in SQL ${...} expressions, consider using a variable instead [select myint from sql:MyDB ['select myint from mytesttable where mytesttable.mybigint between ${?} and ${queryvar_int+?}'] order by myint]", ex.getMessage()); } } public void testVariablesPoll() { epService.getEPAdministrator().getConfiguration().addEventType("SupportBean", SupportBean.class); epService.getEPAdministrator().createEPL("create variable boolean queryvar_bool"); epService.getEPAdministrator().createEPL("create variable int queryvar_int"); epService.getEPAdministrator().createEPL("create variable int lower"); epService.getEPAdministrator().createEPL("create variable int upper"); epService.getEPAdministrator().createEPL("on SupportBean set queryvar_int=intPrimitive, queryvar_bool=boolPrimitive, lower=intPrimitive,upper=intBoxed"); // Test int and singlerow String stmtText = "select myint from sql:MyDB ['select myint from mytesttable where ${queryvar_int} = mytesttable.mybigint']"; EPStatement stmt = epService.getEPAdministrator().createEPL(stmtText); listener = new SupportUpdateListener(); stmt.addListener(listener); EPAssertionUtil.assertPropsPerRowAnyOrder(stmt.iterator(), new String[]{"myint"}, null); sendSupportBeanEvent(5); EPAssertionUtil.assertPropsPerRowAnyOrder(stmt.iterator(), new String[]{"myint"}, new Object[][]{{50}}); stmt.destroy(); assertFalse(listener.isInvoked()); // Test boolean and multirow stmtText = "select * from sql:MyDB ['select mybigint, mybool from mytesttable where ${queryvar_bool} = mytesttable.mybool and myint between ${lower} and ${upper} order by mybigint']"; stmt = epService.getEPAdministrator().createEPL(stmtText); stmt.addListener(listener); String[] fields = new String[] {"mybigint", "mybool"}; EPAssertionUtil.assertPropsPerRowAnyOrder(stmt.iterator(), fields, null); sendSupportBeanEvent(true, 10, 40); EPAssertionUtil.assertPropsPerRowAnyOrder(stmt.iterator(), fields, new Object[][]{{1L, true}, {4L, true}}); sendSupportBeanEvent(false, 30, 80); EPAssertionUtil.assertPropsPerRowAnyOrder(stmt.iterator(), fields, new Object[][]{{3L, false}, {5L, false}, {6L, false}}); sendSupportBeanEvent(true, 20, 30); EPAssertionUtil.assertPropsPerRowAnyOrder(stmt.iterator(), fields, null); sendSupportBeanEvent(true, 20, 60); EPAssertionUtil.assertPropsPerRowAnyOrder(stmt.iterator(), fields, new Object[][]{{4L, true}}); } private void sendSupportBeanEvent(int intPrimitive) { SupportBean bean = new SupportBean(); bean.setIntPrimitive(intPrimitive); epService.getEPRuntime().sendEvent(bean); } private void sendSupportBeanEvent(boolean boolPrimitive, int intPrimitive, int intBoxed) { SupportBean bean = new SupportBean(); bean.setBoolPrimitive(boolPrimitive); bean.setIntPrimitive(intPrimitive); bean.setIntBoxed(intBoxed); epService.getEPRuntime().sendEvent(bean); } }
gpl-2.0
v7fasttrack/virtuoso-opensource
binsrc/samples/JDBC/jdk1.5/JDBCDemo/WebJDBCDemo.java
1619
/* * WebJDBCDemo.java * * $Id$ * * Sample JDBC program * * This file is part of the OpenLink Software Virtuoso Open-Source (VOS) * project. * * Copyright (C) 1998-2014 OpenLink Software * * This project is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; only version 2 of the License, dated June 1991. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * */ import java.awt.*; import java.applet.*; public class WebJDBCDemo extends Applet { public void init() { super.init(); String theServer = getCodeBase().getHost(); String sNumParams = getParameter("numParams"); int numParams = 0; String[] params; if (sNumParams != null) numParams = Integer.parseInt(sNumParams); System.out.println("numParams = "+numParams); params = new String[numParams]; for (int i = 0; i < numParams; i++) { params[i] = "jdbc:virtuoso://"+theServer+getParameter("URL"+Integer.toString(i+1)); System.out.println("Param"+i+" = "+params[i]); } JDBCDemo jd = new JDBCDemo(params,true); jd.show(); } }
gpl-2.0
aosm/gcc_40
libjava/gnu/java/security/action/GetPropertyAction.java
2818
/* GetPropertyAction.java Copyright (C) 2004 Free Software Foundation, Inc. This file is part of GNU Classpath. GNU Classpath is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. GNU Classpath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GNU Classpath; see the file COPYING. If not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ package gnu.java.security.action; import java.security.PrivilegedAction; /** * PrivilegedAction implementation that calls System.getProperty() with * the property name passed to its constructor. * * Example of use: * <code> * GetPropertyAction action = new GetPropertyAction("http.proxyPort"); * String port = AccessController.doPrivileged(action); * </code> */ public class GetPropertyAction implements PrivilegedAction { String name; String value = null; public GetPropertyAction() { } public GetPropertyAction(String propName) { setParameters(propName); } public GetPropertyAction(String propName, String defaultValue) { setParameters(propName, defaultValue); } public Object run() { return System.getProperty(name, value); } public GetPropertyAction setParameters(String propName) { this.name = propName; this.value = null; return this; } public GetPropertyAction setParameters(String propName, String defaultValue) { this.name = propName; this.value = defaultValue; return this; } }
gpl-2.0
qoswork/opennmszh
features/vaadin-node-maps/src/main/java/org/opennms/features/vaadin/nodemaps/internal/gwt/client/ui/controls/search/SearchStateManager.java
20356
package org.opennms.features.vaadin.nodemaps.internal.gwt.client.ui.controls.search; import com.google.gwt.core.client.Scheduler; import com.google.gwt.core.client.Scheduler.ScheduledCommand; import com.google.gwt.dom.client.NativeEvent; import com.google.gwt.event.dom.client.KeyCodes; import com.vaadin.terminal.gwt.client.VConsole; public abstract class SearchStateManager { private SearchState m_state; private ValueItem m_valueItem; private ValueItem m_history; public SearchStateManager(final ValueItem valueItem, final ValueItem history) { m_valueItem = valueItem; m_history = history; final String valueSearchString = m_valueItem.getValue(); final String historySearchString = getHistorySearchString(); if (historySearchString != null) { m_valueItem.setValue(historySearchString); m_state = State.SEARCHING_FINISHED; } else if (valueSearchString != null && !"".equals(valueSearchString)) { m_state = State.SEARCHING_FINISHED; } else { m_state = State.NOT_SEARCHING; } m_state.initialize(this); } SearchState getState() { return m_state; } protected ValueItem getValueItem() { return m_valueItem; } public void updateMatchCount(final int matchCount) { m_state = m_state.updateMatchCount(this, matchCount); } public boolean handleAutocompleteEvent(final NativeEvent event) { final String eventType = event.getType(); final int eventKeyCode = event.getKeyCode(); VConsole.log("handleAutocompleteEvent(" + m_state + "): received " + eventType + " (keyCode = " + eventKeyCode + ")"); if ("keydown".equals(eventType)) { switch (eventKeyCode) { case KeyCodes.KEY_ESCAPE: Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { m_state = m_state.cancelSearching(SearchStateManager.this); } }); break; case KeyCodes.KEY_ENTER: Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { m_state = m_state.currentEntrySelected(SearchStateManager.this); } }); break; } } else if ("click".equals(eventType) || "touchstart".equals(eventType)) { // someone clicked on an entry Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { m_state = m_state.currentEntrySelected(SearchStateManager.this); } }); return true; } else { VConsole.log("handleAutocompleteEvent(" + m_state + "): unhandled event: " + eventType); return true; } return false; } public void handleSearchIconEvent(final NativeEvent event) { final String eventType = event.getType(); VConsole.log("handleSearchIconEvent(" + m_state + "): received " + eventType + " (keyCode = " + event.getKeyCode() + ")"); if ("click".equals(eventType) || "touchstart".equals(eventType)) { Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { m_state = m_state.finishedSearching(SearchStateManager.this); } }); } else { VConsole.log("handleSearchIconEvent(" + m_state + "): unhandled event: " + eventType); } } public void handleInputEvent(final NativeEvent event) { final String eventType = event.getType(); VConsole.log("handleInputEvent(" + m_state + "): received " + eventType + " (keyCode = " + event.getKeyCode() + ")"); if ("keydown".equals(eventType)) { switch (event.getKeyCode()) { case KeyCodes.KEY_ESCAPE: Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { m_state = m_state.cancelSearching(SearchStateManager.this); } }); break; case KeyCodes.KEY_DOWN: Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { m_state = m_state.autocompleteStartNavigation(SearchStateManager.this); } }); break; case KeyCodes.KEY_ENTER: Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { m_state = m_state.finishedSearching(SearchStateManager.this); } }); break; default: Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { final String value = m_valueItem.getValue(); if (value == null || "".equals(value)) { m_state = m_state.cancelSearching(SearchStateManager.this); } else { m_state = m_state.searchInputReceived(SearchStateManager.this); } } }); break; } } else if ("search".equals(eventType)) { final String searchString = m_valueItem.getValue(); if ("".equals(searchString)) { Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { m_state = m_state.cancelSearching(SearchStateManager.this); } }); } } else { VConsole.log("handleInputEvent(" + m_state + "): unhandled event: " + eventType); } } public void reset() { m_state = m_state.cancelSearching(this); } interface SearchState { public abstract SearchState initialize(SearchStateManager manager); public abstract SearchState cancelSearching(SearchStateManager manager); public abstract SearchState finishedSearching(SearchStateManager manager); public abstract SearchState currentEntrySelected(SearchStateManager manager); public abstract SearchState searchInputReceived(SearchStateManager manager); public abstract SearchState autocompleteStartNavigation(SearchStateManager manager); public abstract SearchState updateMatchCount(SearchStateManager manager, int matchCount); } enum State implements SearchState { // Markers are not being filtered, input box is empty, autocomplete is hidden. NOT_SEARCHING { @Override public SearchState initialize(final SearchStateManager manager) { manager.focusInput(); manager.hideAutocomplete(); return this; } @Override public SearchState cancelSearching(final SearchStateManager manager) { // make sure input is focused manager.focusInput(); return this; } @Override public SearchState autocompleteStartNavigation(final SearchStateManager manager) { // if we're not searching, starting navigation won't do // anything because // we don't have a search phrase yet VConsole.log("WARNING: attempting to start autocomplete navigation, but we're not searching!"); return this; } @Override public SearchState searchInputReceived(final SearchStateManager manager) { manager.refresh(); manager.showAutocomplete(); return SEARCHING_AUTOCOMPLETE_VISIBLE; } @Override public SearchState finishedSearching(final SearchStateManager manager) { // if we're not searching, we can't finish :) VConsole.log("WARNING: attempting to finish, but we're not searching!"); return this; } @Override public SearchState currentEntrySelected(final SearchStateManager manager) { // if we're not searching, we can't select an entry VConsole.log("WARNING: attempting to finish, but we're not searching!"); return this; } @Override public SearchState updateMatchCount(final SearchStateManager manager, final int matchCount) { VConsole.log("WARNING: match count updated, but we're not searching!"); return this; } }, // Markers are being filtered, input box has content, autocomplete is visible. SEARCHING_AUTOCOMPLETE_VISIBLE { @Override public SearchState initialize(final SearchStateManager manager) { manager.focusInput(); manager.showAutocomplete(); manager.refresh(); return this; } @Override public SearchState cancelSearching(final SearchStateManager manager) { manager.clearSearchInput(); manager.hideAutocomplete(); manager.updateHistorySearchString(); manager.refresh(); return State.NOT_SEARCHING; } @Override public SearchState autocompleteStartNavigation(final SearchStateManager manager) { // we are already searching with autocomplete visible, but // input came // to the input box, so we return focus to the autocomplete // box manager.focusAutocomplete(); return SEARCHING_AUTOCOMPLETE_ACTIVE; } @Override public SearchState searchInputReceived(final SearchStateManager manager) { // we're still searching, so show/update autocomplete, and // then update markers manager.refresh(); return this; } @Override public SearchState finishedSearching(final SearchStateManager manager) { manager.hideAutocomplete(); manager.updateHistorySearchString(); manager.refresh(); return State.SEARCHING_FINISHED; } @Override public SearchState currentEntrySelected(final SearchStateManager manager) { // the user has clicked an entry manager.hideAutocomplete(); manager.entrySelected(); manager.updateHistorySearchString(); manager.refresh(); return SEARCHING_FINISHED; } @Override public SearchState updateMatchCount(final SearchStateManager manager, final int matchCount) { // if there are no matches, hide the autocomplete if (matchCount == 0) { manager.hideAutocomplete(); return SEARCHING_AUTOCOMPLETE_HIDDEN; } else { return this; } } }, // Markers are being filtered, input box has content, autocomplete is focused and navigable. SEARCHING_AUTOCOMPLETE_ACTIVE { @Override public SearchState initialize(final SearchStateManager manager) { manager.showAutocomplete(); manager.focusAutocomplete(); manager.refresh(); return this; } @Override public SearchState cancelSearching(final SearchStateManager manager) { manager.clearSearchInput(); manager.hideAutocomplete(); manager.updateHistorySearchString(); manager.refresh(); return State.NOT_SEARCHING; } @Override public SearchState finishedSearching(final SearchStateManager manager) { manager.hideAutocomplete(); manager.focusInput(); manager.updateHistorySearchString(); manager.refresh(); return State.SEARCHING_FINISHED; } @Override public SearchState searchInputReceived(final SearchStateManager manager) { // somehow we've got new search input, user has probably typed something in themselves, // flip back to the input-box-has-focus state manager.focusInput(); return SEARCHING_AUTOCOMPLETE_VISIBLE.searchInputReceived(manager); } @Override public SearchState autocompleteStartNavigation(final SearchStateManager manager) { // navigation has already started VConsole.log("WARNING: attempting to start navigation when it has already started"); return this; } @Override public SearchState currentEntrySelected(final SearchStateManager manager) { // the user has clicked an entry or hit enter manager.hideAutocomplete(); manager.entrySelected(); manager.focusInput(); manager.updateHistorySearchString(); manager.refresh(); return SEARCHING_FINISHED; } @Override public SearchState updateMatchCount(final SearchStateManager manager, final int matchCount) { // if there are no matches, hide the autocomplete if (matchCount == 0) { manager.hideAutocomplete(); return SEARCHING_AUTOCOMPLETE_HIDDEN; } else { return this; } } }, // Markers are being filtered, input box has content, autocomplete is not visible. // (this happens when there are 0 matches to the current search) SEARCHING_AUTOCOMPLETE_HIDDEN { @Override public SearchState initialize(final SearchStateManager manager) { manager.focusInput(); manager.hideAutocomplete(); manager.refresh(); return this; } @Override public SearchState cancelSearching(final SearchStateManager manager) { manager.clearSearchInput(); manager.focusInput(); manager.hideAutocomplete(); manager.updateHistorySearchString(); manager.refresh(); return State.NOT_SEARCHING; } @Override public SearchState finishedSearching(final SearchStateManager manager) { manager.hideAutocomplete(); manager.focusInput(); manager.updateHistorySearchString(); manager.refresh(); return State.SEARCHING_FINISHED; } @Override public SearchState currentEntrySelected(final SearchStateManager manager) { VConsole.log("Current entry got selected, but there is no current entry visible!"); return this; } @Override public SearchState searchInputReceived(final SearchStateManager manager) { // refresh, and let the marker update trigger a match count update manager.refresh(); return this; } @Override public SearchState autocompleteStartNavigation(final SearchStateManager manager) { VConsole.log("Autocomplete is already hidden because of a previous match count update, this doesn't make sense!"); return this; } @Override public SearchState updateMatchCount(final SearchStateManager manager, final int matchCount) { // autocomplete is hidden, so if we have matches now, we should re-show it if (matchCount > 0) { manager.showAutocomplete(); return SEARCHING_AUTOCOMPLETE_VISIBLE; } return this; } }, // Markers are being filtered, input box has content, autocomplete is hidden. SEARCHING_FINISHED { @Override public SearchState initialize(final SearchStateManager manager) { manager.focusInput(); manager.hideAutocomplete(); manager.refresh(); return this; } @Override public SearchState cancelSearching(final SearchStateManager manager) { manager.clearSearchInput(); manager.focusInput(); manager.hideAutocomplete(); manager.updateHistorySearchString(); manager.refresh(); return State.NOT_SEARCHING; } @Override public SearchState autocompleteStartNavigation(final SearchStateManager manager) { // we're "finished" searching, but if the user wishes to start navigation again, // they can hit the down-arrow to re-open autocomplete and resume searching manager.showAutocomplete(); manager.focusAutocomplete(); manager.refresh(); return SEARCHING_AUTOCOMPLETE_ACTIVE; } @Override public SearchState searchInputReceived(final SearchStateManager manager) { // user has focused the input box and started typing again manager.refresh(); manager.showAutocomplete(); manager.focusInput(); return SEARCHING_AUTOCOMPLETE_VISIBLE; } @Override public SearchState finishedSearching(final SearchStateManager manager) { // we're already finished searching... finish... again? VConsole.log("WARNING: attempting to finish search, but we're already finished!"); return this; } @Override public SearchState currentEntrySelected(final SearchStateManager manager) { VConsole.log("WARNING: attempting to select an entry, but we're already finished!"); return this; } @Override public SearchState updateMatchCount(final SearchStateManager manager, final int matchCount) { // map count is updated, but search is finished, so autocomplete should stay hidden return this; } }; } private String getHistorySearchString() { final String value = m_history.getValue(); if (value != null && value.startsWith("search/")) { return value.replaceFirst("^search\\/", ""); } else { return null; } } protected void updateHistorySearchString() { final String token = m_history.getValue(); final String value = m_valueItem.getValue(); final String newToken = (value == null || "".equals(value)) ? "" : "search/" + value; if (!newToken.equals(token)) { m_history.setValue(newToken); } } public abstract void refresh(); public abstract void entrySelected(); public abstract void clearSearchInput(); public abstract void focusInput(); public abstract void focusAutocomplete(); public abstract void showAutocomplete(); public abstract void hideAutocomplete(); }
gpl-2.0
md-5/jdk10
src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.nodeinfo/src/org/graalvm/compiler/nodeinfo/StructuralInput.java
3109
/* * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.graalvm.compiler.nodeinfo; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Marker type for describing node inputs in snippets that are not of type {@link InputType#Value}. */ public abstract class StructuralInput { private StructuralInput() { throw new Error("Illegal instance of StructuralInput. This class should be used in snippets only."); } @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @Inherited public @interface MarkerType { InputType value(); } /** * Marker type for {@link InputType#Memory} edges in snippets. */ @MarkerType(InputType.Memory) public abstract static class Memory extends StructuralInput { } /** * Marker type for {@link InputType#Condition} edges in snippets. */ @MarkerType(InputType.Condition) public abstract static class Condition extends StructuralInput { } /** * Marker type for {@link InputType#State} edges in snippets. */ @MarkerType(InputType.State) public abstract static class State extends StructuralInput { } /** * Marker type for {@link InputType#Guard} edges in snippets. */ @MarkerType(InputType.Guard) public abstract static class Guard extends StructuralInput { } /** * Marker type for {@link InputType#Anchor} edges in snippets. */ @MarkerType(InputType.Anchor) public abstract static class Anchor extends StructuralInput { } /** * Marker type for {@link InputType#Association} edges in snippets. */ @MarkerType(InputType.Association) public abstract static class Association extends StructuralInput { } /** * Marker type for {@link InputType#Extension} edges in snippets. */ @MarkerType(InputType.Extension) public abstract static class Extension extends StructuralInput { } }
gpl-2.0
shelan/jdk9-mirror
langtools/src/jdk.compiler/share/classes/com/sun/source/doctree/InlineTagTree.java
1530
/* * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.source.doctree; /** * A tree node used as the base class for the different types of * inline tags. * * @since 1.8 */ @jdk.Exported public interface InlineTagTree extends DocTree { /** * Returns the name of the tag. * @return the name of the tag */ String getTagName(); }
gpl-2.0
tonysparks/seventh
src/seventh/shared/WatchedAsset.java
538
/* * see license.txt */ package seventh.shared; import java.io.IOException; /** * The asset that is being watched * * @author Tony * */ public interface WatchedAsset<T> { /** * Retrieve the Asset * * @return the Asset in question */ public T getAsset(); /** * Release this asset */ public void release(); /** * The asset has changed on the file system * * @throws IOException */ public void onAssetChanged() throws IOException; }
gpl-2.0
tp81/openmicroscopy
components/blitz/src/omero/cmd/graphs/ChownFacadeI.java
5167
/* * Copyright (C) 2014-2015 University of Dundee & Open Microscopy Environment. * All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package omero.cmd.graphs; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import com.google.common.collect.HashMultimap; import com.google.common.collect.SetMultimap; import ome.services.graphs.GraphException; import omero.cmd.Chown; import omero.cmd.ERR; import omero.cmd.Helper; import omero.cmd.IRequest; import omero.cmd.OK; import omero.cmd.Response; import omero.cmd.HandleI.Cancel; /** * Implements an approximation of {@link Chown}'s API using {@link omero.cmd.Chown2}. * @author m.t.b.carroll@dundee.ac.uk * @since 5.1.0 * @deprecated will be removed in OMERO 5.3, so use the * <a href="http://www.openmicroscopy.org/site/support/omero5.1/developers/Server/ObjectGraphs.html">new graphs implementation</a> */ @Deprecated @SuppressWarnings("deprecation") public class ChownFacadeI extends Chown implements IRequest { private final GraphRequestFactory graphRequestFactory; private final SetMultimap<String, Long> targetObjects = HashMultimap.create(); private IRequest chownRequest; /** * Construct a new <q>chown</q> request; called from {@link GraphRequestFactory#getRequest(Class)}. * @param graphRequestFactory a means of instantiating a sub-request for root-anchored subgraphs */ public ChownFacadeI(GraphRequestFactory graphRequestFactory) { this.graphRequestFactory = graphRequestFactory; this.chownRequest = graphRequestFactory.getRequest(Chown2I.class); } @Override public Map<String, String> getCallContext() { return chownRequest.getCallContext(); } /** * Add the given model object to the chown request's target objects. * To be called <em>before</em> {@link #init(Helper)}. * @param type the model object's type * @param id the model object's ID */ public void addToTargets(String type, long id) { targetObjects.put(GraphUtil.getFirstClassName(type), id); } @Override public void init(Helper helper) { /* find class name at start of type string */ if (type.charAt(0) == '/') { type = type.substring(1); } final Chown2I actualChown = (Chown2I) chownRequest; /* set target object and group then review options */ addToTargets(type, id); actualChown.targetObjects = new HashMap<String, List<Long>>(); for (final Map.Entry<String, Collection<Long>> oneClassToTarget : targetObjects.asMap().entrySet()) { actualChown.targetObjects.put(oneClassToTarget.getKey(), new ArrayList<Long>(oneClassToTarget.getValue())); } targetObjects.clear(); actualChown.userId = user; try { GraphUtil.translateOptions(graphRequestFactory, options, actualChown, helper.getEventContext().isCurrentUserAdmin()); } catch (GraphException ge) { final Exception e = new IllegalArgumentException("could not accept request options"); throw helper.cancel(new ERR(), e, "bad-options"); } /* check for root-anchored subgraph */ final int lastSlash = type.lastIndexOf('/'); if (lastSlash > 0) { /* wrap in skip-head request for operating on subgraphs */ final SkipHeadI wrapper = graphRequestFactory.getRequest(SkipHeadI.class); GraphUtil.copyFields(actualChown, wrapper); wrapper.startFrom = Collections.singletonList(type.substring(lastSlash + 1)); wrapper.request = actualChown; chownRequest = wrapper; } /* now the chown request is configured, complete initialization */ chownRequest.init(helper); } @Override public Object step(int step) throws Cancel { return chownRequest.step(step); } @Override public void finish() { chownRequest.finish(); } @Override public void buildResponse(int step, Object object) { chownRequest.buildResponse(step, object); } @Override public Response getResponse() { final Response responseToWrap = chownRequest.getResponse(); if (responseToWrap instanceof ERR) { return responseToWrap; } /* no actual wrapping needed */ return new OK(); } }
gpl-2.0
erpcya/adempierePOS
base/src/org/eevolution/model/X_C_TaxGroup.java
4645
/****************************************************************************** * Product: Adempiere ERP & CRM Smart Business Solution * * Copyright (C) 1999-2007 ComPiere, Inc. All Rights Reserved. * * This program is free software, you can redistribute it and/or modify it * * under the terms version 2 of the GNU General Public License as published * * by the Free Software Foundation. This program is distributed in the hope * * that it will be useful, but WITHOUT ANY WARRANTY, without even the implied * * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * * with this program, if not, write to the Free Software Foundation, Inc., * * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * For the text or an alternative of this public license, you may reach us * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * or via info@compiere.org or http://www.compiere.org/license.html * *****************************************************************************/ /** Generated Model - DO NOT CHANGE */ package org.eevolution.model; import java.sql.ResultSet; import java.util.Properties; import org.compiere.model.*; import org.compiere.util.KeyNamePair; /** Generated Model for C_TaxGroup * @author Adempiere (generated) * @version Release 3.8.0 - $Id$ */ public class X_C_TaxGroup extends PO implements I_C_TaxGroup, I_Persistent { /** * */ private static final long serialVersionUID = 20150101L; /** Standard Constructor */ public X_C_TaxGroup (Properties ctx, int C_TaxGroup_ID, String trxName) { super (ctx, C_TaxGroup_ID, trxName); /** if (C_TaxGroup_ID == 0) { setC_TaxGroup_ID (0); setName (null); setValue (null); } */ } /** Load Constructor */ public X_C_TaxGroup (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } /** AccessLevel * @return 3 - Client - Org */ protected int get_AccessLevel() { return accessLevel.intValue(); } /** Load Meta Data */ protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_C_TaxGroup[") .append(get_ID()).append("]"); return sb.toString(); } /** Set Tax Group. @param C_TaxGroup_ID Tax Group */ public void setC_TaxGroup_ID (int C_TaxGroup_ID) { if (C_TaxGroup_ID < 1) set_ValueNoCheck (COLUMNNAME_C_TaxGroup_ID, null); else set_ValueNoCheck (COLUMNNAME_C_TaxGroup_ID, Integer.valueOf(C_TaxGroup_ID)); } /** Get Tax Group. @return Tax Group */ public int getC_TaxGroup_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_TaxGroup_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Comment/Help. @param Help Comment or Hint */ public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help. @return Comment or Hint */ public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
gpl-2.0
b-cuts/esper
esper/src/main/java/com/espertech/esper/epl/core/eval/EvalInsertWildcardRevision.java
1694
/* * ************************************************************************************* * Copyright (C) 2006-2015 EsperTech, Inc. All rights reserved. * * http://www.espertech.com/esper * * http://www.espertech.com * * ---------------------------------------------------------------------------------- * * The software in this package is published under the terms of the GPL license * * a copy of which has been included with this distribution in the license.txt file. * * ************************************************************************************* */ package com.espertech.esper.epl.core.eval; import com.espertech.esper.client.EventBean; import com.espertech.esper.client.EventType; import com.espertech.esper.epl.core.SelectExprProcessor; import com.espertech.esper.epl.expression.core.ExprEvaluatorContext; import com.espertech.esper.event.vaevent.ValueAddEventProcessor; public class EvalInsertWildcardRevision extends EvalBase implements SelectExprProcessor { private final ValueAddEventProcessor vaeProcessor; public EvalInsertWildcardRevision(SelectExprContext selectExprContext, EventType resultEventType, ValueAddEventProcessor vaeProcessor) { super(selectExprContext, resultEventType); this.vaeProcessor = vaeProcessor; } public EventBean process(EventBean[] eventsPerStream, boolean isNewData, boolean isSynthesize, ExprEvaluatorContext exprEvaluatorContext) { EventBean theEvent = eventsPerStream[0]; return vaeProcessor.getValueAddEventBean(theEvent); } }
gpl-2.0
rfdrake/opennms
opennms-services/src/main/java/org/opennms/netmgt/trapd/Trapd.java
10787
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2006-2012 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * OpenNMS(R) is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <license@opennms.org> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.netmgt.trapd; import java.io.IOException; import java.lang.reflect.UndeclaredThrowableException; import java.net.InetAddress; import java.sql.SQLException; import java.util.List; import java.util.concurrent.ExecutorService; import javax.annotation.Resource; import org.opennms.core.logging.Logging; import org.opennms.core.utils.BeanUtils; import org.opennms.core.utils.InetAddressUtils; import org.opennms.netmgt.daemon.AbstractServiceDaemon; import org.opennms.netmgt.snmp.SnmpUtils; import org.opennms.netmgt.snmp.SnmpV3User; import org.opennms.netmgt.snmp.TrapNotification; import org.opennms.netmgt.snmp.TrapNotificationListener; import org.opennms.netmgt.snmp.TrapProcessor; import org.opennms.netmgt.snmp.TrapProcessorFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.Assert; /** * <p> * The Trapd listens for SNMP traps on the standard port(162). Creates a * SnmpTrapSession and implements the SnmpTrapHandler to get callbacks when * traps are received. * </p> * * <p> * The received traps are converted into XML and sent to eventd. * </p> * * <p> * <strong>Note: </strong>Trapd is a PausableFiber so as to receive control * events. However, a 'pause' on Trapd has no impact on the receiving and * processing of traps. * </p> * * @author <A HREF="mailto:weave@oculan.com">Brian Weaver </A> * @author <A HREF="mailto:sowmya@opennms.org">Sowmya Nataraj </A> * @author <A HREF="mailto:larry@opennms.org">Lawrence Karnowski </A> * @author <A HREF="mailto:mike@opennms.org">Mike Davidson </A> * @author <A HREF="mailto:tarus@opennms.org">Tarus Balog </A> * @author <A HREF="http://www.opennms.org">OpenNMS.org </A> */ public class Trapd extends AbstractServiceDaemon implements TrapProcessorFactory, TrapNotificationListener { private static final Logger LOG = LoggerFactory.getLogger(Trapd.class); private static final String LOG4J_CATEGORY = "trapd"; /** * The last status sent to the service control manager. */ private int m_status = START_PENDING; /** * The thread pool that processes traps */ private ExecutorService m_backlogQ; /** * The queue processing thread */ @Autowired private TrapQueueProcessorFactory m_processorFactory; /** * The class instance used to receive new events from for the system. */ @Autowired private BroadcastEventProcessor m_eventReader; /** * Trapd IP manager. Contains IP address -> node ID mapping. */ @Autowired private TrapdIpMgr m_trapdIpMgr; @Resource(name="snmpTrapAddress") private String m_snmpTrapAddress; @Resource(name="snmpTrapPort") private Integer m_snmpTrapPort; @Resource(name="snmpV3Users") private List<SnmpV3User> m_snmpV3Users; private boolean m_registeredForTraps; /** * <P> * Constructs a new Trapd object that receives and forwards trap messages * via JSDT. The session is initialized with the default client name of <EM> * OpenNMS.trapd</EM>. The trap session is started on the default port, as * defined by the SNMP library. * </P> * * @see org.opennms.protocols.snmp.SnmpTrapSession */ public Trapd() { super(LOG4J_CATEGORY); } /** * <p>createTrapProcessor</p> * * @return a {@link org.opennms.netmgt.snmp.TrapProcessor} object. */ @Override public TrapProcessor createTrapProcessor() { return new EventCreator(m_trapdIpMgr); } /** {@inheritDoc} */ @Override public void trapReceived(TrapNotification trapNotification) { m_backlogQ.submit(m_processorFactory.getInstance(trapNotification)); } /** * <p>onInit</p> */ @Override public synchronized void onInit() { BeanUtils.assertAutowiring(this); Assert.state(m_backlogQ != null, "backlogQ must be set"); try { m_trapdIpMgr.dataSourceSync(); } catch (final SQLException e) { LOG.error("init: Failed to load known IP address list", e); throw new UndeclaredThrowableException(e); } try { InetAddress address = getInetAddress(); LOG.info("Listening on {}:{}", address == null ? "[all interfaces]" : InetAddressUtils.str(address), m_snmpTrapPort); SnmpUtils.registerForTraps(this, this, address, m_snmpTrapPort, m_snmpV3Users); m_registeredForTraps = true; LOG.debug("init: Creating the trap session"); } catch (final IOException e) { if (e instanceof java.net.BindException) { Logging.withPrefix("OpenNMS.Manager", new Runnable() { @Override public void run() { LOG.error("init: Failed to listen on SNMP trap port, perhaps something else is already listening?", e); } }); LOG.error("init: Failed to listen on SNMP trap port, perhaps something else is already listening?", e); } else { LOG.error("init: Failed to initialize SNMP trap socket", e); } throw new UndeclaredThrowableException(e); } try { m_eventReader.open(); } catch (final Throwable e) { LOG.error("init: Failed to open event reader", e); throw new UndeclaredThrowableException(e); } } private InetAddress getInetAddress() { if (m_snmpTrapAddress.equals("*")) { return null; } return InetAddressUtils.addr(m_snmpTrapAddress); } /** * Create the SNMP trap session and create the communication channel * to communicate with eventd. * * @exception java.lang.reflect.UndeclaredThrowableException * if an unexpected database, or IO exception occurs. * @see org.opennms.protocols.snmp.SnmpTrapSession * @see org.opennms.protocols.snmp.SnmpTrapHandler */ @Override public synchronized void onStart() { m_status = STARTING; LOG.debug("start: Initializing the trapd config factory"); m_status = RUNNING; LOG.debug("start: Trapd ready to receive traps"); } /** * Pauses Trapd */ @Override public void onPause() { if (m_status != RUNNING) { return; } m_status = PAUSE_PENDING; LOG.debug("pause: Calling pause on processor"); m_status = PAUSED; LOG.debug("pause: Trapd paused"); } /** * Resumes Trapd */ @Override public void onResume() { if (m_status != PAUSED) { return; } m_status = RESUME_PENDING; LOG.debug("resume: Calling resume on processor"); m_status = RUNNING; LOG.debug("resume: Trapd resumed"); } /** * Stops the currently running service. If the service is not running then * the command is silently discarded. */ @Override public synchronized void onStop() { m_status = STOP_PENDING; // shutdown and wait on the background processing thread to exit. LOG.debug("stop: closing communication paths."); try { if (m_registeredForTraps) { LOG.debug("stop: Closing SNMP trap session."); SnmpUtils.unregisterForTraps(this, getInetAddress(), m_snmpTrapPort); LOG.debug("stop: SNMP trap session closed."); } else { LOG.debug("stop: not attemping to closing SNMP trap session--it was never opened"); } } catch (final IOException e) { LOG.warn("stop: exception occurred closing session", e); } catch (final IllegalStateException e) { LOG.debug("stop: The SNMP session was already closed", e); } LOG.debug("stop: Stopping queue processor."); m_backlogQ.shutdown(); m_eventReader.close(); m_status = STOPPED; LOG.debug("stop: Trapd stopped"); } /** * Returns the current status of the service. * * @return The service's status. */ @Override public synchronized int getStatus() { return m_status; } /** {@inheritDoc} */ @Override public void trapError(final int error, final String msg) { LOG.warn("Error Processing Received Trap: error = {} {}", error, (msg != null ? ", ref = " + msg : "")); } /** * <p>getEventReader</p> * * @return a {@link org.opennms.netmgt.trapd.BroadcastEventProcessor} object. */ public BroadcastEventProcessor getEventReader() { return m_eventReader; } /** * <p>setEventReader</p> * * @param eventReader a {@link org.opennms.netmgt.trapd.BroadcastEventProcessor} object. */ public void setEventReader(BroadcastEventProcessor eventReader) { m_eventReader = eventReader; } /** * <p>getBacklogQ</p> * * @return a {@link java.util.concurrent.ExecutorService} object. */ public ExecutorService getBacklogQ() { return m_backlogQ; } /** * <p>setBacklogQ</p> * * @param backlogQ a {@link java.util.concurrent.ExecutorService} object. */ public void setBacklogQ(ExecutorService backlogQ) { m_backlogQ = backlogQ; } public static String getLoggingCategory() { return LOG4J_CATEGORY; } }
gpl-2.0
hexbinary/landing
src/test/java/org/oscarehr/billing/CA/BC/dao/TeleplanRefusalCodeDaoTest.java
1686
/** * Copyright (c) 2001-2002. Department of Family Medicine, McMaster University. All Rights Reserved. * This software is published under the GPL GNU General Public License. * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * This software was written for the * Department of Family Medicine * McMaster University * Hamilton * Ontario, Canada */ package org.oscarehr.billing.CA.BC.dao; import static org.junit.Assert.assertNotNull; import org.junit.Before; import org.junit.Test; import org.oscarehr.common.dao.DaoTestFixtures; import org.oscarehr.common.dao.utils.SchemaUtils; import org.oscarehr.util.SpringUtils; public class TeleplanRefusalCodeDaoTest extends DaoTestFixtures { public TeleplanRefusalCodeDao dao = SpringUtils.getBean(TeleplanRefusalCodeDao.class); public TeleplanRefusalCodeDaoTest() { } @Before public void before() throws Exception { SchemaUtils.restoreTable("teleplan_refusal_code"); } @Test public void testFindByCode() { assertNotNull(dao.findByCode("CODE")); } }
gpl-2.0
dant3/vlc-android
vlc-android/src/com/android/widget/SlidingTabLayout.java
13435
/* * Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.widget; import android.content.Context; import android.graphics.Color; import android.graphics.Typeface; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.text.TextUtils; import android.util.AttributeSet; import android.util.SparseArray; import android.util.TypedValue; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.HorizontalScrollView; import android.widget.LinearLayout; import android.widget.TextView; import org.videolan.vlc.R; import org.videolan.vlc.util.Util; /** * To be used with ViewPager to provide a tab indicator component which give constant feedback as to * the user's scroll progress. * <p> * To use the component, simply add it to your view hierarchy. Then in your * {@link android.app.Activity} or {@link android.support.v4.app.Fragment} call * {@link #setViewPager(ViewPager)} providing it the ViewPager this layout is being used for. * <p> * The colors can be customized in two ways. The first and simplest is to provide an array of colors * via {@link #setSelectedIndicatorColors(int...)}. The * alternative is via the {@link TabColorizer} interface which provides you complete control over * which color is used for any individual position. * <p> * The views used as tabs can be customized by calling {@link #setCustomTabView(int, int)}, * providing the layout ID of your custom layout. */ public class SlidingTabLayout extends HorizontalScrollView { /** * Allows complete control over the colors drawn in the tab layout. Set with * {@link #setCustomTabColorizer(TabColorizer)}. */ public interface TabColorizer { /** * @return return the color of the indicator used when {@code position} is selected. */ int getIndicatorColor(int position); } public interface OnTabChangedListener { public void tabChanged(int position); } private static final int TITLE_OFFSET_DIPS = 24; private static final int TAB_VIEW_HORIZONTAL_PADDING_DIPS = 5; private static final int TAB_VIEW_VERTICAL_PADDING_DIPS = 10; private static final int TAB_VIEW_TEXT_SIZE_SP = 12; private int mTitleOffset; private int mTabViewLayoutId; private int mTabViewTextViewId; private boolean mDistributeEvenly; private ViewPager mViewPager; private OnTabChangedListener tabChangedListener; private SparseArray<String> mContentDescriptions = new SparseArray<String>(); private final SlidingTabStrip mTabStrip; public SlidingTabLayout(Context context) { this(context, null); } public SlidingTabLayout(Context context, AttributeSet attrs) { this(context, attrs, 0); } public SlidingTabLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); // Disable the Scroll Bar setHorizontalScrollBarEnabled(false); int hpadding = getResources().getDimensionPixelSize(R.dimen.tab_layout_horizontal_padding); setPadding(hpadding, 0, hpadding, 0); setBackgroundColor(getResources().getColor(Util.getResourceFromAttribute(context, org.videolan.vlc.R.attr.background_actionbar))); // Make sure that the Tab Strips fills this View setFillViewport(true); mTitleOffset = (int) (TITLE_OFFSET_DIPS * getResources().getDisplayMetrics().density); mTabStrip = new SlidingTabStrip(context); addView(mTabStrip, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); } /** * Set the custom {@link TabColorizer} to be used. * * If you only require simple custmisation then you can use * {@link #setSelectedIndicatorColors(int...)} to achieve * similar effects. */ public void setCustomTabColorizer(TabColorizer tabColorizer) { mTabStrip.setCustomTabColorizer(tabColorizer); } public void setDistributeEvenly(boolean distributeEvenly) { mDistributeEvenly = distributeEvenly; } /** * Sets the colors to be used for indicating the selected tab. These colors are treated as a * circular array. Providing one color will mean that all tabs are indicated with the same color. */ public void setSelectedIndicatorColors(int... colors) { mTabStrip.setSelectedIndicatorColors(colors); } /** * Set the {@link ViewPager.OnPageChangeListener}. When using {@link SlidingTabLayout} you are * required to set any {@link ViewPager.OnPageChangeListener} through this method. This is so * that the layout can update it's scroll position correctly. * * @see ViewPager#setOnPageChangeListener(ViewPager.OnPageChangeListener) */ public void setOnPageChangeListener(ViewPager.OnPageChangeListener listener) { mViewPagerPageChangeListener = listener; } /** * Set the custom layout to be inflated for the tab views. * * @param layoutResId Layout id to be inflated * @param textViewId id of the {@link TextView} in the inflated view */ public void setCustomTabView(int layoutResId, int textViewId) { mTabViewLayoutId = layoutResId; mTabViewTextViewId = textViewId; } /** * Sets the associated view pager. Note that the assumption here is that the pager content * (number of tabs and tab titles) does not change after this call has been made. */ public void setViewPager(ViewPager viewPager) { mTabStrip.removeAllViews(); mViewPager = viewPager; if (viewPager != null) { viewPager.setOnPageChangeListener(new InternalViewPagerListener()); populateTabStrip(); } } /** * Create a default view to be used for tabs. This is called if a custom tab view is not set via * {@link #setCustomTabView(int, int)}. */ protected TextView createDefaultTabView(Context context) { TextView textView = new TextView(context); textView.setGravity(Gravity.CENTER); textView.setSingleLine(); textView.setEllipsize(TextUtils.TruncateAt.END); textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, TAB_VIEW_TEXT_SIZE_SP); textView.setTypeface(Typeface.DEFAULT_BOLD); textView.setLayoutParams(new LinearLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); textView.setTextColor(Color.WHITE); int hpadding = (int) (TAB_VIEW_HORIZONTAL_PADDING_DIPS * getResources().getDisplayMetrics().density); int vpadding = (int) (TAB_VIEW_VERTICAL_PADDING_DIPS * getResources().getDisplayMetrics().density); textView.setPadding(hpadding, vpadding, hpadding, vpadding); return textView; } private void populateTabStrip() { final PagerAdapter adapter = mViewPager.getAdapter(); final View.OnClickListener tabClickListener = new TabClickListener(); for (int i = 0; i < adapter.getCount(); i++) { View tabView = null; TextView tabTitleView = null; if (mTabViewLayoutId != 0) { // If there is a custom tab view layout id set, try and inflate it tabView = LayoutInflater.from(getContext()).inflate(mTabViewLayoutId, mTabStrip, false); tabTitleView = (TextView) tabView.findViewById(mTabViewTextViewId); } else { tabView = createDefaultTabView(getContext()); tabTitleView = (TextView) tabView; } if (mDistributeEvenly) { LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) tabView.getLayoutParams(); lp.width = 0; lp.weight = 1; } tabTitleView.setText(adapter.getPageTitle(i).toString().toUpperCase()); tabTitleView.setTypeface(Typeface.DEFAULT_BOLD); tabView.setOnClickListener(tabClickListener); String desc = mContentDescriptions.get(i, null); if (desc != null) { tabView.setContentDescription(desc); } mTabStrip.addView(tabView); if (i == mViewPager.getCurrentItem()) { tabView.setSelected(true); tabTitleView.setTextColor(getResources().getColor(Util.getResourceFromAttribute(getContext(), R.attr.font_actionbar_selected))); } } } public void setContentDescription(int i, String desc) { mContentDescriptions.put(i, desc); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); if (mViewPager != null) { scrollToTab(mViewPager.getCurrentItem(), 0); } } private void scrollToTab(int tabIndex, int positionOffset) { final int tabStripChildCount = mTabStrip.getChildCount(); if (tabStripChildCount == 0 || tabIndex < 0 || tabIndex >= tabStripChildCount) { return; } View selectedChild = mTabStrip.getChildAt(tabIndex); if (selectedChild != null) { int targetScrollX = selectedChild.getLeft() + positionOffset; if (tabIndex > 0 || positionOffset > 0) { // If we're not at the first child and are mid-scroll, make sure we obey the offset targetScrollX -= mTitleOffset; } scrollTo(targetScrollX, 0); } } private class InternalViewPagerListener implements ViewPager.OnPageChangeListener { private int mScrollState; @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { int tabStripChildCount = mTabStrip.getChildCount(); if ((tabStripChildCount == 0) || (position < 0) || (position >= tabStripChildCount)) { return; } mTabStrip.onViewPagerPageChanged(position, positionOffset); View selectedTitle = mTabStrip.getChildAt(position); int extraOffset = (selectedTitle != null) ? (int) (positionOffset * selectedTitle.getWidth()) : 0; scrollToTab(position, extraOffset); if (mViewPagerPageChangeListener != null) { mViewPagerPageChangeListener.onPageScrolled(position, positionOffset, positionOffsetPixels); } } @Override public void onPageScrollStateChanged(int state) { mScrollState = state; if (mViewPagerPageChangeListener != null) { mViewPagerPageChangeListener.onPageScrollStateChanged(state); } } @Override public void onPageSelected(int position) { if (mScrollState == ViewPager.SCROLL_STATE_IDLE) { mTabStrip.onViewPagerPageChanged(position, 0f); scrollToTab(position, 0); } for (int i = 0; i < mTabStrip.getChildCount(); i++) { mTabStrip.getChildAt(i).setSelected(position == i); } if (mViewPagerPageChangeListener != null) { mViewPagerPageChangeListener.onPageSelected(position); } } } private class TabClickListener implements View.OnClickListener { @Override public void onClick(View v) { for (int i = 0; i < mTabStrip.getChildCount(); i++) { if (v == mTabStrip.getChildAt(i)) { mViewPager.setCurrentItem(i); return; } } } } public void setOnTabChangedListener(OnTabChangedListener listener) { tabChangedListener = listener; } private ViewPager.OnPageChangeListener mViewPagerPageChangeListener = new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { if (tabChangedListener != null) tabChangedListener.tabChanged(position); for (int i = 0; i < mTabStrip.getChildCount(); i++) { if (mTabStrip.getChildAt(i) instanceof TextView) { int color = (i == position) ? getResources().getColor(Util.getResourceFromAttribute(getContext(), R.attr.font_actionbar_selected)) : getResources().getColor(Util.getResourceFromAttribute(getContext(), R.attr.font_actionbar)); ((TextView) mTabStrip.getChildAt(i)).setTextColor(color); } } } @Override public void onPageScrollStateChanged(int state) { } }; }
gpl-2.0
Rocky-Hu/jecstore
web-main/web-admin/src/main/java/net/oxmall/admin/module/system/controller/PermissionController.java
3886
package net.oxmall.admin.module.system.controller; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.oxmall.admin.module.base.annotation.EntityClass; import net.oxmall.admin.module.base.annotation.DataFormClass; import net.oxmall.admin.module.system.bean.form.PermissionDataForm; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import net.oxmall.admin.module.base.controller.AdviceController; import net.oxmall.admin.module.system.bean.condition.PermissionFilterCondition; import net.oxmall.base.common.model.tree.TreeNode; import net.oxmall.base.entities.Module; import net.oxmall.base.entities.Permission; import net.oxmall.module.system.security.shiro.annotation.SecurityModule; import net.oxmall.module.system.service.ModuleService; import net.oxmall.module.system.service.PermissionService; /** * @author rocky.hu * @date Feb 15, 2017 9:15:36 PM */ @Controller @RequestMapping("/admin/permission") @SecurityModule(value = "permission") @EntityClass(Permission.class) @DataFormClass(PermissionDataForm.class) public class PermissionController extends AdviceController<Permission, Integer, PermissionDataForm, PermissionFilterCondition> { @Autowired private PermissionService permissionService; @Autowired private ModuleService moduleService; @Autowired public PermissionController(PermissionService entityService) { super(entityService); } @RequestMapping(value = "/checkCode", method = RequestMethod.GET) @ResponseBody public boolean checkCode(@RequestParam("code") String code, @RequestParam(value = "id", required = false) Integer id) { if (id != null && id != 0) { Permission permission = permissionService.get(id); if (permission.getCode().equals(code)) { return true; } } if (permissionService.isExistCode(code)) { return false; } else { return true; } } @RequestMapping(value = "tree") @ResponseBody public List<TreeNode<Module>> getPermissionTree(@RequestParam(value = "roleId", required = false) Integer roleId) { return permissionService.getPermissionTree(roleId); } @Override public void doBeforeAdd(PermissionDataForm dataForm, HttpServletRequest request) { Integer moduleId = Integer.parseInt(request.getParameter("moduleId")); Module module = moduleService.get(moduleId); dataForm.setModule(module); this.setAddView("pages.permission.add.data"); } @Override protected void doBeforeSave(PermissionDataForm dataForm, Permission entity, HttpServletRequest request) { } @Override public void doBeforeEdit(PermissionDataForm dataForm, Permission permission, ModelMap model, HttpServletRequest request) { this.setEditView("pages.permission.edit.data"); } @Override public void doAfterEdit(PermissionDataForm datForm, Permission entity, ModelMap model, HttpServletRequest request, HttpServletResponse response) { datForm.setModule(entity.getModule()); } @ModelAttribute("moduleTreeList") public List<Module> getModuleTreeList() { return moduleService.getModuleTreeList(); } }
gpl-2.0
marcoserafini/h-store
src/frontend/org/voltdb/compiler/projectfile/ExportsType.java
14456
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2012.07.11 at 03:04:20 PM EDT // package org.voltdb.compiler.projectfile; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for exportsType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="exportsType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="connector" minOccurs="0"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;all> * &lt;element name="tables" minOccurs="0"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="table" maxOccurs="unbounded" minOccurs="0"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;attribute name="name" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="exportonly" type="{http://www.w3.org/2001/XMLSchema}boolean" default="false" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/all> * &lt;attribute name="class" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="enabled" type="{http://www.w3.org/2001/XMLSchema}boolean" default="false" /> * &lt;attribute name="users" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="groups" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "exportsType", propOrder = { "connector" }) public class ExportsType { protected ExportsType.Connector connector; /** * Gets the value of the connector property. * * @return * possible object is * {@link ExportsType.Connector } * */ public ExportsType.Connector getConnector() { return connector; } /** * Sets the value of the connector property. * * @param value * allowed object is * {@link ExportsType.Connector } * */ public void setConnector(ExportsType.Connector value) { this.connector = value; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;all> * &lt;element name="tables" minOccurs="0"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="table" maxOccurs="unbounded" minOccurs="0"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;attribute name="name" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="exportonly" type="{http://www.w3.org/2001/XMLSchema}boolean" default="false" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/all> * &lt;attribute name="class" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="enabled" type="{http://www.w3.org/2001/XMLSchema}boolean" default="false" /> * &lt;attribute name="users" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="groups" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { }) public static class Connector { protected ExportsType.Connector.Tables tables; @XmlAttribute(name = "class", required = true) protected String clazz; @XmlAttribute protected Boolean enabled; @XmlAttribute protected String users; @XmlAttribute protected String groups; /** * Gets the value of the tables property. * * @return * possible object is * {@link ExportsType.Connector.Tables } * */ public ExportsType.Connector.Tables getTables() { return tables; } /** * Sets the value of the tables property. * * @param value * allowed object is * {@link ExportsType.Connector.Tables } * */ public void setTables(ExportsType.Connector.Tables value) { this.tables = value; } /** * Gets the value of the clazz property. * * @return * possible object is * {@link String } * */ public String getClazz() { return clazz; } /** * Sets the value of the clazz property. * * @param value * allowed object is * {@link String } * */ public void setClazz(String value) { this.clazz = value; } /** * Gets the value of the enabled property. * * @return * possible object is * {@link Boolean } * */ public boolean isEnabled() { if (enabled == null) { return false; } else { return enabled; } } /** * Sets the value of the enabled property. * * @param value * allowed object is * {@link Boolean } * */ public void setEnabled(Boolean value) { this.enabled = value; } /** * Gets the value of the users property. * * @return * possible object is * {@link String } * */ public String getUsers() { return users; } /** * Sets the value of the users property. * * @param value * allowed object is * {@link String } * */ public void setUsers(String value) { this.users = value; } /** * Gets the value of the groups property. * * @return * possible object is * {@link String } * */ public String getGroups() { return groups; } /** * Sets the value of the groups property. * * @param value * allowed object is * {@link String } * */ public void setGroups(String value) { this.groups = value; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="table" maxOccurs="unbounded" minOccurs="0"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;attribute name="name" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="exportonly" type="{http://www.w3.org/2001/XMLSchema}boolean" default="false" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "table" }) public static class Tables { protected List<ExportsType.Connector.Tables.Table> table; /** * Gets the value of the table property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the table property. * * <p> * For example, to add a new item, do as follows: * <pre> * getTable().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ExportsType.Connector.Tables.Table } * * */ public List<ExportsType.Connector.Tables.Table> getTable() { if (table == null) { table = new ArrayList<ExportsType.Connector.Tables.Table>(); } return this.table; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;attribute name="name" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="exportonly" type="{http://www.w3.org/2001/XMLSchema}boolean" default="false" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") public static class Table { @XmlAttribute(required = true) protected String name; @XmlAttribute protected Boolean exportonly; /** * Gets the value of the name property. * * @return * possible object is * {@link String } * */ public String getName() { return name; } /** * Sets the value of the name property. * * @param value * allowed object is * {@link String } * */ public void setName(String value) { this.name = value; } /** * Gets the value of the exportonly property. * * @return * possible object is * {@link Boolean } * */ public boolean isExportonly() { if (exportonly == null) { return false; } else { return exportonly; } } /** * Sets the value of the exportonly property. * * @param value * allowed object is * {@link Boolean } * */ public void setExportonly(Boolean value) { this.exportonly = value; } } } } }
gpl-3.0
KillerDesigner/lavagna
src/main/java/io/lavagna/web/api/SearchController.java
7095
/** * This file is part of lavagna. * * lavagna is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * lavagna is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with lavagna. If not, see <http://www.gnu.org/licenses/>. */ package io.lavagna.web.api; import io.lavagna.common.Json; import io.lavagna.model.CardFull; import io.lavagna.model.CardLabel.LabelDomain; import io.lavagna.model.Permission; import io.lavagna.model.SearchResults; import io.lavagna.model.User; import io.lavagna.model.UserWithPermission; import io.lavagna.service.CardLabelRepository; import io.lavagna.service.CardRepository; import io.lavagna.service.ProjectService; import io.lavagna.service.SearchFilter; import io.lavagna.service.SearchService; import io.lavagna.service.UserRepository; import io.lavagna.web.helper.ExpectPermission; import java.lang.reflect.Type; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Validate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.google.gson.reflect.TypeToken; @ExpectPermission(Permission.SEARCH) @RestController public class SearchController { private final UserRepository userRepository; private final CardRepository cardRepository; private final SearchService searchService; private final CardLabelRepository cardLabelRepository; private final ProjectService projectService; private static final Type LIST_OF_SEARCH_FILTERS = new TypeToken<List<SearchFilter>>() { }.getType(); @Autowired public SearchController(UserRepository userRepository, CardRepository cardRepository, CardLabelRepository cardLabelRepository, SearchService searchService, ProjectService projectService) { this.userRepository = userRepository; this.cardRepository = cardRepository; this.cardLabelRepository = cardLabelRepository; this.searchService = searchService; this.projectService = projectService; } /** * Given a list of user identifier "provider:username" it return a map name -> id. * * @return */ @RequestMapping(value = "/api/search/user-mapping", method = RequestMethod.GET) public Map<String, Integer> findUsersId(@RequestParam("from") List<String> users) { return userRepository.findUsersId(users); } /** * Given a list of card identifier "PROJECT-CARD_SEQUENCE" it return a map card identifier -> id Used by search.js * * @return */ @RequestMapping(value = "/api/search/card-mapping", method = RequestMethod.GET) public Map<String, Integer> findCardsIds(@RequestParam("from") List<String> cards) { return cardRepository.findCardsIds(cards); } /** * Given a list of label list value, return a map value -> card label id -> card label list value id * * @param labelValues * @return */ @RequestMapping(value = "/api/search/label-list-value-mapping", method = RequestMethod.GET) public Map<String, Map<Integer, Integer>> findLabelListValueMapping(@RequestParam("from") List<String> labelValues) { return cardLabelRepository.findLabelListValueMapping(labelValues); } @RequestMapping(value = "/api/search/card", method = RequestMethod.GET) public SearchResults search(@RequestParam("q") String queryAsJson, @RequestParam(value = "projectName", required = false) String projectName, @RequestParam(value = "page", required = false, defaultValue = "0") int page, UserWithPermission userWithPermission) { List<SearchFilter> searchFilters = Json.GSON.fromJson(queryAsJson, LIST_OF_SEARCH_FILTERS); Integer projectId = toProjectId(projectName); return searchService.find(searchFilters, projectId, null, userWithPermission, page); } @RequestMapping(value = "/api/search/user", method = RequestMethod.GET) public List<User> findUsers(@RequestParam("term") String term, @RequestParam(value = "projectName", required = false) String projectName, UserWithPermission userWithPermission) { // TODO: ugly code boolean useProjectSearch = StringUtils.isNotBlank(projectName); if (useProjectSearch && !hasReadAccessToProject(userWithPermission, projectName)) { return Collections.emptyList(); } String[] splitted = StringUtils.split(term, ':'); if (term != null && splitted.length > 0) { String value = splitted.length == 1 ? splitted[0] : splitted[1]; return useProjectSearch ? userRepository.findUsers(value, projectService.findByShortName(projectName).getId(), Permission.READ) : userRepository.findUsers(value); } else { return Collections.emptyList(); } } private static boolean hasReadAccessToProject(UserWithPermission userWithPermission, String projectName) { return (userWithPermission.getBasePermissions().containsKey(Permission.READ) || userWithPermission .projectsWithPermission(Permission.READ).contains(projectName)); } @RequestMapping(value = "/api/search/autocomplete-card", method = RequestMethod.GET) public List<CardFull> searchCardForAutocomplete(@RequestParam("term") String term, UserWithPermission userWithPermission) { boolean hasGlobalAccess = userWithPermission.getBasePermissions().containsKey(Permission.READ); Set<Integer> projectReadAccess = userWithPermission.projectsIdWithPermission(Permission.READ); Validate.isTrue(hasGlobalAccess || !projectReadAccess.isEmpty()); return cardRepository.findCardBy(term, hasGlobalAccess ? null : projectReadAccess); } @RequestMapping(value = "/api/search/milestone", method = RequestMethod.GET) public List<String> findMilestones(@RequestParam("term") String term, @RequestParam(value = "projectName", required = false) String projectName, UserWithPermission userWithPermission) { Integer projectId = toProjectId(projectName); return cardLabelRepository.findListValuesBy(LabelDomain.SYSTEM, "MILESTONE", term, projectId, userWithPermission); } @RequestMapping(value = "/api/search/label-name", method = RequestMethod.GET) public List<String> findLabelNames(@RequestParam("term") String term, @RequestParam(value = "projectName", required = false) String projectName, UserWithPermission userWithPermission) { Integer projectId = toProjectId(projectName); return cardLabelRepository.findUserLabelNameBy(term, projectId, userWithPermission); } private Integer toProjectId(String projectName) { return projectName == null ? null : projectService.findByShortName(projectName).getId(); } }
gpl-3.0
kidaa/RealmSpeak
magic_realm/utility/components/source/com/robin/magic_realm/components/utility/RealmDirectInfoHolder.java
5896
/* * RealmSpeak is the Java application for playing the board game Magic Realm. * Copyright (c) 2005-2015 Robin Warren * E-mail: robin@dewkid.com * * This program is free software: you can redistribute it and/or modify it under the terms of the * GNU General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * * http://www.gnu.org/licenses/ */ package com.robin.magic_realm.components.utility; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import com.robin.game.objects.GameData; import com.robin.game.objects.GameObject; import com.robin.magic_realm.components.wrapper.CharacterWrapper; public class RealmDirectInfoHolder { // Direct Info Commands for TRADE interface public static final String TRADE_INIT = "trInit"; public static final String TRADE_BUSY = "trBusy"; public static final String TRADE_ADD_OBJECTS = "trAdd"; public static final String TRADE_REMOVE_OBJECTS = "trRem"; public static final String TRADE_ADD_DISC = "trAddD"; public static final String TRADE_REMOVE_DISC = "trRemD"; public static final String TRADE_ACCEPT = "trAccept"; public static final String TRADE_UNACCEPT = "trUnAcc"; public static final String TRADE_CANCEL = "trCanc"; public static final String TRADE_GOLD = "trGold"; public static final String TRADE_DONE = "trDone"; // Direct Info Commands for showing popup messages public static final String POPUP_MESSAGE = "puMessage"; // Direct Info Commands for querying players public static final String QUERY_YN = "quYesNo"; public static final String QUERY_YN_NUM = "quYesNoNum"; // Placeholder for when I implement "Ask Demon" public static final String QUERY_RESPONSE = "quResponse"; public static final String QUERY_CANCEL = "quCancel"; // Static responses to query public static final String QUERY_RESPONSE_YES = "qurYES"; public static final String QUERY_RESPONSE_NO = "qurNO"; // Direct Info Commands for energizing spells public static final String SPELL_AFFECT_TARGETS = "spAffTarg"; public static final String SPELL_AFFECT_TARGETS_EXPIRE_IMMEDIATE = "spAffTargEi"; public static final String SPELL_WISH_FORCE_TRANSPORT = "spForTrans"; // Direct Info Command for passing detail log to clients public static final String HOST_DETAIL_LOG = "hsDetailLog"; public static final String HOST_NEED_EMAIL = "hsNeedEmail"; public static final String CLIENT_RESPOND_EMAIL = "clRespEmail"; public static final String RANDOM_NUMBER_GENERATOR = "hsRndNumGen"; private static final int CHAR_ACTIVE = 0; private static final int CHAR_INCLUDE = 1; private static final int COMMAND = 2; private static final int GAME_OBJECT_ID_LIST_START = 3; private GameData data; private ArrayList list; public RealmDirectInfoHolder(GameData data) { this.data = data; list = new ArrayList(); // Three required placeholders list.add(""); list.add(""); list.add(""); } public String toString() { return "RealmDirectInfoHolder: "+list.toString(); } public RealmDirectInfoHolder(GameData data,ArrayList in) { this(data); if (in.size()<GAME_OBJECT_ID_LIST_START) { throw new IllegalArgumentException("Invalid list"); } list = new ArrayList(in); } public RealmDirectInfoHolder(GameData data,String playerName) { this(data); list.set(CHAR_ACTIVE,playerName); } public RealmDirectInfoHolder(GameData data,CharacterWrapper active,CharacterWrapper include) { this(data); list.set(CHAR_ACTIVE,active.getGameObject().getStringId()); list.set(CHAR_INCLUDE,include.getGameObject().getStringId()); } public String getPlayerName() { return (String)list.get(CHAR_ACTIVE); } public void setCommand(String in) { list.set(COMMAND,in); } public void setGold(int in) { clearGameObjectList(); list.add(String.valueOf(in)); } public int getGold() { String val = (String)list.get(GAME_OBJECT_ID_LIST_START); return Integer.valueOf(val).intValue(); } public void setString(String in) { clearGameObjectList(); list.add(in); } public String getString() { return (String)list.get(GAME_OBJECT_ID_LIST_START); } public void setGameObjects(Collection in) { clearGameObjectList(); for (Iterator i=in.iterator();i.hasNext();) { addGameObject((GameObject)i.next()); } } public void setStrings(Collection in) { clearGameObjectList(); list.addAll(in); } public void clearGameObjectList() { list = new ArrayList(list.subList(0,3)); } public void addGameObject(GameObject go) { list.add(go.getStringId()); } public String getCommand() { return (String)list.get(COMMAND); } public CharacterWrapper getActiveCharacter() { String id = (String)list.get(CHAR_ACTIVE); GameObject go = data.getGameObject(Long.valueOf(id)); return new CharacterWrapper(go); } public CharacterWrapper getIncludeCharacter() { String id = (String)list.get(CHAR_INCLUDE); GameObject go = data.getGameObject(Long.valueOf(id)); return new CharacterWrapper(go); } public ArrayList getGameObjects() { ArrayList ret = new ArrayList(); for (int i=GAME_OBJECT_ID_LIST_START;i<list.size();i++) { String id = (String)list.get(i); ret.add(data.getGameObject(Long.valueOf(id))); } return ret; } public ArrayList<String> getStrings() { ArrayList<String> ret = new ArrayList<String>(); for (int i=GAME_OBJECT_ID_LIST_START;i<list.size();i++) { String string = (String)list.get(i); ret.add(string); } return ret; } public ArrayList getInfo() { return list; } }
gpl-3.0
cywong0827/test
src/com/watabou/pixeldungeon/effects/particles/WindParticle.java
2837
/* * Pixel Dungeon * Copyright (C) 2012-2014 Oleg Dolya * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.pixeldungeon.effects.particles; import com.watabou.noosa.Game; import com.watabou.noosa.Group; import com.watabou.noosa.particles.Emitter; import com.watabou.noosa.particles.PixelParticle; import com.watabou.noosa.particles.Emitter.Factory; import com.watabou.pixeldungeon.Dungeon; import com.watabou.pixeldungeon.DungeonTilemap; import com.watabou.utils.PointF; import com.watabou.utils.Random; public class WindParticle extends PixelParticle { public static final Emitter.Factory FACTORY = new Factory() { @Override public void emit( Emitter emitter, int index, float x, float y ) { ((WindParticle)emitter.recycle( WindParticle.class )).reset( x, y ); } }; private static float angle = Random.Float( PointF.PI * 2 ); private static PointF speed = new PointF().polar( angle, 5 ); private float size; public WindParticle() { super(); lifespan = Random.Float( 1, 2 ); scale.set( size = Random.Float( 3 ) ); } public void reset( float x, float y ) { revive(); left = lifespan; super.speed.set( WindParticle.speed ); super.speed.scale( size ); this.x = x - super.speed.x * lifespan / 2; this.y = y - super.speed.y * lifespan / 2; angle += Random.Float( -0.1f, +0.1f ); speed = new PointF().polar( angle, 5 ); am = 0; } @Override public void update() { super.update(); float p = left / lifespan; am = (p < 0.5f ? p : 1 - p) * size * 0.2f; } public static class Wind extends Group { private int pos; private float x; private float y; private float delay; public Wind( int pos ) { super(); this.pos = pos; PointF p = DungeonTilemap.tileToWorld( pos ); x = p.x; y = p.y; delay = Random.Float( 5 ); } @Override public void update() { if (visible = Dungeon.visible[pos]) { super.update(); if ((delay -= Game.elapsed) <= 0) { delay = Random.Float( 5 ); ((WindParticle)recycle( WindParticle.class )).reset( x + Random.Float( DungeonTilemap.SIZE ), y + Random.Float( DungeonTilemap.SIZE ) ); } } } } }
gpl-3.0
agilee/Deskera-Project-Management
src/java/com/krawler/esp/fileparser/mpp/projectTask.java
5411
/* * Copyright (C) 2012 Krawler Information Systems Pvt Ltd * All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package com.krawler.esp.fileparser.mpp; import java.text.SimpleDateFormat; import java.util.Date; public class projectTask { private int taskid; private String taskname; private String duration; private Date startdate; private Date enddate; private String resourcename; private String predecessor; private Number percentcomplete; private String notes; private Date actstartdate; private Date actenddate; private boolean ismilestone; private int parent; private int level; private int flag; private int priority; private boolean isparent; /** * Creates a new instance of projectTask */ public projectTask(int tkid, String tknm, String durn, Date stdate, Date eddate, String resnm, String pred, Number percom, int nor, String Notes, Date acsdt, Date acedt, boolean milstone, int flg, int priority, boolean isparent) { /* * this.TaskId=tkid; this.TaskName=tknm; this.Durn=durn; * this.StDate=stdate; this.EndDate=eddate; this.ResourceName=resnm; * this.Predecessor=pred; this.PerCom=percom; this.NoOfRes=nor; * this.Notes=Notes; this.AcStDate=acsdt; this.ActEdDate=acedt; * this.IsMilestone=milstone; this.flag=flg; */ this.taskid = tkid; this.taskname = tknm; this.duration = durn; this.startdate = stdate; this.enddate = eddate; this.resourcename = resnm; this.predecessor = pred; this.percentcomplete = percom; this.notes = Notes; this.actstartdate = acsdt; this.actenddate = acedt; this.ismilestone = milstone; this.flag = flg; this.priority = priority; this.isparent = isparent; } public boolean getisparent(){ return this.isparent; } public void setisparent(boolean value){ this.isparent = value; } public int gettaskid() { return taskid; } public void settaskid(int TaskId) { this.taskid = TaskId; } public String gettaskname() { return taskname; } public void settaskname(String TaskName) { this.taskname = TaskName; } public String getduration() { return duration; } public void setduration(String Durn) { this.duration = Durn; } public int getflag() { return this.flag; } public String getstartdate() { // return StDate.toString(); if(startdate != null){ SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); return df.format(startdate).toString(); } else return null; } public void setstartdate(Date StDate) { this.startdate = StDate; } public String getenddate() { if(enddate != null){ SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); return df.format(enddate).toString(); } else return null; // return EndDate.toString(); } public void setenddate(Date EndDate) { this.enddate = EndDate; } public String getresourcename() { return resourcename; } public void setresourcename(String ResourceName) { this.resourcename = ResourceName; } public String getpredecessor() { return predecessor; } public void setpredecessor(String Predecessor) { this.predecessor = Predecessor; } public Number getpercentcomplete() { return percentcomplete; } public void setpercentcomplete(Number PerCom) { this.percentcomplete = PerCom; } public String getnotes() { return notes; } public void setnotes(String Notes) { this.notes = Notes; } public String getactstartdate() { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); String abc = null; if (actstartdate != null) { abc = df.format(actstartdate).toString(); } return abc; } public void setactstartdate(Date AcStDate) { this.actstartdate = AcStDate; } public String getactenddate() { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); String abc = null; if (actenddate != null) { abc = df.format(actenddate).toString(); } return abc; // return actenddate; } public void setactenddate(Date ActEdDate) { this.actenddate = ActEdDate; } public boolean getismilestone() { return ismilestone; } public void setismilestone(boolean IsMilestone) { this.ismilestone = IsMilestone; } public int getparent() { return parent; } public void setparent(int Parent) { this.parent = Parent; } public int getlevel() { return level; } public void setlevel(int Level) { this.level = Level; } public void setPriority(int priority){ this.priority = priority; } public int getPriority(){ return this.priority; } }
gpl-3.0
Interlearning/cardeal
imindsgf/src/br/com/cardeal/model/IndexByProductToArqExp.java
963
package br.com.cardeal.model; public class IndexByProductToArqExp { private int index; private Product product; public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } public Product getProduct() { return product; } public void setProduct(Product product) { this.product = product; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((product == null) ? 0 : product.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; IndexByProductToArqExp other = (IndexByProductToArqExp) obj; if (product == null) { if (other.product != null) return false; } else if (!product.equals(other.product)) return false; return true; } }
gpl-3.0
MartyParty21/AwakenDreamsClient
mcp/temp/src/minecraft/net/minecraft/inventory/ContainerDispenser.java
2036
package net.minecraft.inventory; import javax.annotation.Nullable; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Container; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; public class ContainerDispenser extends Container { private final IInventory field_178146_a; public ContainerDispenser(IInventory p_i45799_1_, IInventory p_i45799_2_) { this.field_178146_a = p_i45799_2_; for(int i = 0; i < 3; ++i) { for(int j = 0; j < 3; ++j) { this.func_75146_a(new Slot(p_i45799_2_, j + i * 3, 62 + j * 18, 17 + i * 18)); } } for(int k = 0; k < 3; ++k) { for(int i1 = 0; i1 < 9; ++i1) { this.func_75146_a(new Slot(p_i45799_1_, i1 + k * 9 + 9, 8 + i1 * 18, 84 + k * 18)); } } for(int l = 0; l < 9; ++l) { this.func_75146_a(new Slot(p_i45799_1_, l, 8 + l * 18, 142)); } } public boolean func_75145_c(EntityPlayer p_75145_1_) { return this.field_178146_a.func_70300_a(p_75145_1_); } @Nullable public ItemStack func_82846_b(EntityPlayer p_82846_1_, int p_82846_2_) { ItemStack itemstack = null; Slot slot = (Slot)this.field_75151_b.get(p_82846_2_); if(slot != null && slot.func_75216_d()) { ItemStack itemstack1 = slot.func_75211_c(); itemstack = itemstack1.func_77946_l(); if(p_82846_2_ < 9) { if(!this.func_75135_a(itemstack1, 9, 45, true)) { return null; } } else if(!this.func_75135_a(itemstack1, 0, 9, false)) { return null; } if(itemstack1.field_77994_a == 0) { slot.func_75215_d((ItemStack)null); } else { slot.func_75218_e(); } if(itemstack1.field_77994_a == itemstack.field_77994_a) { return null; } slot.func_82870_a(p_82846_1_, itemstack1); } return itemstack; } }
gpl-3.0
MartyParty21/AwakenDreamsClient
mcp/temp/src/minecraft/net/minecraft/world/chunk/storage/AnvilChunkLoader.java
19389
package net.minecraft.world.chunk.storage; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import javax.annotation.Nullable; import net.minecraft.block.Block; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityList; import net.minecraft.nbt.CompressedStreamTools; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.ResourceLocation; import net.minecraft.util.datafix.DataFixer; import net.minecraft.util.datafix.FixTypes; import net.minecraft.util.datafix.IDataFixer; import net.minecraft.util.datafix.IDataWalker; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.ChunkPos; import net.minecraft.world.MinecraftException; import net.minecraft.world.NextTickListEntry; import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.NibbleArray; import net.minecraft.world.chunk.storage.ExtendedBlockStorage; import net.minecraft.world.chunk.storage.IChunkLoader; import net.minecraft.world.chunk.storage.RegionFileCache; import net.minecraft.world.storage.IThreadedFileIO; import net.minecraft.world.storage.ThreadedFileIOBase; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class AnvilChunkLoader implements IChunkLoader, IThreadedFileIO { private static final Logger field_151505_a = LogManager.getLogger(); private final Map<ChunkPos, NBTTagCompound> field_75828_a = new ConcurrentHashMap(); private final Set<ChunkPos> field_75826_b = Collections.<ChunkPos>newSetFromMap(new ConcurrentHashMap()); private final File field_75825_d; private final DataFixer field_186055_e; private boolean field_183014_e; public AnvilChunkLoader(File p_i46673_1_, DataFixer p_i46673_2_) { this.field_75825_d = p_i46673_1_; this.field_186055_e = p_i46673_2_; } @Nullable public Chunk func_75815_a(World p_75815_1_, int p_75815_2_, int p_75815_3_) throws IOException { ChunkPos chunkpos = new ChunkPos(p_75815_2_, p_75815_3_); NBTTagCompound nbttagcompound = (NBTTagCompound)this.field_75828_a.get(chunkpos); if(nbttagcompound == null) { DataInputStream datainputstream = RegionFileCache.func_76549_c(this.field_75825_d, p_75815_2_, p_75815_3_); if(datainputstream == null) { return null; } nbttagcompound = this.field_186055_e.func_188257_a(FixTypes.CHUNK, CompressedStreamTools.func_74794_a(datainputstream)); } return this.func_75822_a(p_75815_1_, p_75815_2_, p_75815_3_, nbttagcompound); } protected Chunk func_75822_a(World p_75822_1_, int p_75822_2_, int p_75822_3_, NBTTagCompound p_75822_4_) { if(!p_75822_4_.func_150297_b("Level", 10)) { field_151505_a.error("Chunk file at {},{} is missing level data, skipping", new Object[]{Integer.valueOf(p_75822_2_), Integer.valueOf(p_75822_3_)}); return null; } else { NBTTagCompound nbttagcompound = p_75822_4_.func_74775_l("Level"); if(!nbttagcompound.func_150297_b("Sections", 9)) { field_151505_a.error("Chunk file at {},{} is missing block data, skipping", new Object[]{Integer.valueOf(p_75822_2_), Integer.valueOf(p_75822_3_)}); return null; } else { Chunk chunk = this.func_75823_a(p_75822_1_, nbttagcompound); if(!chunk.func_76600_a(p_75822_2_, p_75822_3_)) { field_151505_a.error("Chunk file at {},{} is in the wrong location; relocating. (Expected {}, {}, got {}, {})", new Object[]{Integer.valueOf(p_75822_2_), Integer.valueOf(p_75822_3_), Integer.valueOf(p_75822_2_), Integer.valueOf(p_75822_3_), Integer.valueOf(chunk.field_76635_g), Integer.valueOf(chunk.field_76647_h)}); nbttagcompound.func_74768_a("xPos", p_75822_2_); nbttagcompound.func_74768_a("zPos", p_75822_3_); chunk = this.func_75823_a(p_75822_1_, nbttagcompound); } return chunk; } } } public void func_75816_a(World p_75816_1_, Chunk p_75816_2_) throws MinecraftException, IOException { p_75816_1_.func_72906_B(); try { NBTTagCompound nbttagcompound = new NBTTagCompound(); NBTTagCompound nbttagcompound1 = new NBTTagCompound(); nbttagcompound.func_74782_a("Level", nbttagcompound1); nbttagcompound.func_74768_a("DataVersion", 510); this.func_75820_a(p_75816_2_, p_75816_1_, nbttagcompound1); this.func_75824_a(p_75816_2_.func_76632_l(), nbttagcompound); } catch (Exception exception) { field_151505_a.error((String)"Failed to save chunk", (Throwable)exception); } } protected void func_75824_a(ChunkPos p_75824_1_, NBTTagCompound p_75824_2_) { if(!this.field_75826_b.contains(p_75824_1_)) { this.field_75828_a.put(p_75824_1_, p_75824_2_); } ThreadedFileIOBase.func_178779_a().func_75735_a(this); } public boolean func_75814_c() { if(this.field_75828_a.isEmpty()) { if(this.field_183014_e) { field_151505_a.info("ThreadedAnvilChunkStorage ({}): All chunks are saved", new Object[]{this.field_75825_d.getName()}); } return false; } else { ChunkPos chunkpos = (ChunkPos)this.field_75828_a.keySet().iterator().next(); boolean lvt_3_1_; try { this.field_75826_b.add(chunkpos); NBTTagCompound nbttagcompound = (NBTTagCompound)this.field_75828_a.remove(chunkpos); if(nbttagcompound != null) { try { this.func_183013_b(chunkpos, nbttagcompound); } catch (Exception exception) { field_151505_a.error((String)"Failed to save chunk", (Throwable)exception); } } lvt_3_1_ = true; } finally { this.field_75826_b.remove(chunkpos); } return lvt_3_1_; } } private void func_183013_b(ChunkPos p_183013_1_, NBTTagCompound p_183013_2_) throws IOException { DataOutputStream dataoutputstream = RegionFileCache.func_76552_d(this.field_75825_d, p_183013_1_.field_77276_a, p_183013_1_.field_77275_b); CompressedStreamTools.func_74800_a(p_183013_2_, dataoutputstream); dataoutputstream.close(); } public void func_75819_b(World p_75819_1_, Chunk p_75819_2_) throws IOException { } public void func_75817_a() { } public void func_75818_b() { try { this.field_183014_e = true; while(true) { if(this.func_75814_c()) { continue; } } } finally { this.field_183014_e = false; } } public static void func_189889_a(DataFixer p_189889_0_) { p_189889_0_.func_188258_a(FixTypes.CHUNK, new IDataWalker() { public NBTTagCompound func_188266_a(IDataFixer p_188266_1_, NBTTagCompound p_188266_2_, int p_188266_3_) { if(p_188266_2_.func_150297_b("Level", 10)) { NBTTagCompound nbttagcompound = p_188266_2_.func_74775_l("Level"); if(nbttagcompound.func_150297_b("Entities", 9)) { NBTTagList nbttaglist = nbttagcompound.func_150295_c("Entities", 10); for(int i = 0; i < nbttaglist.func_74745_c(); ++i) { nbttaglist.func_150304_a(i, p_188266_1_.func_188251_a(FixTypes.ENTITY, (NBTTagCompound)nbttaglist.func_179238_g(i), p_188266_3_)); } } if(nbttagcompound.func_150297_b("TileEntities", 9)) { NBTTagList nbttaglist1 = nbttagcompound.func_150295_c("TileEntities", 10); for(int j = 0; j < nbttaglist1.func_74745_c(); ++j) { nbttaglist1.func_150304_a(j, p_188266_1_.func_188251_a(FixTypes.BLOCK_ENTITY, (NBTTagCompound)nbttaglist1.func_179238_g(j), p_188266_3_)); } } } return p_188266_2_; } }); } private void func_75820_a(Chunk p_75820_1_, World p_75820_2_, NBTTagCompound p_75820_3_) { p_75820_3_.func_74768_a("xPos", p_75820_1_.field_76635_g); p_75820_3_.func_74768_a("zPos", p_75820_1_.field_76647_h); p_75820_3_.func_74772_a("LastUpdate", p_75820_2_.func_82737_E()); p_75820_3_.func_74783_a("HeightMap", p_75820_1_.func_177445_q()); p_75820_3_.func_74757_a("TerrainPopulated", p_75820_1_.func_177419_t()); p_75820_3_.func_74757_a("LightPopulated", p_75820_1_.func_177423_u()); p_75820_3_.func_74772_a("InhabitedTime", p_75820_1_.func_177416_w()); ExtendedBlockStorage[] aextendedblockstorage = p_75820_1_.func_76587_i(); NBTTagList nbttaglist = new NBTTagList(); boolean flag = !p_75820_2_.field_73011_w.func_177495_o(); for(ExtendedBlockStorage extendedblockstorage : aextendedblockstorage) { if(extendedblockstorage != Chunk.field_186036_a) { NBTTagCompound nbttagcompound = new NBTTagCompound(); nbttagcompound.func_74774_a("Y", (byte)(extendedblockstorage.func_76662_d() >> 4 & 255)); byte[] abyte = new byte[4096]; NibbleArray nibblearray = new NibbleArray(); NibbleArray nibblearray1 = extendedblockstorage.func_186049_g().func_186017_a(abyte, nibblearray); nbttagcompound.func_74773_a("Blocks", abyte); nbttagcompound.func_74773_a("Data", nibblearray.func_177481_a()); if(nibblearray1 != null) { nbttagcompound.func_74773_a("Add", nibblearray1.func_177481_a()); } nbttagcompound.func_74773_a("BlockLight", extendedblockstorage.func_76661_k().func_177481_a()); if(flag) { nbttagcompound.func_74773_a("SkyLight", extendedblockstorage.func_76671_l().func_177481_a()); } else { nbttagcompound.func_74773_a("SkyLight", new byte[extendedblockstorage.func_76661_k().func_177481_a().length]); } nbttaglist.func_74742_a(nbttagcompound); } } p_75820_3_.func_74782_a("Sections", nbttaglist); p_75820_3_.func_74773_a("Biomes", p_75820_1_.func_76605_m()); p_75820_1_.func_177409_g(false); NBTTagList nbttaglist1 = new NBTTagList(); for(int i = 0; i < p_75820_1_.func_177429_s().length; ++i) { for(Entity entity : p_75820_1_.func_177429_s()[i]) { NBTTagCompound nbttagcompound2 = new NBTTagCompound(); if(entity.func_70039_c(nbttagcompound2)) { p_75820_1_.func_177409_g(true); nbttaglist1.func_74742_a(nbttagcompound2); } } } p_75820_3_.func_74782_a("Entities", nbttaglist1); NBTTagList nbttaglist2 = new NBTTagList(); for(TileEntity tileentity : p_75820_1_.func_177434_r().values()) { NBTTagCompound nbttagcompound3 = tileentity.func_189515_b(new NBTTagCompound()); nbttaglist2.func_74742_a(nbttagcompound3); } p_75820_3_.func_74782_a("TileEntities", nbttaglist2); List<NextTickListEntry> list = p_75820_2_.func_72920_a(p_75820_1_, false); if(list != null) { long j = p_75820_2_.func_82737_E(); NBTTagList nbttaglist3 = new NBTTagList(); for(NextTickListEntry nextticklistentry : list) { NBTTagCompound nbttagcompound1 = new NBTTagCompound(); ResourceLocation resourcelocation = (ResourceLocation)Block.field_149771_c.func_177774_c(nextticklistentry.func_151351_a()); nbttagcompound1.func_74778_a("i", resourcelocation == null?"":resourcelocation.toString()); nbttagcompound1.func_74768_a("x", nextticklistentry.field_180282_a.func_177958_n()); nbttagcompound1.func_74768_a("y", nextticklistentry.field_180282_a.func_177956_o()); nbttagcompound1.func_74768_a("z", nextticklistentry.field_180282_a.func_177952_p()); nbttagcompound1.func_74768_a("t", (int)(nextticklistentry.field_77180_e - j)); nbttagcompound1.func_74768_a("p", nextticklistentry.field_82754_f); nbttaglist3.func_74742_a(nbttagcompound1); } p_75820_3_.func_74782_a("TileTicks", nbttaglist3); } } private Chunk func_75823_a(World p_75823_1_, NBTTagCompound p_75823_2_) { int i = p_75823_2_.func_74762_e("xPos"); int j = p_75823_2_.func_74762_e("zPos"); Chunk chunk = new Chunk(p_75823_1_, i, j); chunk.func_177420_a(p_75823_2_.func_74759_k("HeightMap")); chunk.func_177446_d(p_75823_2_.func_74767_n("TerrainPopulated")); chunk.func_177421_e(p_75823_2_.func_74767_n("LightPopulated")); chunk.func_177415_c(p_75823_2_.func_74763_f("InhabitedTime")); NBTTagList nbttaglist = p_75823_2_.func_150295_c("Sections", 10); int k = 16; ExtendedBlockStorage[] aextendedblockstorage = new ExtendedBlockStorage[16]; boolean flag = !p_75823_1_.field_73011_w.func_177495_o(); for(int l = 0; l < nbttaglist.func_74745_c(); ++l) { NBTTagCompound nbttagcompound = nbttaglist.func_150305_b(l); int i1 = nbttagcompound.func_74771_c("Y"); ExtendedBlockStorage extendedblockstorage = new ExtendedBlockStorage(i1 << 4, flag); byte[] abyte = nbttagcompound.func_74770_j("Blocks"); NibbleArray nibblearray = new NibbleArray(nbttagcompound.func_74770_j("Data")); NibbleArray nibblearray1 = nbttagcompound.func_150297_b("Add", 7)?new NibbleArray(nbttagcompound.func_74770_j("Add")):null; extendedblockstorage.func_186049_g().func_186019_a(abyte, nibblearray, nibblearray1); extendedblockstorage.func_76659_c(new NibbleArray(nbttagcompound.func_74770_j("BlockLight"))); if(flag) { extendedblockstorage.func_76666_d(new NibbleArray(nbttagcompound.func_74770_j("SkyLight"))); } extendedblockstorage.func_76672_e(); aextendedblockstorage[i1] = extendedblockstorage; } chunk.func_76602_a(aextendedblockstorage); if(p_75823_2_.func_150297_b("Biomes", 7)) { chunk.func_76616_a(p_75823_2_.func_74770_j("Biomes")); } NBTTagList nbttaglist1 = p_75823_2_.func_150295_c("Entities", 10); if(nbttaglist1 != null) { for(int j1 = 0; j1 < nbttaglist1.func_74745_c(); ++j1) { NBTTagCompound nbttagcompound1 = nbttaglist1.func_150305_b(j1); func_186050_a(nbttagcompound1, p_75823_1_, chunk); chunk.func_177409_g(true); } } NBTTagList nbttaglist2 = p_75823_2_.func_150295_c("TileEntities", 10); if(nbttaglist2 != null) { for(int k1 = 0; k1 < nbttaglist2.func_74745_c(); ++k1) { NBTTagCompound nbttagcompound2 = nbttaglist2.func_150305_b(k1); TileEntity tileentity = TileEntity.func_190200_a(p_75823_1_, nbttagcompound2); if(tileentity != null) { chunk.func_150813_a(tileentity); } } } if(p_75823_2_.func_150297_b("TileTicks", 9)) { NBTTagList nbttaglist3 = p_75823_2_.func_150295_c("TileTicks", 10); if(nbttaglist3 != null) { for(int l1 = 0; l1 < nbttaglist3.func_74745_c(); ++l1) { NBTTagCompound nbttagcompound3 = nbttaglist3.func_150305_b(l1); Block block; if(nbttagcompound3.func_150297_b("i", 8)) { block = Block.func_149684_b(nbttagcompound3.func_74779_i("i")); } else { block = Block.func_149729_e(nbttagcompound3.func_74762_e("i")); } p_75823_1_.func_180497_b(new BlockPos(nbttagcompound3.func_74762_e("x"), nbttagcompound3.func_74762_e("y"), nbttagcompound3.func_74762_e("z")), block, nbttagcompound3.func_74762_e("t"), nbttagcompound3.func_74762_e("p")); } } } return chunk; } @Nullable public static Entity func_186050_a(NBTTagCompound p_186050_0_, World p_186050_1_, Chunk p_186050_2_) { Entity entity = func_186053_a(p_186050_0_, p_186050_1_); if(entity == null) { return null; } else { p_186050_2_.func_76612_a(entity); if(p_186050_0_.func_150297_b("Passengers", 9)) { NBTTagList nbttaglist = p_186050_0_.func_150295_c("Passengers", 10); for(int i = 0; i < nbttaglist.func_74745_c(); ++i) { Entity entity1 = func_186050_a(nbttaglist.func_150305_b(i), p_186050_1_, p_186050_2_); if(entity1 != null) { entity1.func_184205_a(entity, true); } } } return entity; } } @Nullable public static Entity func_186054_a(NBTTagCompound p_186054_0_, World p_186054_1_, double p_186054_2_, double p_186054_4_, double p_186054_6_, boolean p_186054_8_) { Entity entity = func_186053_a(p_186054_0_, p_186054_1_); if(entity == null) { return null; } else { entity.func_70012_b(p_186054_2_, p_186054_4_, p_186054_6_, entity.field_70177_z, entity.field_70125_A); if(p_186054_8_ && !p_186054_1_.func_72838_d(entity)) { return null; } else { if(p_186054_0_.func_150297_b("Passengers", 9)) { NBTTagList nbttaglist = p_186054_0_.func_150295_c("Passengers", 10); for(int i = 0; i < nbttaglist.func_74745_c(); ++i) { Entity entity1 = func_186054_a(nbttaglist.func_150305_b(i), p_186054_1_, p_186054_2_, p_186054_4_, p_186054_6_, p_186054_8_); if(entity1 != null) { entity1.func_184205_a(entity, true); } } } return entity; } } } @Nullable protected static Entity func_186053_a(NBTTagCompound p_186053_0_, World p_186053_1_) { try { return EntityList.func_75615_a(p_186053_0_, p_186053_1_); } catch (RuntimeException var3) { return null; } } public static void func_186052_a(Entity p_186052_0_, World p_186052_1_) { if(p_186052_1_.func_72838_d(p_186052_0_) && p_186052_0_.func_184207_aI()) { for(Entity entity : p_186052_0_.func_184188_bt()) { func_186052_a(entity, p_186052_1_); } } } @Nullable public static Entity func_186051_a(NBTTagCompound p_186051_0_, World p_186051_1_, boolean p_186051_2_) { Entity entity = func_186053_a(p_186051_0_, p_186051_1_); if(entity == null) { return null; } else if(p_186051_2_ && !p_186051_1_.func_72838_d(entity)) { return null; } else { if(p_186051_0_.func_150297_b("Passengers", 9)) { NBTTagList nbttaglist = p_186051_0_.func_150295_c("Passengers", 10); for(int i = 0; i < nbttaglist.func_74745_c(); ++i) { Entity entity1 = func_186051_a(nbttaglist.func_150305_b(i), p_186051_1_, p_186051_2_); if(entity1 != null) { entity1.func_184205_a(entity, true); } } } return entity; } } }
gpl-3.0
itachi1706/PneumaticCraft
src/pneumaticCraft/common/network/PacketSetGlobalVariable.java
2025
package pneumaticCraft.common.network; import io.netty.buffer.ByteBuf; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiScreen; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.world.ChunkPosition; import pneumaticCraft.client.gui.GuiRemote; import pneumaticCraft.common.remote.GlobalVariableManager; import cpw.mods.fml.common.network.ByteBufUtils; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; public class PacketSetGlobalVariable extends AbstractPacket<PacketSetGlobalVariable>{ private String varName; private ChunkPosition value; public PacketSetGlobalVariable(){} public PacketSetGlobalVariable(String varName, ChunkPosition value){ this.varName = varName; this.value = value; } public PacketSetGlobalVariable(String varName, int value){ this(varName, new ChunkPosition(value, 0, 0)); } public PacketSetGlobalVariable(String varName, boolean value){ this(varName, value ? 1 : 0); } @Override public void fromBytes(ByteBuf buf){ varName = ByteBufUtils.readUTF8String(buf); value = new ChunkPosition(buf.readInt(), buf.readInt(), buf.readInt()); } @Override public void toBytes(ByteBuf buf){ ByteBufUtils.writeUTF8String(buf, varName); buf.writeInt(value.chunkPosX); buf.writeInt(value.chunkPosY); buf.writeInt(value.chunkPosZ); } @Override @SideOnly(Side.CLIENT) public void handleClientSide(PacketSetGlobalVariable message, EntityPlayer player){ handleServerSide(message, player); GuiScreen screen = Minecraft.getMinecraft().currentScreen; if(screen instanceof GuiRemote) { ((GuiRemote)screen).onGlobalVariableChange(message.varName); } } @Override public void handleServerSide(PacketSetGlobalVariable message, EntityPlayer player){ GlobalVariableManager.getInstance().set(message.varName, message.value); } }
gpl-3.0
obiba/onyx
onyx-core/src/main/java/org/obiba/onyx/print/impl/DefaultPdfTemplateEngine.java
7587
/******************************************************************************* * Copyright 2008(c) The OBiBa Consortium. All rights reserved. * * This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package org.obiba.onyx.print.impl; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import org.obiba.magma.NoSuchVariableException; import org.obiba.magma.Value; import org.obiba.magma.ValueSet; import org.obiba.magma.ValueTable; import org.obiba.magma.VariableValueSource; import org.obiba.magma.type.DateTimeType; import org.obiba.magma.type.TextType; import org.obiba.onyx.core.domain.participant.Participant; import org.obiba.onyx.core.io.support.LocalizedResourceLoader; import org.obiba.onyx.core.service.ActiveInterviewService; import org.obiba.onyx.magma.MagmaInstanceProvider; import org.obiba.onyx.print.PdfTemplateEngine; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Required; import org.springframework.context.MessageSource; import org.springframework.core.io.Resource; import com.lowagie.text.pdf.AcroFields; import com.lowagie.text.pdf.PdfReader; import com.lowagie.text.pdf.PdfStamper; public class DefaultPdfTemplateEngine implements PdfTemplateEngine { private static final Logger log = LoggerFactory.getLogger(PdfTemplateReport.class); private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); private MagmaInstanceProvider magmaInstanceProvider; private MessageSource messageSource; public void setMagmaInstanceProvider(MagmaInstanceProvider magmaInstanceProvider) { this.magmaInstanceProvider = magmaInstanceProvider; } @Required public void setMessageSource(MessageSource messageSource) { this.messageSource = messageSource; } public InputStream applyTemplate(Locale locale, Map<String, String> fieldToVariableMap, LocalizedResourceLoader reportTemplateLoader, ActiveInterviewService activeInterviewService) { // Get report template Resource resource = reportTemplateLoader.getLocalizedResource(locale); // Read report template PdfReader pdfReader; try { pdfReader = new PdfReader(resource.getInputStream()); } catch(Exception ex) { throw new RuntimeException("Report to participant template cannot be read", ex); } ByteArrayOutputStream output = new ByteArrayOutputStream(); PdfStamper stamper = null; // Set the values in the report data fields try { stamper = new PdfStamper(pdfReader, output); stamper.setFormFlattening(true); AcroFields form = stamper.getAcroFields(); Participant participant = activeInterviewService.getParticipant(); setVariableDataFields(participant, form, fieldToVariableMap, locale); setAdditionalDataFields(form); } catch(Exception ex) { throw new RuntimeException("An error occured while preparing the report to participant", ex); } finally { try { stamper.close(); } catch(Exception e) { log.warn("Could not close PdfStamper", e); } try { output.close(); } catch(IOException e) { log.warn("Could not close OutputStream", e); } pdfReader.close(); } return new ByteArrayInputStream(output.toByteArray()); } public void setDateFormat(String dateFormat) { this.dateFormat = new SimpleDateFormat(dateFormat); } private void setAdditionalDataFields(AcroFields form) { try { form.setField("DateInterview\\.date", dateFormat.format(new Date())); } catch(Exception ex) { throw new RuntimeException(ex); } } private void setVariableDataFields(Participant participant, AcroFields form, Map<String, String> fieldToVariableMap, Locale locale) { HashMap<String, String> fieldList = form.getFields(); try { // Iterate on each field of pdf template for(Entry<String, String> field : fieldList.entrySet()) { String[] keys = splitData(field.getKey()); // TEMPORARY FIX so that "NA" is displayed in a field if the data is not available. // This should be replaced by a default value for the field in the PDF template, // however this didn't seem to work when I tested it (default values were not getting printed) // We need to find a way to fix that (might be a bug in Acrobat forms). form.setField(field.getKey(), "N/A"); // Iterate on each key for one field of pdf template (for example when a variable depends on several // instruments) for(String variableKey : keys) { String variablePath = fieldToVariableMap.get(variableKey); if(variablePath != null) { try { ValueTable valueTable = magmaInstanceProvider.resolveTableFromVariablePath(variablePath); VariableValueSource variable = magmaInstanceProvider.resolveVariablePath(variablePath); ValueSet valueSet = valueTable.getValueSet(magmaInstanceProvider.newParticipantEntity(participant)); String valueString = getValueAsString(variable.getVariable(), variable.getValue(valueSet), locale); if(valueString != null && valueString.length() != 0) { form.setField(field.getKey(), valueString); break; } } catch(NoSuchVariableException e) { log.error("Invalid PDF template definition. Field '{}' is linked to inexistent variable '{}'.", field.getKey(), variablePath); throw e; } } } } } catch(Exception ex) { throw new RuntimeException(ex); } } private String getValueAsString(org.obiba.magma.Variable variable, Value value, Locale locale) { if(value.isNull()) return ""; String valueString = ""; if(value.isSequence()) { for(Value v : value.asSequence().getValues()) { valueString += " " + getValueAsString(variable, v, locale); } } else { valueString = value.toString(); String unit = variable.getUnit(); if(value.getValueType() == DateTimeType.get()) { valueString = dateFormat.format(value.getValue()); } else if(value.getValueType() == TextType.get() && unit == null) { valueString = messageSource.getMessage(valueString, null, valueString, locale); } else { if(variable != null && unit != null) valueString += " " + unit; } } return valueString; } private String[] splitData(String string) { // By default, a field name in a PDF form starts with "form[0].page[0].", concatenated with the custom name that we // gave to this field String pattern = "([a-zA-Z0-9]+\\[+[0-9]+\\]+\\.){2}"; // Delete "form[0].page[0]." string to keep only the custom name given to the variable String variable = string.replaceFirst(pattern, ""); variable = variable.replaceAll("\\[[0-9]\\]", ""); // If multiple instrument types are used for the same field, they are separated by "-" String[] list = variable.split("-"); return list; } }
gpl-3.0
niuran1993/Deskera-HRMS
mavenHrmsSpring/src/main/java/com/krawler/esp/servlets/ExportServlet.java
31076
/* * Copyright (C) 2012 Krawler Information Systems Pvt Ltd * All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package com.krawler.esp.servlets; import com.krawler.common.admin.KWLCurrency; import com.krawler.common.session.SessionExpiredException; import java.awt.Color; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.hibernate.Session; import com.krawler.esp.database.hrmsDbcon; import com.krawler.common.service.ServiceException; import com.krawler.common.util.StringUtil; import com.krawler.common.util.URLUtil; import com.krawler.esp.database.payrollDBCon; import com.krawler.esp.handlers.AuthHandler; import com.krawler.esp.handlers.StorageHandler; import com.krawler.esp.hibernate.impl.HibernateUtil; import com.krawler.utils.json.base.JSONArray; import com.krawler.utils.json.base.JSONException; import com.krawler.utils.json.base.JSONObject; import com.lowagie.text.Document; import com.lowagie.text.DocumentException; import com.lowagie.text.Element; import com.lowagie.text.ExceptionConverter; import com.lowagie.text.Font; import com.lowagie.text.FontFactory; import com.lowagie.text.HeaderFooter; import com.lowagie.text.Image; import com.lowagie.text.PageSize; import com.lowagie.text.Paragraph; import com.lowagie.text.Phrase; import com.lowagie.text.Rectangle; import com.lowagie.text.pdf.PdfCell; import com.lowagie.text.pdf.PdfContentByte; import com.lowagie.text.pdf.PdfPCell; import com.lowagie.text.pdf.PdfPTable; import com.lowagie.text.pdf.PdfPageEventHelper; import com.lowagie.text.pdf.PdfWriter; import java.text.DecimalFormat; import javax.naming.ConfigurationException; public class ExportServlet extends HttpServlet { private static Font fontSmallRegular = FontFactory.getFont("Helvetica", 8, Font.BOLD, Color.BLACK); private static Font fontMediumRegular = FontFactory.getFont("Helvetica", 12, Font.NORMAL, Color.BLACK); private static Font fontMediumBold = FontFactory.getFont("Helvetica", 12, Font.BOLD, Color.BLACK); private static Font fontSmallBold = FontFactory.getFont("Helvetica", 8, Font.BOLD, Color.BLACK); private static Font fontRegular = FontFactory.getFont("Helvetica", 12, Font.NORMAL, Color.BLACK); private static Font fontBold = FontFactory.getFont("Helvetica", 12, Font.BOLD, Color.BLACK); private static Font fontBig = FontFactory.getFont("Helvetica", 24, Font.NORMAL, Color.BLACK); private static String imgPath = ""; private static String companyName = "Deskera"; private static final String defaultCompanyImgPath = "images/logo.gif"; private static com.krawler.utils.json.base.JSONObject config = null; private PdfPTable header = null; private PdfPTable footer = null; public class EndPage extends PdfPageEventHelper { public void onEndPage(PdfWriter writer, Document document) { try { Rectangle page = document.getPageSize(); getHeaderFooter(document); // Add page header header.setTotalWidth(page.getWidth()-document.leftMargin()-document.rightMargin()); header.writeSelectedRows(0, -1, document.leftMargin(), page.getHeight()-10 ,writer.getDirectContent()); // Add page footer footer.setTotalWidth(page.getWidth()-document.leftMargin()-document.rightMargin()); footer.writeSelectedRows(0, -1, document.leftMargin(), document.bottomMargin()-5 ,writer.getDirectContent()); // Add page border if (config.getBoolean("pageBorder")) { int bmargin = 8; //border margin PdfContentByte cb = writer.getDirectContent(); cb.rectangle( bmargin, bmargin, page.getWidth() - bmargin*2, page.getHeight() - bmargin*2); cb.setColorStroke(Color.LIGHT_GRAY); cb.stroke(); } } catch (JSONException e) { throw new ExceptionConverter(e); } } } private static final long serialVersionUID = -8401651817881523209L; static SimpleDateFormat df = new SimpleDateFormat("yyyy-M-dd"); protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, ServiceException, IOException, SessionExpiredException, JSONException { if (com.krawler.esp.handlers.SessionHandler.isValidSession(request, response)) { org.hibernate.Session session = null; ByteArrayOutputStream baos = null; String filename = request.getParameter("name"); String fileType = null; JSONObject grid=null; JSONArray gridmap=null; try { session = HibernateUtil.getCurrentSession(); fileType = request.getParameter("filetype"); if(request.getParameter("gridconfig")!=null) { grid = new JSONObject(request.getParameter("gridconfig")); gridmap = grid.getJSONArray("data"); } if (StringUtil.equal(fileType, "csv")) { createCsvFile(session, request, response); } else if (StringUtil.equal(fileType, "pdf")) { baos = getPdfData(gridmap, request,session); writeDataToFile(filename, fileType, baos, response); } } catch (Exception ex) { throw ServiceException.FAILURE(ex.getMessage(), ex); } finally { HibernateUtil.closeSession(session); } } else { response.getOutputStream().println("{\"valid\": false}"); } } private void writeDataToFile(String filename, String fileType, ByteArrayOutputStream baos, HttpServletResponse response) throws IOException { try { response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "." + fileType + "\""); response.setContentType("application/octet-stream"); response.setContentLength(baos.size()); response.getOutputStream().write(baos.toByteArray()); response.getOutputStream().flush(); response.getOutputStream().close(); } catch(IOException e){ response.getOutputStream().println("{\"valid\": false}"); } } private static void addComponyLogo(Document d, HttpServletRequest req) throws ConfigurationException, DocumentException { PdfPTable table = new PdfPTable(1); imgPath = StorageHandler.GetProfileImgStorePath() + "logo.gif"; table.setHorizontalAlignment(Element.ALIGN_LEFT); table.setWidthPercentage(50); PdfPCell cell = null; try { if(StringUtil.isStandAlone()){ imgPath = URLUtil.getPageURL(req, "").concat(defaultCompanyImgPath); } Image img = Image.getInstance(imgPath); cell = new PdfPCell(img); } catch (Exception e) { cell = new PdfPCell(new Paragraph(companyName, fontBig)); } cell.setBorder(0); cell.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(cell); d.add(table); } private static void addTitleSubtitle(Document d) throws DocumentException, JSONException { java.awt.Color tColor = new Color(Integer.parseInt(config.getString("textColor"), 16)); fontBold.setColor(tColor); fontRegular.setColor(tColor); PdfPTable table = new PdfPTable(1); table.setHorizontalAlignment(Element.ALIGN_CENTER); table.setWidthPercentage(100); table.setSpacingBefore(6); //Report Title PdfPCell cell = new PdfPCell(new Paragraph(config.getString("title"), fontBold)); cell.setBorder(0); cell.setBorderWidth(0); cell.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(cell); //Report Subtitle(s) String[] SubTitles = config.getString("subtitles").split("~");// '~' as separator for(int i=0; i < SubTitles.length; i++){ cell = new PdfPCell(new Paragraph(SubTitles[i], fontSmallRegular)); cell.setBorder(0); cell.setBorderWidth(0); cell.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(cell); } table.setSpacingAfter(6); d.add(table); //Separator line PdfPTable line = new PdfPTable(1); line.setWidthPercentage(100); PdfPCell cell1 = null; cell1 = new PdfPCell(new Paragraph("")); cell1.setBorder(PdfPCell.BOTTOM); line.addCell(cell1); d.add(line); } private int addTable(int stcol, int stpcol, int strow, int stprow, JSONArray store, String[] colwidth2, String[] colHeader, String[] widths, String[] align, Document document,HttpServletRequest request,Session session) throws JSONException, DocumentException, SessionExpiredException { java.awt.Color tColor = new Color(Integer.parseInt(config.getString("textColor"), 16)); fontSmallBold.setColor(tColor); PdfPTable table; float[] tcol; tcol = new float[colHeader.length+1]; tcol[0]=40; for(int i=1;i<colHeader.length+1;i++) { tcol[i] = Float.parseFloat(widths[i-1]); } table = new PdfPTable(colHeader.length+1); table.setWidthPercentage(tcol,document.getPageSize()); table.setSpacingBefore(15); Font f1 = FontFactory.getFont("Helvetica", 8, Font.NORMAL, tColor); PdfPCell h2 = new PdfPCell(new Paragraph("No.", fontSmallBold)); if (config.getBoolean("gridBorder")) { h2.setBorder(PdfPCell.BOX); } else { h2.setBorder(0); } h2.setPadding(4); h2.setBorderColor(Color.GRAY); h2.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(h2); PdfPCell h1=null; for (int hcol = stcol; hcol < colwidth2.length; hcol++) { if(align[hcol].equals("right") && !colHeader[hcol].equals("")) { String currency = currencyRender("",session,request); h1 = new PdfPCell(new Paragraph(colHeader[hcol]+"("+currency+")", fontSmallBold)); } else h1 = new PdfPCell(new Paragraph(colHeader[hcol], fontSmallBold)); h1.setHorizontalAlignment(Element.ALIGN_CENTER); if (config.getBoolean("gridBorder")) { h1.setBorder(PdfPCell.BOX); } else { h1.setBorder(0); } h1.setBorderColor(Color.GRAY); h1.setPadding(4); table.addCell(h1); } table.setHeaderRows(1); for (int row = strow; row <stprow ; row++) { h2 = new PdfPCell(new Paragraph(String.valueOf(row + 1), f1)); if (config.getBoolean("gridBorder")) { h2.setBorder(PdfPCell.BOTTOM | PdfPCell.LEFT | PdfPCell.RIGHT); } else { h2.setBorder(0); } h2.setPadding(4); h2.setBorderColor(Color.GRAY); h2.setHorizontalAlignment(Element.ALIGN_CENTER); h2.setVerticalAlignment(Element.ALIGN_CENTER); table.addCell(h2); JSONObject temp = store.getJSONObject(row); for (int col = 0; col < colwidth2.length; col++) { Paragraph para = null; if(align[col].equals("right") && !temp.getString(colwidth2[col]).equals("")) { String currency = currencyRender(temp.getString(colwidth2[col]),session,request); para = new Paragraph(currency, f1); } else { if (colwidth2[col].equals("invoiceno")) { para=new Paragraph(temp.getString("no").toString(),f1); } else if (colwidth2[col].equals("invoicedate")) { para=new Paragraph(temp.getString("date").toString(),f1); } else if ((temp.isNull(colwidth2[col])) && !(colwidth2[col].equals("invoiceno")) && !(colwidth2[col].equals("invoicedate"))) { para =new Paragraph("", fontMediumRegular); } else { para=new Paragraph(temp.getString(colwidth2[col]).toString(),f1); } } h1 = new PdfPCell(para); if (config.getBoolean("gridBorder")) { h1.setBorder(PdfPCell.BOTTOM | PdfPCell.LEFT | PdfPCell.RIGHT); } else { h1.setBorder(0); } h1.setPadding(4); h1.setBorderColor(Color.GRAY); if(!align[col].equals("right") && !align[col].equals("left")) { h1.setHorizontalAlignment(Element.ALIGN_CENTER); h1.setVerticalAlignment(Element.ALIGN_CENTER); } else if(align[col].equals("right")) { h1.setHorizontalAlignment(Element.ALIGN_RIGHT); h1.setVerticalAlignment(Element.ALIGN_RIGHT); } else if(align[col].equals("left")) { h1.setHorizontalAlignment(Element.ALIGN_LEFT); h1.setVerticalAlignment(Element.ALIGN_LEFT); } table.addCell(h1); } } document.add(table); document.newPage(); return stpcol; } public void getHeaderFooter(Document document) throws JSONException { java.awt.Color tColor = new Color(Integer.parseInt(config.getString("textColor"), 16)); fontSmallRegular.setColor(tColor); java.util.Date dt = new java.util.Date(); String date="yyyy-MM-dd"; java.text.SimpleDateFormat dtf = new java.text.SimpleDateFormat(date); String DateStr = dtf.format(dt); // -------- header ---------------- header = new PdfPTable(3); String HeadDate = ""; if (config.getBoolean("headDate")) HeadDate = DateStr; PdfPCell headerDateCell = new PdfPCell(new Phrase( HeadDate, fontSmallRegular)); headerDateCell.setBorder(0); headerDateCell.setPaddingBottom(4); header.addCell(headerDateCell); PdfPCell headerNotecell = new PdfPCell(new Phrase(config.getString("headNote"), fontSmallRegular)); headerNotecell.setBorder(0); headerNotecell.setPaddingBottom(4); headerNotecell.setHorizontalAlignment(PdfCell.ALIGN_CENTER); header.addCell(headerNotecell); String HeadPager = ""; if(config.getBoolean("headPager")) HeadPager = String.valueOf(document.getPageNumber());//current page no PdfPCell headerPageNocell = new PdfPCell(new Phrase(HeadPager, fontSmallRegular)); headerPageNocell.setBorder(0); headerPageNocell.setPaddingBottom(4); headerPageNocell.setHorizontalAlignment(PdfCell.ALIGN_RIGHT); header.addCell(headerPageNocell); PdfPCell headerSeparator = new PdfPCell(new Phrase("")); headerSeparator.setBorder(PdfPCell.BOX); headerSeparator.setPadding(0); headerSeparator.setColspan(3); header.addCell(headerSeparator); // -------- header end ---------------- // -------- footer ------------------- footer = new PdfPTable(3); PdfPCell footerSeparator = new PdfPCell(new Phrase("")); footerSeparator.setBorder(PdfPCell.BOX); footerSeparator.setPadding(0); footerSeparator.setColspan(3); footer.addCell(footerSeparator); String PageDate = ""; if(config.getBoolean("footDate")) PageDate = DateStr; PdfPCell pagerDateCell = new PdfPCell(new Phrase( PageDate, fontSmallRegular)); pagerDateCell.setBorder(0); footer.addCell(pagerDateCell); PdfPCell footerNotecell = new PdfPCell(new Phrase(config.getString("footNote"), fontSmallRegular)); footerNotecell.setBorder(0); footerNotecell.setHorizontalAlignment(PdfCell.ALIGN_CENTER); footer.addCell(footerNotecell); String FootPager = ""; if(config.getBoolean("footPager")) FootPager = String.valueOf(document.getPageNumber());//current page no PdfPCell footerPageNocell = new PdfPCell(new Phrase(FootPager, fontSmallRegular)); footerPageNocell.setBorder(0); footerPageNocell.setHorizontalAlignment(PdfCell.ALIGN_RIGHT); footer.addCell(footerPageNocell); // -------- footer end ----------- } private ByteArrayOutputStream getPdfData(JSONArray gridmap, HttpServletRequest request,Session session) throws ServiceException, SessionExpiredException{ ByteArrayOutputStream baos = new ByteArrayOutputStream(); PdfWriter writer=null; try{ String colHeader =""; String colHeaderFinal=""; String fieldListFinal =""; String fieldList = ""; String width=""; String align=""; String alignFinal=""; String widthFinal=""; String colHeaderArrStr[]=null; String dataIndexArrStr[]=null; String widthArrStr[]=null; String alignArrStr[]=null; String htmlCode=""; String advStr=""; int strLength=0; float totalWidth=0; config = new com.krawler.utils.json.base.JSONObject(request.getParameter("config")); String tmpTitle = config.getString("title"); Document document = null; Rectangle rec =null; if (config.getBoolean("landscape")){ Rectangle recPage=new Rectangle(PageSize.A4.rotate()); recPage.setBackgroundColor(new java.awt.Color(Integer.parseInt(config.getString("bgColor"), 16))); document = new Document(recPage, 15, 15, 30, 30); rec=document.getPageSize(); totalWidth=rec.getWidth(); } else { Rectangle recPage=new Rectangle(PageSize.A4); recPage.setBackgroundColor(new java.awt.Color(Integer.parseInt(config.getString("bgColor"), 16))); document = new Document(recPage, 15, 15, 30, 30); rec=document.getPageSize(); totalWidth=rec.getWidth(); } writer = PdfWriter.getInstance(document, baos); writer.setPageEvent(new EndPage()); document.open(); if (config.getBoolean("showLogo")) { addComponyLogo(document, request); } addTitleSubtitle(document); if(gridmap!=null) { for (int i = 0; i < gridmap.length(); i++) { JSONObject temp = gridmap.getJSONObject(i); colHeader+=temp.getString("title"); if(colHeader.indexOf("*")!=-1) colHeader = colHeader.substring(0, colHeader.indexOf("*")-1)+","; else colHeader += ","; fieldList += temp.getString("header") + ","; if(!config.getBoolean("landscape")) { int totalWidth1=(int) ((totalWidth / gridmap.length()) - 5.00); width+=""+totalWidth1 +","; //resize according to page view[potrait] } else width += temp.getString("width") + ","; if (temp.getString("align").equals("")) { align += "none" + ","; } else { align +=temp.getString("align")+","; } } strLength = colHeader.length() - 1; colHeaderFinal = colHeader.substring(0, strLength); strLength = fieldList.length() - 1; fieldListFinal = fieldList.substring(0, strLength); strLength = width.length() - 1; widthFinal = width.substring(0, strLength); strLength = align.length() - 1; alignFinal = align.substring(0, strLength); colHeaderArrStr = colHeaderFinal.split(","); dataIndexArrStr = fieldListFinal.split(","); widthArrStr = widthFinal.split(","); alignArrStr = alignFinal.split(","); } else { fieldList=request.getParameter("header"); colHeader=request.getParameter("title"); width=request.getParameter("width"); align=request.getParameter("align"); colHeaderArrStr = colHeader.split(","); dataIndexArrStr = fieldList.split(","); widthArrStr = width.split(","); alignArrStr = align.split(","); } JSONObject obj = null; obj = getReport(request, session); JSONArray store = obj.getJSONArray("data"); addTable(0, colHeaderArrStr.length, 0, store.length(), store, dataIndexArrStr, colHeaderArrStr, widthArrStr, alignArrStr, document, request, session); document.close(); } catch (ConfigurationException ex) { throw ServiceException.FAILURE("ExportProjectReport.getPdfData", ex); } catch (DocumentException ex) { throw ServiceException.FAILURE("ExportProjectReport.getPdfData", ex); } catch (JSONException e){ throw ServiceException.FAILURE("ExportProjectReport.getPdfData", e); }finally{ writer.close(); } return baos; } public String currencyRender(String currency,Session session,HttpServletRequest request) throws SessionExpiredException { KWLCurrency cur = (KWLCurrency)session.load(KWLCurrency.class, AuthHandler.getCurrencyID(request)); String symbol=cur.getHtmlcode(); try{ char temp= (char) Integer.parseInt(symbol,16); symbol=Character.toString(temp); } catch (Exception e){ } float v = 0; DecimalFormat decimalFormat = new DecimalFormat("#,##0.00"); if(currency.equals("")) return symbol; v = Float.parseFloat(currency); String fmt=decimalFormat.format(v); fmt=symbol+fmt; return fmt; } public static JSONObject getReport(HttpServletRequest request, Session session) throws ServiceException, JSONException { JSONObject obj = new JSONObject(); try { int mode = Integer.parseInt(request.getParameter("get")); switch (mode) { case 2: obj = hrmsDbcon.getTimesheetReport(request); break; case 4: String result = ""; JSONObject tempobj = new JSONObject(); payrollDBCon rh = new payrollDBCon(); result = rh.getter(34, request); tempobj = new JSONObject(result); obj = tempobj.getJSONObject("data"); break; case 5: String result1 = ""; JSONObject tempobj1 = new JSONObject(); payrollDBCon rh1 = new payrollDBCon(); result1 = rh1.getter(48, request); tempobj1 = new JSONObject(result1); obj = tempobj1.getJSONObject("data"); break; } } catch (Exception ex) { throw ServiceException.FAILURE(ex.getMessage(), ex); } finally { } return obj; } public static void createCsvFile(Session session, HttpServletRequest request, HttpServletResponse response) { try { String report = request.getParameter("get"); String headers[] = null; String titles[] = null; JSONObject obj = null; String nm = null; obj = getReport(request, session); if (request.getParameter("header") != null) { String head = request.getParameter("header"); String tit = request.getParameter("title"); headers = (String[]) head.split(","); titles = (String[]) tit.split(","); } else { headers = (String[]) obj.getString("header").split(","); titles = (String[]) obj.getString("title").split(","); } StringBuilder reportSB = new StringBuilder(); JSONArray repArr = obj.getJSONArray("data"); for (int h = 0; h < headers.length; h++) { if (h < headers.length - 1) { reportSB.append("\"" + titles[h] + "\","); } else { reportSB.append("\"" + titles[h] + "\"\n"); } } for (int t = 0; t < repArr.length(); t++) { JSONObject temp = repArr.getJSONObject(t); for (int h = 0; h < headers.length; h++) { if (h < headers.length - 1) { if (headers[h].equals("invoiceno")) { reportSB.append("\" " + temp.getString("no") + "\","); } else if (headers[h].equals("invoicedate")) { reportSB.append("\" " + temp.getString("date") + "\","); } else if ((temp.isNull(headers[h])) && !(headers[h].equals("invoiceno")) && !(headers[h].equals("invoicedate"))) { reportSB.append(","); } else { reportSB.append("\" " + temp.getString(headers[h]) + "\","); } } else { if (headers[h].equals("invoiceno")) { reportSB.append("\" " + temp.getString("no") + "\"\n"); } else if (headers[h].equals("invoicedate")) { reportSB.append("\" " + temp.getString("date") + "\"\n"); } else if ((temp.isNull(headers[h])) && !(headers[h].equals("invoiceno")) && !(headers[h].equals("invoicedate"))) { reportSB.append("\" \"\n"); } else { reportSB.append("\"" + temp.getString(headers[h]) + "\"\n"); } } } } String fname = request.getParameter("name"); nm = request.getParameter("name"); if (nm == null || nm == "") { nm = fname; } ByteArrayOutputStream os = new ByteArrayOutputStream(); os.write(reportSB.toString().getBytes()); os.close(); response.setHeader("Content-Disposition", "attachment; filename=\"" + fname + ".csv\""); response.setContentType("application/octet-stream"); response.setContentLength(os.size()); response.getOutputStream().write(os.toByteArray()); response.getOutputStream().flush(); } catch (ServiceException ex) { Logger.getLogger(ExportServlet.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(ExportServlet.class.getName()).log(Level.SEVERE, null, ex); } catch (JSONException e) { Logger.getLogger(ExportServlet.class.getName()).log(Level.SEVERE, null, e); } } public static void setHeaderFooter(Document doc, String headerText) { HeaderFooter footer = new HeaderFooter(new Phrase(" ", FontFactory.getFont("Helvetica", 8, Font.NORMAL, Color.BLACK)), true); footer.setBorderWidth(0); footer.setBorderWidthTop(1); footer.setAlignment(HeaderFooter.ALIGN_RIGHT); doc.setFooter(footer); HeaderFooter header = new HeaderFooter(new Phrase(headerText, FontFactory.getFont("Helvetica", 14, Font.BOLD, Color.BLACK)), false); doc.setHeader(header); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { doPost(request, response); } catch (Exception ex) { Logger.getLogger(ExportServlet.class.getName()).log(Level.SEVERE, null, ex); } } /** * Handles the HTTP <code>POST</code> method. * * @param request * servlet request * @param response * servlet response */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { try { processRequest(request, response); } catch (SessionExpiredException ex) { Logger.getLogger(ExportServlet.class.getName()).log(Level.SEVERE, null, ex); } catch (JSONException ex) { Logger.getLogger(ExportServlet.class.getName()).log(Level.SEVERE, null, ex); } } catch (ServiceException ex) { Logger.getLogger(ExportServlet.class.getName()).log(Level.SEVERE, null, ex); } } /** * Returns a short description of the servlet. */ public String getServletInfo() { return "Short description"; } }
gpl-3.0
sss/document-viewer
document-viewer/src/main/java/org/ebookdroid/droids/mupdf/codec/MuPdfDocument.java
2718
package org.ebookdroid.droids.mupdf.codec; import org.ebookdroid.common.settings.AppSettings; import org.ebookdroid.core.codec.AbstractCodecDocument; import org.ebookdroid.core.codec.CodecPage; import org.ebookdroid.core.codec.CodecPageInfo; import org.ebookdroid.core.codec.OutlineLink; import android.graphics.RectF; import java.util.List; public class MuPdfDocument extends AbstractCodecDocument { public static final int FORMAT_PDF = 0; public static final int FORMAT_XPS = 1; public static final int FORMAT_CBZ = 2; public static final int FORMAT_EPUB = 3; public static final int FORMAT_FB2 = 4; MuPdfDocument(final MuPdfContext context, final int format, final String fname, final String pwd) { super(context, open(AppSettings.current().pdfStorageSize << 20, format, fname, pwd)); } @Override public List<OutlineLink> getOutline() { final MuPdfOutline ou = new MuPdfOutline(); return ou.getOutline(documentHandle); } @Override public CodecPage getPage(final int pageNumber) { return MuPdfPage.createPage(documentHandle, pageNumber + 1); } @Override public int getPageCount() { return getPageCount(documentHandle); } @Override public CodecPageInfo getPageInfo(final int pageNumber) { final CodecPageInfo info = new CodecPageInfo(); final int res = getPageInfo(documentHandle, pageNumber + 1, info); if (res == -1) { return null; } else { // Check rotation info.rotation = (360 + info.rotation) % 360; return info; } } @Override protected void freeDocument() { free(documentHandle); } static void normalizeLinkTargetRect(final long docHandle, final int targetPage, final RectF targetRect, final int flags) { final CodecPageInfo cpi = new CodecPageInfo(); MuPdfDocument.getPageInfo(docHandle, targetPage, cpi); final float left = targetRect.left; final float top = targetRect.top; if (((cpi.rotation / 90) % 2) != 0) { targetRect.right = targetRect.left = left / cpi.height; targetRect.bottom = targetRect.top = top / cpi.width; } else { targetRect.right = targetRect.left = left / cpi.width; targetRect.bottom = targetRect.top = top / cpi.height; } } native static int getPageInfo(long docHandle, int pageNumber, CodecPageInfo cpi); private static native long open(int storememory, int format, String fname, String pwd); private static native void free(long handle); private static native int getPageCount(long handle); }
gpl-3.0
TheGreatAndPowerfulWeegee/wipunknown
build/tmp/recompileMc/sources/net/minecraft/client/entity/AbstractClientPlayer.java
5917
package net.minecraft.client.entity; import com.mojang.authlib.GameProfile; import java.io.File; import javax.annotation.Nullable; import net.minecraft.client.Minecraft; import net.minecraft.client.network.NetworkPlayerInfo; import net.minecraft.client.renderer.ImageBufferDownload; import net.minecraft.client.renderer.ThreadDownloadImageData; import net.minecraft.client.renderer.texture.ITextureObject; import net.minecraft.client.renderer.texture.TextureManager; import net.minecraft.client.resources.DefaultPlayerSkin; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.ai.attributes.IAttributeInstance; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Items; import net.minecraft.util.ResourceLocation; import net.minecraft.util.StringUtils; import net.minecraft.world.GameType; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) public abstract class AbstractClientPlayer extends EntityPlayer { private NetworkPlayerInfo playerInfo; public float rotateElytraX; public float rotateElytraY; public float rotateElytraZ; public AbstractClientPlayer(World worldIn, GameProfile playerProfile) { super(worldIn, playerProfile); } /** * Returns true if the player is in spectator mode. */ public boolean isSpectator() { NetworkPlayerInfo networkplayerinfo = Minecraft.getMinecraft().getConnection().getPlayerInfo(this.getGameProfile().getId()); return networkplayerinfo != null && networkplayerinfo.getGameType() == GameType.SPECTATOR; } public boolean isCreative() { NetworkPlayerInfo networkplayerinfo = Minecraft.getMinecraft().getConnection().getPlayerInfo(this.getGameProfile().getId()); return networkplayerinfo != null && networkplayerinfo.getGameType() == GameType.CREATIVE; } /** * Checks if this instance of AbstractClientPlayer has any associated player data. */ public boolean hasPlayerInfo() { return this.getPlayerInfo() != null; } @Nullable protected NetworkPlayerInfo getPlayerInfo() { if (this.playerInfo == null) { this.playerInfo = Minecraft.getMinecraft().getConnection().getPlayerInfo(this.getUniqueID()); } return this.playerInfo; } /** * Returns true if the player has an associated skin. */ public boolean hasSkin() { NetworkPlayerInfo networkplayerinfo = this.getPlayerInfo(); return networkplayerinfo != null && networkplayerinfo.hasLocationSkin(); } /** * Returns true if the player instance has an associated skin. */ public ResourceLocation getLocationSkin() { NetworkPlayerInfo networkplayerinfo = this.getPlayerInfo(); return networkplayerinfo == null ? DefaultPlayerSkin.getDefaultSkin(this.getUniqueID()) : networkplayerinfo.getLocationSkin(); } @Nullable public ResourceLocation getLocationCape() { NetworkPlayerInfo networkplayerinfo = this.getPlayerInfo(); return networkplayerinfo == null ? null : networkplayerinfo.getLocationCape(); } public boolean isPlayerInfoSet() { return this.getPlayerInfo() != null; } /** * Gets the special Elytra texture for the player. */ @Nullable public ResourceLocation getLocationElytra() { NetworkPlayerInfo networkplayerinfo = this.getPlayerInfo(); return networkplayerinfo == null ? null : networkplayerinfo.getLocationElytra(); } public static ThreadDownloadImageData getDownloadImageSkin(ResourceLocation resourceLocationIn, String username) { TextureManager texturemanager = Minecraft.getMinecraft().getTextureManager(); ITextureObject itextureobject = texturemanager.getTexture(resourceLocationIn); if (itextureobject == null) { itextureobject = new ThreadDownloadImageData((File)null, String.format("http://skins.minecraft.net/MinecraftSkins/%s.png", StringUtils.stripControlCodes(username)), DefaultPlayerSkin.getDefaultSkin(getOfflineUUID(username)), new ImageBufferDownload()); texturemanager.loadTexture(resourceLocationIn, itextureobject); } return (ThreadDownloadImageData)itextureobject; } /** * Returns true if the username has an associated skin. */ public static ResourceLocation getLocationSkin(String username) { return new ResourceLocation("skins/" + StringUtils.stripControlCodes(username)); } public String getSkinType() { NetworkPlayerInfo networkplayerinfo = this.getPlayerInfo(); return networkplayerinfo == null ? DefaultPlayerSkin.getSkinType(this.getUniqueID()) : networkplayerinfo.getSkinType(); } public float getFovModifier() { float f = 1.0F; if (this.capabilities.isFlying) { f *= 1.1F; } IAttributeInstance iattributeinstance = this.getEntityAttribute(SharedMonsterAttributes.MOVEMENT_SPEED); f = (float)((double)f * ((iattributeinstance.getAttributeValue() / (double)this.capabilities.getWalkSpeed() + 1.0D) / 2.0D)); if (this.capabilities.getWalkSpeed() == 0.0F || Float.isNaN(f) || Float.isInfinite(f)) { f = 1.0F; } if (this.isHandActive() && this.getActiveItemStack().getItem() == Items.BOW) { int i = this.getItemInUseMaxCount(); float f1 = (float)i / 20.0F; if (f1 > 1.0F) { f1 = 1.0F; } else { f1 = f1 * f1; } f *= 1.0F - f1 * 0.15F; } return net.minecraftforge.client.ForgeHooksClient.getOffsetFOV(this, f); } }
gpl-3.0
YcheLanguageStudio/JavaRelatedStudy
SoftwareAnalysis/Assignments/Assign2Subject/src/test/java/janala/GetNextPermNumTestCase2.java
616
package janala; import org.junit.Test; import static org.junit.Assert.assertArrayEquals; /** * Created by cheyulin on 11/29/16. */ public class GetNextPermNumTestCase2 { private static util.IntArrayUtil jarUtil = new util.IntArrayUtil(); private static tests.homework.IntArrayUtil srcUtil = new tests.homework.IntArrayUtil(); @Test public void testGetNextPermNum() throws Exception { int[] arr0 = {1, 1, 1}; int[] arr1 = {1, 1, 1}; jarUtil.getNextPermutationNumber(arr0); srcUtil.getNextPermutationNumber(arr1); assertArrayEquals(arr0, arr1); } }
gpl-3.0
kingtang/spring-learn
spring-web/src/main/java/org/springframework/http/client/package-info.java
254
/** * * Contains an abstraction over client-side HTTP. This package * contains the {@code ClientHttpRequest} and * {@code ClientHttpResponse}, as well as a basic implementation of these * interfaces. * */ package org.springframework.http.client;
gpl-3.0
cbaakman/Tropicraft
src/main/java/net/tropicraft/item/ItemPineapple.java
4886
package net.tropicraft.item; import java.util.ArrayList; import java.util.List; import net.minecraft.block.Block; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; import net.minecraft.world.World; import net.tropicraft.block.BlockPineapple; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; public class ItemPineapple extends ItemTallFlowers { @SideOnly(Side.CLIENT) private IIcon[] icons; public ItemPineapple(Block block, ArrayList<String> names) { super(block, names); } /** * Register all icons here * @param iconRegister Icon registry */ @Override @SideOnly(Side.CLIENT) public void registerIcons(IIconRegister iconRegister) { icons = new IIcon[names.length]; for (int i = 0 ; i < names.length ; i++) { icons[i] = iconRegister.registerIcon(this.getUnlocalizedName().substring(this.getUnlocalizedName().indexOf(".") + 1) + "Item_" + names[i]); } } /** * Gets an icon index based on an item's damage value */ @Override @SideOnly(Side.CLIENT) public IIcon getIconFromDamage(int damage) { return block.getIcon(0, BlockPineapple.TOTAL_GROW_TICKS + 1); } /** * Called to actually place the block, after the location is determined * and all permission checks have been made. * * @param stack The item stack that was used to place the block. This can be changed inside the method. * @param player The player who is placing the block. Can be null if the block is not being placed by a player. * @param side The side the player (or machine) right-clicked on. */ @Override public boolean placeBlockAt(ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ, int metadata) { if (!world.setBlock(x, y, z, block, 0, 3)) { return false; } if (world.getBlock(x, y, z) == block) { block.onBlockPlacedBy(world, x, y, z, player, stack); block.onPostBlockPlaced(world, x, y, z, metadata); } return true; } /** * Returns the metadata of the block which this Item (ItemBlock) can place */ public int getMetadata(int par1) { return par1; } /** * returns a list of items with the same ID, but different meta (eg: wood returns 4 blocks) */ @SuppressWarnings({ "rawtypes", "unchecked" }) @Override @SideOnly(Side.CLIENT) public void getSubItems(Item item, CreativeTabs tab, List list) { for (int i = 0; i < this.icons.length; ++i) { list.add(new ItemStack(item, 1, i + 1)); } } /** * Callback for item usage. If the item does something special on right clicking, he will have one of those. Return * True if something happen and false if it don't. This is for ITEMS, not BLOCKS */ public boolean onItemUse(ItemStack itemstack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ) { Block block = world.getBlock(x, y, z); if (block == Blocks.snow_layer && (world.getBlockMetadata(x, y, z) & 7) < 1) { side = 1; } else if (block != Blocks.vine && block != Blocks.tallgrass && block != Blocks.deadbush && !block.isReplaceable(world, x, y, z)) { if (side == 0) { --y; } if (side == 1) { ++y; } if (side == 2) { --z; } if (side == 3) { ++z; } if (side == 4) { --x; } if (side == 5) { ++x; } } if (itemstack.stackSize == 0) { return false; } else if (!player.canPlayerEdit(x, y, z, side, itemstack)) { return false; } else if (y == 255 && this.block.getMaterial().isSolid()) { return false; } else if (world.canPlaceEntityOnSide(this.block, x, y, z, false, side, player, itemstack)) { int meta = this.block.onBlockPlaced(world, x, y, z, side, hitX, hitY, hitZ, 0); if (placeBlockAt(itemstack, player, world, x, y, z, side, hitX, hitY, hitZ, meta)) { world.playSoundEffect((double)((float)x + 0.5F), (double)((float)y + 0.5F), (double)((float)z + 0.5F), this.block.stepSound.func_150496_b(), (this.block.stepSound.getVolume() + 1.0F) / 2.0F, this.block.stepSound.getPitch() * 0.8F); --itemstack.stackSize; } return true; } else { return false; } } }
mpl-2.0
SmartInfrastructures/xipi
portlets/InfrastructurePortlet.old/docroot/WEB-INF/src/com/liferay/infinity/infrastucture/struts/action/SearchAction.java
2459
package com.liferay.infinity.infrastucture.struts.action; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.infinity.util.InfrastructureUtil; import org.infinity.util.SqlKeyWordDefine; import com.liferay.infinity.infrastucture.struts.form.SearchForm; import com.liferay.infinity.infrastucture.struts.form.ViewForm; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.util.Util; public class SearchAction extends Action { public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { SearchForm sForm = (SearchForm)form; //System.out.println("MMMMMM"+nestedForm.getIdIfradesc()); List list=new ArrayList(); if (sForm.getSearchString()!=null && sForm.getSearchString().trim()!=""){ //System.out.println("AAAA"+sForm.getSearchString()); list=InfrastructureUtil.getInfrastructuresSummaryByName(SqlKeyWordDefine.STATE_PUBLISH,sForm.getSearchString().trim()); if(Util.checkIfUserIsAdmin(request.getRemoteUser())){ list.addAll(InfrastructureUtil.getInfrastructuresSummaryByName(SqlKeyWordDefine.STATE_DRAFT_COMPLETE,sForm.getSearchString())); list.addAll(InfrastructureUtil.getInfrastructuresSummaryByName(SqlKeyWordDefine.STATE_NOT_PUBLISH,sForm.getSearchString())); } }else{ list=InfrastructureUtil.getInfrastructuresSummary(SqlKeyWordDefine.STATE_PUBLISH); if(Util.checkIfUserIsAdmin(request.getRemoteUser())){ list.addAll(InfrastructureUtil.getInfrastructuresSummary(SqlKeyWordDefine.STATE_DRAFT_COMPLETE)); list.addAll(InfrastructureUtil.getInfrastructuresSummary(SqlKeyWordDefine.STATE_NOT_PUBLISH)); } } ViewForm nestedForm= new ViewForm(); nestedForm.setInfrastructureSummaryList(list); sForm.setSearchString(""); request.getSession().setAttribute("viewForm", nestedForm); return mapping.findForward("portlet.infrastructure.find"); //return mapping.findForward("portlet.infrastructure.nested"); //return mapping.findForward("/sample_struts_portlet/nested_success"); } private static Log _log = LogFactoryUtil.getLog(SearchAction.class); }
agpl-3.0
aihua/opennms
features/minion/shell/poller/src/main/java/org/opennms/features/minion/shell/poller/ListMonitors.java
1962
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2016 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2016 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * OpenNMS(R) is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <license@opennms.org> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.features.minion.shell.poller; import org.apache.karaf.shell.api.action.Action; import org.apache.karaf.shell.api.action.Command; import org.apache.karaf.shell.api.action.lifecycle.Reference; import org.apache.karaf.shell.api.action.lifecycle.Service; import org.opennms.netmgt.poller.ServiceMonitorRegistry; @Command(scope = "poller", name = "list-monitors", description = "Lists all of the available monitors.") @Service public class ListMonitors implements Action { @Reference ServiceMonitorRegistry registry; @Override public Object execute() throws Exception { registry.getMonitorClassNames().stream().forEachOrdered(e -> { System.out.printf("%s\n", e); }); return null; } }
agpl-3.0
klebergraciasoares/ireport-fork
ireport-designer/src/com/jaspersoft/ireport/designer/actions/OpenSubreportAction.java
9827
/* * iReport - Visual Designer for JasperReports. * Copyright (C) 2002 - 2013 Jaspersoft Corporation. All rights reserved. * http://www.jaspersoft.com * * Unless you have purchased a commercial license agreement from Jaspersoft, * the following license terms apply: * * This program is part of iReport. * * iReport is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * iReport is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with iReport. If not, see <http://www.gnu.org/licenses/>. */ package com.jaspersoft.ireport.designer.actions; import com.jaspersoft.ireport.designer.IReportManager; import com.jaspersoft.ireport.designer.JrxmlEditorSupport; import com.jaspersoft.ireport.designer.SubreportOpenerProvider; import com.jaspersoft.ireport.designer.outline.nodes.ElementNode; import com.jaspersoft.ireport.designer.utils.Misc; import java.io.File; import java.util.Collection; import java.util.Iterator; import javax.swing.JOptionPane; import net.sf.jasperreports.engine.design.JRDesignExpression; import net.sf.jasperreports.engine.design.JRDesignSubreport; import net.sf.jasperreports.engine.design.JasperDesign; import org.openide.cookies.OpenCookie; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileUtil; import org.openide.loaders.DataObject; import org.openide.util.HelpCtx; import org.openide.util.Lookup; import org.openide.util.actions.NodeAction; import org.openide.util.lookup.Lookups; /** * * @author gtoffoli */ public final class OpenSubreportAction extends NodeAction { public String getName() { return "Open Subreport"; } @Override protected void initialize() { super.initialize(); // see org.openide.util.actions.SystemAction.iconResource() javadoc for more details putValue("noIconInMenu", Boolean.TRUE); } public HelpCtx getHelpCtx() { return HelpCtx.DEFAULT_HELP; } @Override protected boolean asynchronous() { return false; } protected void subreportNotFound(String msg) { // Display a message here... JOptionPane.showMessageDialog(Misc.getMainFrame(), "Unable to open the subreport:\n"+msg); } protected void performAction(org.openide.nodes.Node[] activatedNodes) { JasperDesign jasperDesign = ((ElementNode)activatedNodes[0]).getJasperDesign(); JRDesignSubreport subreport = (JRDesignSubreport)((ElementNode)activatedNodes[0]).getElement(); // Find the jrxml pointed by this subreport expression... // if (subreport.getExpression() == null || // subreport.getExpression().getValueClassName() == null || // !subreport.getExpression().getValueClassName().equals("java.lang.String")) // { // // Return default image... // // Unable to resolve the subreoport jrxml file... // subreportNotFound("The subreport expression is empty or it is not of type String."); // return; // } // // JRDesignDataset dataset = jasperDesign.getMainDesignDataset(); // ClassLoader classLoader = IReportManager.getReportClassLoader(); // // File fileToOpen = null; // JrxmlEditorSupport es = IReportManager.getInstance().getActiveVisualView().getEditorSupport(); // // // String error = null; // try { // // // Try to process the expression... // ExpressionInterpreter interpreter = new ExpressionInterpreter(dataset, classLoader); // interpreter.setConvertNullParams(true); // // Object ret = interpreter.interpretExpression( subreport.getExpression().getText() ); // // if (ret != null) // { // String resourceName = ret + ""; // if (resourceName.toLowerCase().endsWith(".jasper")) // { // resourceName = resourceName.substring(0, resourceName.length() - ".jasper".length()); // resourceName += ".jrxml"; // } // // if (!resourceName.toLowerCase().endsWith(".jrxml")) // { // throw new Exception("Unable to resolve the jrxml file for this subreport expression"); // } // // File f = new File(resourceName); // if (!f.exists()) // { // String jrxmlFileName = f.getName(); // File reportFolder = null; // JrxmlVisualView visualView = IReportManager.getInstance().getActiveVisualView(); // if (visualView != null) // { // File file = FileUtil.toFile(visualView.getEditorSupport().getDataObject().getPrimaryFile()); // if (file.getParentFile() != null) // { // reportFolder = file.getParentFile(); // } // } // // URL[] urls = new URL[]{}; // if (reportFolder != null) // { // urls = new URL[]{ reportFolder.toURI().toURL()}; // } // IRURLClassLoader urlClassLoader = new IRURLClassLoader(urls, classLoader); // // URL url = urlClassLoader.getResource(resourceName); // if (url == null) // { // // try just the file name... // url = urlClassLoader.getResource(jrxmlFileName); // // if (url == null) // { // throw new Exception(resourceName + " not found."); // } // } // // f = new File(url.toURI().getPath()); // if (f.exists()) // { // fileToOpen = f; // } // else // { // throw new Exception(f + " not found."); // } // } // else // { // fileToOpen = f; // } // // } // else // { // throw new Exception(); // } // } catch (Throwable ex) { // // fileToOpen = null; // error = ex.getMessage(); // ex.printStackTrace(); // } // // // fileToOpen = notifySubreportProviders(es, subreport, fileToOpen); // // if (fileToOpen != null) // { // try { // openFile(fileToOpen); // } catch (Throwable ex) { // error = ex.getMessage(); // subreportNotFound(error); // ex.printStackTrace(); // } // } // else // { // if (error == null) // { // error = "The subreport expression returned null. I'm unable to locate the subreport jrxml :-("; // } // subreportNotFound(error); // } try { JrxmlEditorSupport es = IReportManager.getInstance().getActiveVisualView().getEditorSupport(); File fileToOpen = Misc.locateFileFromExpression(jasperDesign, null, (JRDesignExpression) subreport.getExpression(), null, ".jrxml", null); fileToOpen = notifySubreportProviders(es, subreport, fileToOpen); openFile(fileToOpen); } catch (Exception ex) { subreportNotFound(ex.getMessage()); } } protected File notifySubreportProviders(JrxmlEditorSupport ed, JRDesignSubreport subreportElement, File file) { Lookup lookup = Lookups.forPath("ireport/SubreportOpenerProviders"); // NOI18N Collection<? extends SubreportOpenerProvider> subreportProviders = lookup.lookupAll(SubreportOpenerProvider.class); Iterator<? extends SubreportOpenerProvider> it = subreportProviders.iterator(); while (it.hasNext ()) { SubreportOpenerProvider subreportOpenerProvider = it.next(); try { File f = subreportOpenerProvider.openingSubreport(ed, subreportElement, file); if (f!=null) { file = f; } } catch (Throwable t) { t.printStackTrace(); } } return file; } protected boolean enable(org.openide.nodes.Node[] activatedNodes) { if (activatedNodes == null || activatedNodes.length != 1) return false; // Check we have selected a subreport if (activatedNodes[0] instanceof ElementNode && ((ElementNode)activatedNodes[0]).getElement() instanceof JRDesignSubreport) { return true; } return false; } private void openFile(File f) throws Exception { DataObject obj; f = FileUtil.normalizeFile(f); FileObject fl = FileUtil.toFileObject(f); if (fl == null) throw new Exception("Unable to open the file " + f); obj = DataObject.find(fl); OpenCookie ocookie = obj.getCookie(OpenCookie.class); if (ocookie != null) { ocookie.open(); } } }
agpl-3.0
zheguang/BerkeleyDB
lang/java/src/com/sleepycat/collections/StoredSortedMap.java
12683
/*- * See the file LICENSE for redistribution information. * * Copyright (c) 2000, 2014 Oracle and/or its affiliates. All rights reserved. * */ package com.sleepycat.collections; import java.util.Comparator; import java.util.SortedMap; import com.sleepycat.bind.EntityBinding; import com.sleepycat.bind.EntryBinding; import com.sleepycat.db.Database; import com.sleepycat.db.OperationStatus; import com.sleepycat.util.RuntimeExceptionWrapper; /** * A SortedMap view of a {@link Database}. * * <p>In addition to the standard SortedMap methods, this class provides the * following methods for stored sorted maps only. Note that the use of these * methods is not compatible with the standard Java collections interface.</p> * <ul> * <li>{@link #headMap(Object, boolean)}</li> * <li>{@link #tailMap(Object, boolean)}</li> * <li>{@link #subMap(Object, boolean, Object, boolean)}</li> * </ul> * * @author Mark Hayes */ public class StoredSortedMap<K, V> extends StoredMap<K, V> implements SortedMap<K, V> { /** * Creates a sorted map view of a {@link Database}. * * @param database is the Database underlying the new collection. * * @param keyBinding is the binding used to translate between key buffers * and key objects. * * @param valueBinding is the binding used to translate between value * buffers and value objects. * * @param writeAllowed is true to create a read-write collection or false * to create a read-only collection. * * @throws IllegalArgumentException if formats are not consistently * defined or a parameter is invalid. * * @throws RuntimeExceptionWrapper if a checked exception is thrown, * including a {@code DatabaseException} on BDB (C edition). */ public StoredSortedMap(Database database, EntryBinding<K> keyBinding, EntryBinding<V> valueBinding, boolean writeAllowed) { super(new DataView(database, keyBinding, valueBinding, null, writeAllowed, null)); } /** * Creates a sorted map view of a {@link Database} with a {@link * PrimaryKeyAssigner}. Writing is allowed for the created map. * * @param database is the Database underlying the new collection. * * @param keyBinding is the binding used to translate between key buffers * and key objects. * * @param valueBinding is the binding used to translate between value * buffers and value objects. * * @param keyAssigner is used by the {@link #append} method to assign * primary keys. * * @throws IllegalArgumentException if formats are not consistently * defined or a parameter is invalid. * * @throws RuntimeExceptionWrapper if a checked exception is thrown, * including a {@code DatabaseException} on BDB (C edition). */ public StoredSortedMap(Database database, EntryBinding<K> keyBinding, EntryBinding<V> valueBinding, PrimaryKeyAssigner keyAssigner) { super(new DataView(database, keyBinding, valueBinding, null, true, keyAssigner)); } /** * Creates a sorted map entity view of a {@link Database}. * * @param database is the Database underlying the new collection. * * @param keyBinding is the binding used to translate between key buffers * and key objects. * * @param valueEntityBinding is the binding used to translate between * key/value buffers and entity value objects. * * @param writeAllowed is true to create a read-write collection or false * to create a read-only collection. * * @throws IllegalArgumentException if formats are not consistently * defined or a parameter is invalid. * * @throws RuntimeExceptionWrapper if a checked exception is thrown, * including a {@code DatabaseException} on BDB (C edition). */ public StoredSortedMap(Database database, EntryBinding<K> keyBinding, EntityBinding<V> valueEntityBinding, boolean writeAllowed) { super(new DataView(database, keyBinding, null, valueEntityBinding, writeAllowed, null)); } /** * Creates a sorted map entity view of a {@link Database} with a {@link * PrimaryKeyAssigner}. Writing is allowed for the created map. * * @param database is the Database underlying the new collection. * * @param keyBinding is the binding used to translate between key buffers * and key objects. * * @param valueEntityBinding is the binding used to translate between * key/value buffers and entity value objects. * * @param keyAssigner is used by the {@link #append} method to assign * primary keys. * * @throws IllegalArgumentException if formats are not consistently * defined or a parameter is invalid. * * @throws RuntimeExceptionWrapper if a checked exception is thrown, * including a {@code DatabaseException} on BDB (C edition). */ public StoredSortedMap(Database database, EntryBinding<K> keyBinding, EntityBinding<V> valueEntityBinding, PrimaryKeyAssigner keyAssigner) { super(new DataView(database, keyBinding, null, valueEntityBinding, true, keyAssigner)); } StoredSortedMap(DataView mapView) { super(mapView); } /** * Returns null since comparators are not supported. The natural ordering * of a stored collection is data byte order, whether the data classes * implement the {@link java.lang.Comparable} interface or not. * This method does not conform to the {@link SortedMap#comparator} * interface. * * @return null. */ public Comparator<? super K> comparator() { return null; } /** * Returns the first (lowest) key currently in this sorted map. * This method conforms to the {@link SortedMap#firstKey} interface. * * @return the first key. * * * @throws RuntimeExceptionWrapper if a checked exception is thrown, * including a {@code DatabaseException} on BDB (C edition). */ public K firstKey() { return getFirstOrLastKey(true); } /** * Returns the last (highest) element currently in this sorted map. * This method conforms to the {@link SortedMap#lastKey} interface. * * @return the last key. * * * @throws RuntimeExceptionWrapper if a checked exception is thrown, * including a {@code DatabaseException} on BDB (C edition). */ public K lastKey() { return getFirstOrLastKey(false); } private K getFirstOrLastKey(boolean doGetFirst) { DataCursor cursor = null; try { cursor = new DataCursor(view, false); OperationStatus status; if (doGetFirst) { status = cursor.getFirst(false); } else { status = cursor.getLast(false); } return (K) ((status == OperationStatus.SUCCESS) ? cursor.getCurrentKey() : null); } catch (Exception e) { throw StoredContainer.convertException(e); } finally { closeCursor(cursor); } } /** * Returns a view of the portion of this sorted set whose keys are * strictly less than toKey. * This method conforms to the {@link SortedMap#headMap} interface. * * <p>Note that the return value is a StoredStoredMap and must be treated * as such; for example, its iterators must be explicitly closed.</p> * * @param toKey is the upper bound. * * @return the submap. * * @throws RuntimeExceptionWrapper if a checked exception is thrown, * including a {@code DatabaseException} on BDB (C edition). */ public SortedMap<K, V> headMap(K toKey) { return subMap(null, false, toKey, false); } /** * Returns a view of the portion of this sorted map whose elements are * strictly less than toKey, optionally including toKey. * This method does not exist in the standard {@link SortedMap} interface. * * <p>Note that the return value is a StoredStoredMap and must be treated * as such; for example, its iterators must be explicitly closed.</p> * * @param toKey is the upper bound. * * @param toInclusive is true to include toKey. * * @return the submap. * * @throws RuntimeExceptionWrapper if a checked exception is thrown, * including a {@code DatabaseException} on BDB (C edition). */ public SortedMap<K, V> headMap(K toKey, boolean toInclusive) { return subMap(null, false, toKey, toInclusive); } /** * Returns a view of the portion of this sorted map whose elements are * greater than or equal to fromKey. * This method conforms to the {@link SortedMap#tailMap} interface. * * <p>Note that the return value is a StoredStoredMap and must be treated * as such; for example, its iterators must be explicitly closed.</p> * * @param fromKey is the lower bound. * * @return the submap. * * @throws RuntimeExceptionWrapper if a checked exception is thrown, * including a {@code DatabaseException} on BDB (C edition). */ public SortedMap<K, V> tailMap(K fromKey) { return subMap(fromKey, true, null, false); } /** * Returns a view of the portion of this sorted map whose elements are * strictly greater than fromKey, optionally including fromKey. * This method does not exist in the standard {@link SortedMap} interface. * * <p>Note that the return value is a StoredStoredMap and must be treated * as such; for example, its iterators must be explicitly closed.</p> * * @param fromKey is the lower bound. * * @param fromInclusive is true to include fromKey. * * @return the submap. * * @throws RuntimeExceptionWrapper if a checked exception is thrown, * including a {@code DatabaseException} on BDB (C edition). */ public SortedMap<K, V> tailMap(K fromKey, boolean fromInclusive) { return subMap(fromKey, fromInclusive, null, false); } /** * Returns a view of the portion of this sorted map whose elements range * from fromKey, inclusive, to toKey, exclusive. * This method conforms to the {@link SortedMap#subMap} interface. * * <p>Note that the return value is a StoredStoredMap and must be treated * as such; for example, its iterators must be explicitly closed.</p> * * @param fromKey is the lower bound. * * @param toKey is the upper bound. * * @return the submap. * * @throws RuntimeExceptionWrapper if a checked exception is thrown, * including a {@code DatabaseException} on BDB (C edition). */ public SortedMap<K, V> subMap(K fromKey, K toKey) { return subMap(fromKey, true, toKey, false); } /** * Returns a view of the portion of this sorted map whose elements are * strictly greater than fromKey and strictly less than toKey, * optionally including fromKey and toKey. * This method does not exist in the standard {@link SortedMap} interface. * * <p>Note that the return value is a StoredStoredMap and must be treated * as such; for example, its iterators must be explicitly closed.</p> * * @param fromKey is the lower bound. * * @param fromInclusive is true to include fromKey. * * @param toKey is the upper bound. * * @param toInclusive is true to include toKey. * * @return the submap. * * @throws RuntimeExceptionWrapper if a checked exception is thrown, * including a {@code DatabaseException} on BDB (C edition). */ public SortedMap<K, V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { try { return new StoredSortedMap( view.subView(fromKey, fromInclusive, toKey, toInclusive, null)); } catch (Exception e) { throw StoredContainer.convertException(e); } } }
agpl-3.0
monjovi/java_jail
cp/traceprinter/VMCommander.java
5934
/***************************************************************************** traceprinter: a Java package to print traces of Java programs David Pritchard (daveagp@gmail.com), created May 2013 The contents of this directory are released under the GNU Affero General Public License, versions 3 or later. See LICENSE or visit: http://www.gnu.org/licenses/agpl.html See README for documentation on this package. ******************************************************************************/ package traceprinter; import com.sun.jdi.*; import java.util.*; public class VMCommander extends Thread { private InMemory im; private ThreadReference tr; private VirtualMachine vm; private Map<String, byte[]> classesToLoad; private String mainClassName; private ClassType ClassLoader_; private ObjectReference ClassLoader_SystemClassLoader; Boolean success; String errorMessage; public VMCommander(InMemory im, ThreadReference tr) { this.im = im; this.tr = tr; this.vm = im.vm; this.classesToLoad = im.bytecode; this.mainClassName = im.mainClass; } ObjectReference VMCommandee_instance = null; public void run() { try { vm.suspend(); // first, make instance of ByteClassLoader ClassLoader_ = classType("java.lang.ClassLoader"); ClassLoader_SystemClassLoader = (ObjectReference) call_s(ClassLoader_, "getSystemClassLoader"); ObjectReference ByteClassLoader_instance = instantiate("traceprinter.shoelace.ByteClassLoader"); // load the classes from their bytecodes for (Map.Entry<String, byte[]> me : classesToLoad.entrySet()) call_i(ByteClassLoader_instance, "define", vm.mirrorOf(me.getKey()), mirrorOf(vm, me.getValue())); // load and instantiate Commandee. very similar to above! VMCommandee_instance = instantiate("traceprinter.shoelace.VMCommandee"); ArrayReference mirrorOfArgs = newArray("java.lang.String", im.argsArray.size()); for (int i=0; i<im.argsArray.size(); i++) mirrorOfArgs.setValue(i, vm.mirrorOf(im.argsArray.getString(i))); StringReference result; try { result = (StringReference) call_i(VMCommandee_instance, "runMain", vm.mirrorOf(mainClassName), mirrorOfArgs, vm.mirrorOf(im.givenStdin)); } catch (VMDisconnectedException e) { // means we exceeded step limit success = true; // visualization is fine return; } /* // uncaught exception that originates in non-user code (e.g. scanner runs out) catch (InvocationException e) { System.out.println(e.toString()); return; } */ if (result == null) { success = true; } else { success = false; errorMessage = "Error: " + result.value(); } vm.resume(); } catch (Exception e) { e.printStackTrace(System.out); throw new RuntimeException(e.toString()); } } // utility methods // calls the default no-arg constructor private ObjectReference instantiate(String x) throws InvalidTypeException, ClassNotLoadedException, IncompatibleThreadStateException, InvocationException { ObjectReference Class_x = (ObjectReference) call_i(ClassLoader_SystemClassLoader, ClassLoader_, "loadClass", vm.mirrorOf(x)); ArrayReference ConstructorArray_x = (ArrayReference) call_i(Class_x, "getConstructors"); ObjectReference Constructor_x = (ObjectReference) ConstructorArray_x.getValue(0); ObjectReference x_instance = (ObjectReference) call_i(Constructor_x, "newInstance"); return x_instance; } // call instance method private Value call_i(ObjectReference o, String s, Value... v) throws InvalidTypeException, ClassNotLoadedException, IncompatibleThreadStateException, InvocationException { return call_i(o, (ClassType) o.referenceType(), s, v); } // call instance method w.r.t. specific class private Value call_i(ObjectReference o, ClassType t, String s, Value... v) throws InvalidTypeException, ClassNotLoadedException, IncompatibleThreadStateException, InvocationException { Method m = t.methodsByName(s).get(0); return o.invokeMethod(tr, m, lv(v), 0); } // call static method private Value call_s(ClassType t, String s, Value... v) throws InvalidTypeException, ClassNotLoadedException, IncompatibleThreadStateException, InvocationException { Method m = t.methodsByName(s).get(0); return t.invokeMethod(tr, m, lv(v), 0); } private ArrayReference newArray(String elementType, int length) { ArrayType at = (ArrayType) vm.classesByName(elementType+"[]").get(0); return at.newInstance(length); } private ClassType classType(String className) { return (ClassType) vm.classesByName(className).get(0); } private List<Value> lv(Value... vs) { return Arrays.asList(vs); } private ArrayReference mirrorOf(VirtualMachine vm, byte[] bytes) throws InvalidTypeException, ClassNotLoadedException { ArrayReference result = newArray("byte", bytes.length); for (int i=0; i < bytes.length; i++) result.setValue(i, vm.mirrorOf(bytes[i])); return result; } }
agpl-3.0
fionakim/biojava
biojava-core/src/main/java/org/biojava/nbio/core/sequence/compound/AmbiguityDNACompoundSet.java
1780
/* * BioJava development code * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. If you do not have a copy, * see: * * http://www.gnu.org/copyleft/lesser.html * * Copyright for this code is held jointly by the individual * authors. These should be listed in @author doc comments. * * For more information on the BioJava project and its aims, * or to join the biojava-l mailing list, visit the home page * at: * * http://www.biojava.org/ * */ package org.biojava.nbio.core.sequence.compound; /** * * @author Andy Yates */ public class AmbiguityDNACompoundSet extends DNACompoundSet { private static class InitaliseOnDemand { public static final AmbiguityDNACompoundSet INSTANCE = new AmbiguityDNACompoundSet(); } public static AmbiguityDNACompoundSet getDNACompoundSet() { return InitaliseOnDemand.INSTANCE; } public AmbiguityDNACompoundSet() { super(); addNucleotideCompound("M", "K", "A", "C"); addNucleotideCompound("R", "Y", "A", "G"); addNucleotideCompound("W", "W", "A", "T"); addNucleotideCompound("S", "S", "C", "G"); addNucleotideCompound("Y", "R", "C", "T"); addNucleotideCompound("K", "M", "G", "T"); addNucleotideCompound("V", "B", "A", "C", "G"); addNucleotideCompound("H", "D", "A", "C", "T"); addNucleotideCompound("D", "H", "A", "G", "T"); addNucleotideCompound("B", "V", "C", "G", "T"); addNucleotideCompound("N", "N", "A", "C", "G", "T"); addNucleotideCompound("I", "I", "N", "A", "C", "G", "T"); calculateIndirectAmbiguities(); } }
lgpl-2.1
xasx/wildfly
testsuite/integration/clustering/src/test/java/org/jboss/as/test/clustering/cluster/web/expiration/SessionExpirationTestCase.java
29890
/* * JBoss, Home of Professional Open Source. * Copyright 2013, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.clustering.cluster.web.expiration; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; import javax.servlet.http.HttpServletResponse; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.utils.HttpClientUtils; import org.apache.http.impl.client.CloseableHttpClient; import org.jboss.arquillian.container.test.api.OperateOnDeployment; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.test.clustering.cluster.AbstractClusteringTestCase; import org.jboss.as.test.clustering.cluster.web.DistributableTestCase; import org.jboss.as.test.http.util.TestHttpClientUtils; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.Test; /** * Validates get/set/remove/invalidate session operations, session expiration, and their corresponding events * * @author Paul Ferraro */ public abstract class SessionExpirationTestCase extends AbstractClusteringTestCase { static WebArchive getBaseDeployment(String moduleName) { WebArchive war = ShrinkWrap.create(WebArchive.class, moduleName + ".war"); war.addClasses(SessionOperationServlet.class, RecordingWebListener.class); // Take web.xml from the managed test. war.setWebXML(DistributableTestCase.class.getPackage(), "web.xml"); return war; } @Test public void test(@ArquillianResource(SessionOperationServlet.class) @OperateOnDeployment(DEPLOYMENT_1) URL baseURL1, @ArquillianResource(SessionOperationServlet.class) @OperateOnDeployment(DEPLOYMENT_2) URL baseURL2) throws IOException, URISyntaxException, InterruptedException { try (CloseableHttpClient client = TestHttpClientUtils.promiscuousCookieHttpClient()) { // This should trigger session creation event, but not added attribute event HttpResponse response = client.execute(new HttpGet(SessionOperationServlet.createSetURI(baseURL1, "a"))); try { Assert.assertTrue(response.containsHeader(SessionOperationServlet.CREATED_SESSIONS)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.DESTROYED_SESSIONS)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.ADDED_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.REPLACED_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.REMOVED_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.BOUND_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.UNBOUND_ATTRIBUTES)); Assert.assertEquals(response.getFirstHeader(SessionOperationServlet.SESSION_ID).getValue(), response.getFirstHeader(SessionOperationServlet.CREATED_SESSIONS).getValue()); } finally { HttpClientUtils.closeQuietly(response); } // This should trigger attribute added event and bound binding event response = client.execute(new HttpGet(SessionOperationServlet.createSetURI(baseURL1, "a", "1"))); try { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertTrue(response.containsHeader(SessionOperationServlet.SESSION_ID)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.CREATED_SESSIONS)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.DESTROYED_SESSIONS)); Assert.assertTrue(response.containsHeader(SessionOperationServlet.ADDED_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.REPLACED_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.REMOVED_ATTRIBUTES)); Assert.assertTrue(response.containsHeader(SessionOperationServlet.BOUND_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.UNBOUND_ATTRIBUTES)); Assert.assertEquals("a", response.getFirstHeader(SessionOperationServlet.ADDED_ATTRIBUTES).getValue()); Assert.assertEquals("1", response.getFirstHeader(SessionOperationServlet.BOUND_ATTRIBUTES).getValue()); } finally { HttpClientUtils.closeQuietly(response); } // No events should have been triggered on remote node response = client.execute(new HttpGet(SessionOperationServlet.createGetURI(baseURL2, "a"))); try { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertTrue(response.containsHeader(SessionOperationServlet.RESULT)); Assert.assertEquals("1", response.getFirstHeader(SessionOperationServlet.RESULT).getValue()); Assert.assertFalse(response.containsHeader(SessionOperationServlet.CREATED_SESSIONS)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.DESTROYED_SESSIONS)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.ADDED_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.REPLACED_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.REMOVED_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.BOUND_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.UNBOUND_ATTRIBUTES)); } finally { HttpClientUtils.closeQuietly(response); } // Make sure remove attribute event is not fired since attribute does not exist response = client.execute(new HttpGet(SessionOperationServlet.createRemoveURI(baseURL2, "b"))); try { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertFalse(response.containsHeader(SessionOperationServlet.RESULT)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.CREATED_SESSIONS)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.DESTROYED_SESSIONS)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.ADDED_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.REPLACED_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.REMOVED_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.BOUND_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.UNBOUND_ATTRIBUTES)); } finally { HttpClientUtils.closeQuietly(response); } // This should trigger attribute replaced event, as well as valueBound/valueUnbound binding events response = client.execute(new HttpGet(SessionOperationServlet.createSetURI(baseURL1, "a", "2"))); try { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertFalse(response.containsHeader(SessionOperationServlet.CREATED_SESSIONS)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.DESTROYED_SESSIONS)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.ADDED_ATTRIBUTES)); Assert.assertTrue(response.containsHeader(SessionOperationServlet.REPLACED_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.REMOVED_ATTRIBUTES)); Assert.assertTrue(response.containsHeader(SessionOperationServlet.BOUND_ATTRIBUTES)); Assert.assertTrue(response.containsHeader(SessionOperationServlet.UNBOUND_ATTRIBUTES)); Assert.assertEquals("a", response.getFirstHeader(SessionOperationServlet.REPLACED_ATTRIBUTES).getValue()); Assert.assertEquals("2", response.getFirstHeader(SessionOperationServlet.BOUND_ATTRIBUTES).getValue()); Assert.assertEquals("1", response.getFirstHeader(SessionOperationServlet.UNBOUND_ATTRIBUTES).getValue()); } finally { HttpClientUtils.closeQuietly(response); } // No events should have been triggered on remote node response = client.execute(new HttpGet(SessionOperationServlet.createGetURI(baseURL2, "a"))); try { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertTrue(response.containsHeader(SessionOperationServlet.RESULT)); Assert.assertEquals("2", response.getFirstHeader(SessionOperationServlet.RESULT).getValue()); Assert.assertFalse(response.containsHeader(SessionOperationServlet.CREATED_SESSIONS)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.DESTROYED_SESSIONS)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.ADDED_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.REPLACED_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.REMOVED_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.BOUND_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.UNBOUND_ATTRIBUTES)); } finally { HttpClientUtils.closeQuietly(response); } // This should trigger attribute removed event and valueUnbound binding event response = client.execute(new HttpGet(SessionOperationServlet.createSetURI(baseURL1, "a"))); try { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertFalse(response.containsHeader(SessionOperationServlet.CREATED_SESSIONS)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.DESTROYED_SESSIONS)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.ADDED_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.REPLACED_ATTRIBUTES)); Assert.assertTrue(response.containsHeader(SessionOperationServlet.REMOVED_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.BOUND_ATTRIBUTES)); Assert.assertTrue(response.containsHeader(SessionOperationServlet.UNBOUND_ATTRIBUTES)); Assert.assertEquals("a", response.getFirstHeader(SessionOperationServlet.REMOVED_ATTRIBUTES).getValue()); Assert.assertEquals("2", response.getFirstHeader(SessionOperationServlet.UNBOUND_ATTRIBUTES).getValue()); } finally { HttpClientUtils.closeQuietly(response); } // No events should have been triggered on remote node response = client.execute(new HttpGet(SessionOperationServlet.createGetURI(baseURL2, "a"))); try { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertFalse(response.containsHeader(SessionOperationServlet.RESULT)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.CREATED_SESSIONS)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.DESTROYED_SESSIONS)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.ADDED_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.REPLACED_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.REMOVED_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.BOUND_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.UNBOUND_ATTRIBUTES)); } finally { HttpClientUtils.closeQuietly(response); } // This should trigger attribute added event and valueBound binding event response = client.execute(new HttpGet(SessionOperationServlet.createSetURI(baseURL1, "a", "3", "4"))); try { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertFalse(response.containsHeader(SessionOperationServlet.CREATED_SESSIONS)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.DESTROYED_SESSIONS)); Assert.assertTrue(response.containsHeader(SessionOperationServlet.ADDED_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.REPLACED_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.REMOVED_ATTRIBUTES)); Assert.assertTrue(response.containsHeader(SessionOperationServlet.BOUND_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.UNBOUND_ATTRIBUTES)); Assert.assertEquals("a", response.getFirstHeader(SessionOperationServlet.ADDED_ATTRIBUTES).getValue()); Assert.assertEquals("3", response.getFirstHeader(SessionOperationServlet.BOUND_ATTRIBUTES).getValue()); } finally { HttpClientUtils.closeQuietly(response); } // No events should have been triggered on remote node response = client.execute(new HttpGet(SessionOperationServlet.createGetURI(baseURL2, "a"))); try { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertTrue(response.containsHeader(SessionOperationServlet.RESULT)); Assert.assertEquals("4", response.getFirstHeader(SessionOperationServlet.RESULT).getValue()); Assert.assertFalse(response.containsHeader(SessionOperationServlet.CREATED_SESSIONS)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.DESTROYED_SESSIONS)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.ADDED_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.REPLACED_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.REMOVED_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.BOUND_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.UNBOUND_ATTRIBUTES)); } finally { HttpClientUtils.closeQuietly(response); } // This should trigger attribute removed event and valueUnbound binding event response = client.execute(new HttpGet(SessionOperationServlet.createRemoveURI(baseURL1, "a"))); try { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertFalse(response.containsHeader(SessionOperationServlet.CREATED_SESSIONS)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.DESTROYED_SESSIONS)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.ADDED_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.REPLACED_ATTRIBUTES)); Assert.assertTrue(response.containsHeader(SessionOperationServlet.REMOVED_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.BOUND_ATTRIBUTES)); Assert.assertTrue(response.containsHeader(SessionOperationServlet.UNBOUND_ATTRIBUTES)); Assert.assertEquals("a", response.getFirstHeader(SessionOperationServlet.REMOVED_ATTRIBUTES).getValue()); Assert.assertEquals("4", response.getFirstHeader(SessionOperationServlet.UNBOUND_ATTRIBUTES).getValue()); } finally { HttpClientUtils.closeQuietly(response); } // No events should have been triggered on remote node response = client.execute(new HttpGet(SessionOperationServlet.createGetURI(baseURL2, "a"))); try { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertFalse(response.containsHeader(SessionOperationServlet.RESULT)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.CREATED_SESSIONS)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.DESTROYED_SESSIONS)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.ADDED_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.REPLACED_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.REMOVED_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.BOUND_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.UNBOUND_ATTRIBUTES)); } finally { HttpClientUtils.closeQuietly(response); } // This should trigger attribute added event and valueBound binding event response = client.execute(new HttpGet(SessionOperationServlet.createSetURI(baseURL2, "a", "5"))); try { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertTrue(response.containsHeader(SessionOperationServlet.SESSION_ID)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.CREATED_SESSIONS)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.DESTROYED_SESSIONS)); Assert.assertTrue(response.containsHeader(SessionOperationServlet.ADDED_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.REPLACED_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.REMOVED_ATTRIBUTES)); Assert.assertTrue(response.containsHeader(SessionOperationServlet.BOUND_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.UNBOUND_ATTRIBUTES)); Assert.assertEquals("a", response.getFirstHeader(SessionOperationServlet.ADDED_ATTRIBUTES).getValue()); Assert.assertEquals("5", response.getFirstHeader(SessionOperationServlet.BOUND_ATTRIBUTES).getValue()); } finally { HttpClientUtils.closeQuietly(response); } // This should trigger session destroyed event and valueUnbound binding event response = client.execute(new HttpGet(SessionOperationServlet.createInvalidateURI(baseURL1))); try { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertTrue(response.containsHeader(SessionOperationServlet.SESSION_ID)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.CREATED_SESSIONS)); Assert.assertTrue(response.containsHeader(SessionOperationServlet.DESTROYED_SESSIONS)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.ADDED_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.REPLACED_ATTRIBUTES)); Assert.assertTrue(response.containsHeader(SessionOperationServlet.REMOVED_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.BOUND_ATTRIBUTES)); Assert.assertTrue(response.containsHeader(SessionOperationServlet.UNBOUND_ATTRIBUTES)); Assert.assertEquals(response.getFirstHeader(SessionOperationServlet.SESSION_ID).getValue(), response.getFirstHeader(SessionOperationServlet.DESTROYED_SESSIONS).getValue()); Assert.assertEquals("a",response.getFirstHeader(SessionOperationServlet.REMOVED_ATTRIBUTES).getValue()); Assert.assertEquals("5", response.getFirstHeader(SessionOperationServlet.UNBOUND_ATTRIBUTES).getValue()); } finally { HttpClientUtils.closeQuietly(response); } // This should trigger attribute added event and valueBound binding event response = client.execute(new HttpGet(SessionOperationServlet.createSetURI(baseURL2, "a", "6"))); try { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertTrue(response.containsHeader(SessionOperationServlet.SESSION_ID)); Assert.assertTrue(response.containsHeader(SessionOperationServlet.CREATED_SESSIONS)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.DESTROYED_SESSIONS)); Assert.assertTrue(response.containsHeader(SessionOperationServlet.ADDED_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.REPLACED_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.REMOVED_ATTRIBUTES)); Assert.assertTrue(response.containsHeader(SessionOperationServlet.BOUND_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.UNBOUND_ATTRIBUTES)); Assert.assertEquals(response.getFirstHeader(SessionOperationServlet.SESSION_ID).getValue(), response.getFirstHeader(SessionOperationServlet.CREATED_SESSIONS).getValue()); Assert.assertEquals("a", response.getFirstHeader(SessionOperationServlet.ADDED_ATTRIBUTES).getValue()); Assert.assertEquals("6", response.getFirstHeader(SessionOperationServlet.BOUND_ATTRIBUTES).getValue()); } finally { HttpClientUtils.closeQuietly(response); } // This should not trigger any events response = client.execute(new HttpGet(SessionOperationServlet.createGetURI(baseURL2, "a", "7"))); try { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertTrue(response.containsHeader(SessionOperationServlet.RESULT)); Assert.assertEquals("6", response.getFirstHeader(SessionOperationServlet.RESULT).getValue()); Assert.assertTrue(response.containsHeader(SessionOperationServlet.SESSION_ID)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.CREATED_SESSIONS)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.DESTROYED_SESSIONS)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.ADDED_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.REPLACED_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.REMOVED_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.BOUND_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.UNBOUND_ATTRIBUTES)); } finally { HttpClientUtils.closeQuietly(response); } // This should not trigger any events response = client.execute(new HttpGet(SessionOperationServlet.createGetURI(baseURL2, "a"))); try { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertTrue(response.containsHeader(SessionOperationServlet.RESULT)); Assert.assertEquals("7", response.getFirstHeader(SessionOperationServlet.RESULT).getValue()); Assert.assertTrue(response.containsHeader(SessionOperationServlet.SESSION_ID)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.CREATED_SESSIONS)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.DESTROYED_SESSIONS)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.ADDED_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.REPLACED_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.REMOVED_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.BOUND_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.UNBOUND_ATTRIBUTES)); } finally { HttpClientUtils.closeQuietly(response); } // Trigger session timeout in 1 second response = client.execute(new HttpGet(SessionOperationServlet.createTimeoutURI(baseURL1, 1))); String sessionId = null; try { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertFalse(response.containsHeader(SessionOperationServlet.RESULT)); Assert.assertTrue(response.containsHeader(SessionOperationServlet.SESSION_ID)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.CREATED_SESSIONS)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.DESTROYED_SESSIONS)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.ADDED_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.REPLACED_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.REMOVED_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.BOUND_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.UNBOUND_ATTRIBUTES)); sessionId = response.getFirstHeader(SessionOperationServlet.SESSION_ID).getValue(); } finally { HttpClientUtils.closeQuietly(response); } // Trigger timeout of sessionId Thread.sleep(2000); // Timeout should trigger session destroyed event and valueUnbound binding event response = client.execute(new HttpGet(SessionOperationServlet.createGetURI(baseURL2, "a"))); try { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertFalse(response.containsHeader(SessionOperationServlet.RESULT)); Assert.assertTrue(response.containsHeader(SessionOperationServlet.SESSION_ID)); Assert.assertTrue(response.containsHeader(SessionOperationServlet.CREATED_SESSIONS)); Assert.assertTrue(response.containsHeader(SessionOperationServlet.DESTROYED_SESSIONS)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.ADDED_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.REPLACED_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.REMOVED_ATTRIBUTES)); Assert.assertFalse(response.containsHeader(SessionOperationServlet.BOUND_ATTRIBUTES)); Assert.assertTrue(response.containsHeader(SessionOperationServlet.UNBOUND_ATTRIBUTES)); Assert.assertEquals(sessionId, response.getFirstHeader(SessionOperationServlet.DESTROYED_SESSIONS).getValue()); Assert.assertEquals(response.getFirstHeader(SessionOperationServlet.SESSION_ID).getValue(), response.getFirstHeader(SessionOperationServlet.CREATED_SESSIONS).getValue()); Assert.assertEquals("7", response.getFirstHeader(SessionOperationServlet.UNBOUND_ATTRIBUTES).getValue()); } finally { HttpClientUtils.closeQuietly(response); } } } }
lgpl-2.1
microcosmx/jade
src/jade/core/ServiceManagerImpl.java
19191
/***************************************************************** JADE - Java Agent DEvelopment Framework is a framework to develop multi-agent systems in compliance with the FIPA specifications. Copyright (C) 2000 CSELT S.p.A. GNU Lesser General Public License This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, version 2.1 of the License. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *****************************************************************/ package jade.core; //#APIDOC_EXCLUDE_FILE import jade.mtp.TransportAddress; import jade.security.JADESecurityException; import jade.util.leap.Map; import jade.util.leap.HashMap; import jade.util.leap.Iterator; import jade.util.Logger; import java.util.Vector; /** The <code>ServiceManagerImpl</code> class is the actual implementation of JADE platform <i>Service Manager</i> and <i>Service Finder</i> components. It holds a set of services and manages them. @author Giovanni Rimassa - FRAMeTech s.r.l. @author Giovanni Caire - TILAB */ public class ServiceManagerImpl implements ServiceManager, ServiceFinder { private static final int IDLE_STATUS = 0; private static final int ACTIVE_STATUS = 1; private static final int TERMINATING_STATUS = 2; private IMTPManager myIMTPManager; private CommandProcessor myCommandProcessor; private PlatformManager myPlatformManager; private boolean invalidPlatformManager; private String platformName; private Node localNode; private NodeDescriptor localNodeDescriptor; private Map localServices; private Map backupManagers; private int status = IDLE_STATUS; private jade.util.Logger myLogger; /** Constructs a new Service Manager implementation complying with a given JADE profile. This constructor is package-scoped, so that only the JADE kernel is allowed to create a new Service Manager implementation. @param p The platform profile describing how the JADE platform is to be configured. */ ServiceManagerImpl(Profile p, PlatformManager pm) throws ProfileException { myCommandProcessor = p.getCommandProcessor(); myIMTPManager = p.getIMTPManager(); myPlatformManager = pm; invalidPlatformManager = false; localServices = new HashMap(5); backupManagers = new HashMap(1); myLogger = Logger.getMyLogger(getClass().getName()); } // Implementation of the ServiceManager interface public String getPlatformName() throws IMTPException { if (platformName == null) { try { platformName = myPlatformManager.getPlatformName(); } catch (IMTPException imtpe) { if (reconnect()) { platformName = myPlatformManager.getPlatformName(); } else { throw imtpe; } } } return platformName; } public synchronized void addAddress(String addr) throws IMTPException { myLogger.log(Logger.INFO, "Adding PlatformManager address " + addr); if (invalidPlatformManager || !compareTransportAddresses(addr, myPlatformManager.getLocalAddress())) { backupManagers.put(addr, myIMTPManager.getPlatformManagerProxy(addr)); if (invalidPlatformManager) { reconnect(); } } } public synchronized void removeAddress(String addr) throws IMTPException { myLogger.log(Logger.INFO, "Removing PlatformManager address " + addr); backupManagers.remove(addr); if (compareTransportAddresses(addr, myPlatformManager.getLocalAddress())) { reconnect(); } } private boolean compareAddresses(String addr1, String addr2) { //#MIDP_EXCLUDE_BEGIN try { TransportAddress ta1 = myIMTPManager.stringToAddr(addr1); TransportAddress ta2 = myIMTPManager.stringToAddr(addr2); if (CaseInsensitiveString.equalsIgnoreCase(ta1.getProto(), ta2.getProto())) { if (CaseInsensitiveString.equalsIgnoreCase(ta1.getPort(), ta2.getPort())) { if (Profile.compareHostNames(ta1.getHost(), ta2.getHost())) { return true; } } } return false; } catch (Exception e) { // If we can't parse the addresses, just compare them as strings return CaseInsensitiveString.equalsIgnoreCase(addr1, addr2); } //#MIDP_EXCLUDE_END /*#MIDP_INCLUDE_BEGIN return CaseInsensitiveString.equalsIgnoreCase(addr1, addr2); #MIDP_INCLUDE_END*/ } public String getLocalAddress() throws IMTPException { return myPlatformManager.getLocalAddress(); } public void addNode(NodeDescriptor desc, ServiceDescriptor[] services) throws IMTPException, ServiceException, JADESecurityException { localNodeDescriptor = desc; localNode = desc.getNode(); try { // Install all services locally and prepare the list of services to notify to the PlatformManager Vector ss = new Vector(services != null ? services.length : 0); if (services != null) { for (int i = 0; i < services.length; ++i) { ServiceDescriptor sd = services[i]; try { installServiceLocally(sd); if (!isLocal(sd.getService())) { ss.addElement(sd); } } catch (Exception e) { if (services[i].isMandatory()) { throw e; } else { myLogger.log(Logger.WARNING, "Exception installing service " + sd.getName(), e); } } } } // Notify the platform manager. Get back a valid name and assign // it to both the node, the node descriptor and the container (if any) String name = null; try { name = myPlatformManager.addNode(desc, ss, false); } catch (IMTPException imtpe) { if (reconnect()) { name = myPlatformManager.addNode(desc, ss, false); } else { throw imtpe; } } adjustName(name); status = ACTIVE_STATUS; } catch (IMTPException imtpe2) { throw imtpe2; } catch (ServiceException se) { throw se; } catch (JADESecurityException ae) { throw ae; } catch (Throwable t) { throw new ServiceException("Unexpected error activating node", t); } } public void removeNode(NodeDescriptor desc) throws IMTPException, ServiceException { // Do not notify the platform manager. The node termination will cause the deregistration... status = TERMINATING_STATUS; // Uninstall all services locally Object[] names = localServices.keySet().toArray(); for (int i = 0; i < names.length; i++) { try { String svcName = (String) names[i]; uninstallServiceLocally(svcName); } catch (IMTPException imtpe) { // This should never happen, because it's a local call... imtpe.printStackTrace(); } } //#MIDP_EXCLUDE_BEGIN // If this node was exporting a PlatformManager, unexport it if (desc.getNode().hasPlatformManager()) { myIMTPManager.unexportPlatformManager(myPlatformManager); } //#MIDP_EXCLUDE_END } public void activateService(ServiceDescriptor desc) throws IMTPException, ServiceException { try { // Install the service locally installServiceLocally(desc); if (!isLocal(desc.getService())) { // Notify the platform manager (add a slice for this service on this node) try { myPlatformManager.addSlice(desc, localNodeDescriptor, false); } catch (IMTPException imtpe) { if (reconnect()) { myPlatformManager.addSlice(desc, localNodeDescriptor, false); } else { throw imtpe; } } } } catch (IMTPException imtpe2) { // Undo the local service installation uninstallServiceLocally(desc.getName()); // Rethrow the exception throw imtpe2; } } private boolean isLocal(Service svc) { return (svc instanceof BaseService && ((BaseService) svc).isLocal()); } public void deactivateService(String name) throws IMTPException, ServiceException { ServiceDescriptor desc = (ServiceDescriptor) localServices.get(name); if (desc != null) { // Notify the platform manager (remove the slice for this service on this node) try { myPlatformManager.removeSlice(name, localNode.getName(), false); } catch (IMTPException imtpe) { if (reconnect()) { myPlatformManager.removeSlice(name, localNode.getName(), false); } else { throw imtpe; } } // Uninstall the service locally uninstallServiceLocally(name); } } ///////////////////////////////////////////////// // ServiceFinder interface ///////////////////////////////////////////////// public Service findService(String key) throws IMTPException, ServiceException { Service svc = null; ServiceDescriptor svcDsc = (ServiceDescriptor) localServices.get(key); if (svcDsc != null) { svc = svcDsc.getService(); } return svc; } public Service.Slice findSlice(String serviceKey, String sliceKey) throws IMTPException, ServiceException { Service.Slice slice = null; try { slice = myPlatformManager.findSlice(serviceKey, sliceKey); } catch (IMTPException imtpe) { if (reconnect()) { slice = myPlatformManager.findSlice(serviceKey, sliceKey); } else { throw imtpe; } } return bindToLocalNode(slice); } public Service.Slice[] findAllSlices(String serviceKey) throws IMTPException, ServiceException { Vector v = null; try { v = myPlatformManager.findAllSlices(serviceKey); } catch (IMTPException imtpe) { if (reconnect()) { v = myPlatformManager.findAllSlices(serviceKey); } else { throw imtpe; } } if (v == null) { return null; } else { Service.Slice[] ss = new Service.Slice[v.size()]; for (int i = 0; i < ss.length; ++i) { ss[i] = bindToLocalNode((Service.Slice) v.elementAt(i)); } return ss; } } ///////////////////////////////////////////////// // Other service installation related methods ///////////////////////////////////////////////// private void installServiceLocally(ServiceDescriptor svcDsc) throws IMTPException, ServiceException { Service svc = svcDsc.getService(); // Install the service filters Filter fOut = svc.getCommandFilter(Filter.OUTGOING); if (fOut != null) { fOut.setServiceName(svc.getName()); myCommandProcessor.addFilter(fOut, Filter.OUTGOING); } Filter fIn = svc.getCommandFilter(Filter.INCOMING); if (fIn != null) { if (fIn == fOut) { // NOTE that fOut is certainly != null myCommandProcessor.removeFilter(fOut, Filter.OUTGOING); throw new ServiceException("The same filter object cannot be used as both incoming and outgoing filter."); } fIn.setServiceName(svc.getName()); myCommandProcessor.addFilter(fIn, Filter.INCOMING); } // Install the service sinks Sink sSrc = svc.getCommandSink(Sink.COMMAND_SOURCE); if (sSrc != null) { myCommandProcessor.registerSink(sSrc, Sink.COMMAND_SOURCE, svc.getName()); } Sink sTgt = svc.getCommandSink(Sink.COMMAND_TARGET); if (sTgt != null) { myCommandProcessor.registerSink(sTgt, Sink.COMMAND_TARGET, svc.getName()); } // Export the local slice so that it can be reached through the network Service.Slice localSlice = svc.getLocalSlice(); if (localSlice != null) { localNode.exportSlice(svc.getName(), localSlice); } // Add the service to the local service finder so that it can be found localServices.put(svc.getName(), svcDsc); // If this service extends BaseService, attach it to the Command Processor if (svc instanceof BaseService) { BaseService bs = (BaseService) svc; bs.setCommandProcessor(myCommandProcessor); } } private void uninstallServiceLocally(String name) throws IMTPException, ServiceException { ServiceDescriptor svcDsc = (ServiceDescriptor) localServices.get(name); if (svcDsc != null) { Service svc = svcDsc.getService(); // Stop the service svc.shutdown(); // Uninstall the service filters Filter fOut = svc.getCommandFilter(Filter.OUTGOING); if (fOut != null) { myCommandProcessor.removeFilter(fOut, Filter.OUTGOING); } Filter fIn = svc.getCommandFilter(Filter.INCOMING); if (fIn != null) { myCommandProcessor.removeFilter(fIn, Filter.INCOMING); } // Uninistall the service sinks Sink sSrc = svc.getCommandSink(Sink.COMMAND_SOURCE); if (sSrc != null) { myCommandProcessor.deregisterSink(Sink.COMMAND_SOURCE, svc.getName()); } Sink sTgt = svc.getCommandSink(Sink.COMMAND_TARGET); if (sTgt != null) { myCommandProcessor.deregisterSink(Sink.COMMAND_TARGET, svc.getName()); } } // Unexport the service slice localNode.unexportSlice(name); // Remove the service localServices.remove(name); } //////////////////////////////////////////////////// // Main container fault management related methods //////////////////////////////////////////////////// void platformManagerDead(String deadPMAddr, String notifyingPMAddr) throws IMTPException { myLogger.log(Logger.INFO, "PlatformManager at "+deadPMAddr+" no longer valid!"); if (compareTransportAddresses(deadPMAddr, myPlatformManager.getLocalAddress())) { // Issue a DEAD_PLATFORM_MANAGER incoming vertical command GenericCommand gCmd = new GenericCommand(Service.DEAD_PLATFORM_MANAGER, null, null); gCmd.addParam(myPlatformManager.getLocalAddress()); Object result = myCommandProcessor.processIncoming(gCmd); if (result instanceof Throwable) { myLogger.log(Logger.WARNING, "Unexpected error processing DEAD_PLATFORM_MANAGER command."); ((Throwable) result).printStackTrace(); } } if (deadPMAddr.equals(notifyingPMAddr)) { // This is a PlatformManager that recovered from a fault reattach(notifyingPMAddr); } else { addAddress(notifyingPMAddr); removeAddress(deadPMAddr); } } /** * This method implements the platform reattachement procedure that is activated after a fault * and a successive recover of the Main Container. * @see jade.core.faultRecovery.FaultRecoveryService */ private synchronized void reattach(String pmAddr) { // We reattach to the recovered PM either if it is our PM or if our // PM is invalid (a previous reattach/reconnect attempt failed). // Otherwise we just do nothing if (invalidPlatformManager || compareTransportAddresses(pmAddr, myPlatformManager.getLocalAddress())) { invalidPlatformManager = true; try { myPlatformManager = myIMTPManager.getPlatformManagerProxy(pmAddr); myLogger.log(Logger.INFO, "Re-attaching to PlatformManager at address " + myPlatformManager.getLocalAddress()); String name = myPlatformManager.addNode(localNodeDescriptor, getLocalServices(), false); if (!name.equals(localNodeDescriptor.getName())) { myLogger.log(Logger.WARNING, "Container name changed re-attaching to PlatformManager: new name = " + name); } adjustName(name); handlePMRefreshed(pmAddr); // Issue a REATTACHED incoming V-Command GenericCommand gCmd = new GenericCommand(Service.REATTACHED, null, null); Object result = myCommandProcessor.processIncoming(gCmd); if (result instanceof Throwable) { myLogger.log(Logger.WARNING, "Unexpected error processing REATTACHED command."); ((Throwable) result).printStackTrace(); } myLogger.log(Logger.INFO, "Re-attachement OK"); } catch (Exception e) { myLogger.log(Logger.SEVERE, "Cannot re-attach to PlatformManager at " + pmAddr + ". " + e); e.printStackTrace(); } } } /** * This method implements the main reconnection procedure that is activated when the main container this container * is connected to crashes and a backup main container becomes the leader. * @see jade.core.replication.MainReplicationService */ private synchronized boolean reconnect() { if (status == ACTIVE_STATUS) { // Check if the current PlatformManager is actually down (another thread // may have reconnected in the meanwhile) try { myPlatformManager.ping(); return true; } catch (IMTPException imtpe) { // The current PlatformManager is actually down --> try to reconnect invalidPlatformManager = true; Iterator it = backupManagers.keySet().iterator(); while (it.hasNext()) { String addr = (String) it.next(); try { myPlatformManager = (PlatformManager) backupManagers.get(addr); myLogger.log(Logger.INFO, "Reconnecting to PlatformManager at address " + myPlatformManager.getLocalAddress()); myPlatformManager.adopt(localNode, null); handlePMRefreshed(addr); // Issue a RECONNECTED incoming V-Command GenericCommand gCmd = new GenericCommand(Service.RECONNECTED, null, null); Object result = myCommandProcessor.processIncoming(gCmd); if (result instanceof Throwable) { myLogger.log(Logger.WARNING, "Unexpected error processing RECONNECTED command."); ((Throwable) result).printStackTrace(); } myLogger.log(Logger.INFO, "Reconnection OK"); return true; } catch (Exception e) { myLogger.log(Logger.WARNING, "Reconnection failed"); // Ignore it and try the next address... } } } } return false; } private void handlePMRefreshed(String pmAddr) { // Clear any cached slice of the Main container Object[] services = localServices.values().toArray(); for (int i = 0; i < services.length; ++i) { ServiceDescriptor svcDsc = (ServiceDescriptor) services[i]; Service svc = svcDsc.getService(); if (svc instanceof BaseService) { ((BaseService) svc).clearCachedSlice(MAIN_SLICE); } } myIMTPManager.reconnected(myPlatformManager); backupManagers.remove(pmAddr); invalidPlatformManager = false; } public Vector getLocalServices() { Object[] services = localServices.values().toArray(); Vector ss = new Vector(services.length); for (int i = 0; i < services.length; ++i) { ss.addElement(services[i]); } return ss; } ////////////////////////////////////////////////// // Private utility methods ////////////////////////////////////////////////// private void adjustName(String name) { localNodeDescriptor.setName(name); localNode.setName(name); ContainerID cid = localNodeDescriptor.getContainer(); if (cid != null) { cid.setName(name); } } private Service.Slice bindToLocalNode(Service.Slice slice) throws ServiceException { if (slice != null) { // If the newly retrieved slice is a proxy, bind it to the local node if (slice instanceof SliceProxy) { ((SliceProxy) slice).setLocalNodeDescriptor(localNodeDescriptor); } // Also if the slice is for the local node be sure it includes the real local // node and not a proxy Node n = slice.getNode(); if (n.getName().equals(localNode.getName()) && !n.equals(localNode)) { ((SliceProxy) slice).setNode(localNode); } } return slice; } private boolean compareTransportAddresses(String addr1, String addr2) { //#MIDP_EXCLUDE_BEGIN return Profile.compareTransportAddresses(addr1, addr2, myIMTPManager); //#MIDP_EXCLUDE_END /*#MIDP_INCLUDE_BEGIN return addr1.equals(addr2); #MIDP_INCLUDE_END*/ } }
lgpl-2.1
JordanReiter/railo
railo-java/railo-core/src/railo/runtime/query/caster/TimeCast.java
584
package railo.runtime.query.caster; import java.io.IOException; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Time; import java.util.TimeZone; import railo.commons.date.JREDateTimeUtil; import railo.runtime.type.dt.DateTimeImpl; public class TimeCast implements Cast{ @Override public Object toCFType(TimeZone tz, int type, ResultSet rst, int columnIndex) throws SQLException, IOException { Time t = rst.getTime(columnIndex,JREDateTimeUtil.getThreadCalendar(tz)); if(t==null) return null; return new DateTimeImpl(t.getTime(),false); } }
lgpl-2.1
Moderbord/Droidforce-UserInterface
cm4Android/src/de/tum/in/i22/uc/cm/datatypes/basic/PxpSpec.java
1012
package de.tum.in.i22.uc.cm.datatypes.basic; public class PxpSpec { private final String ip; private final int port; private final String description; private final String id; public PxpSpec(String ip, int port, String id, String description){ this.id = id; this.ip = ip; this.description = description; this.port = port; } public String getIp() { return ip; } public int getPort() { return port; } public String getDescription() { return description; } public String getId() { return id; } // @Override // public void setIp(String ip) { // // TODO Auto-generated method stub // this.ip = ip; // } // // @Override // public void setPort(int port) { // // TODO Auto-generated method stub // this.port = port; // } // // @Override // public void setDesc(String description) { // // TODO Auto-generated method stub // this.description = description; // } // // @Override // public void setId(String id) { // // TODO Auto-generated method stub // this.id = id; // } }
lgpl-2.1
getrailo/railo
railo-java/railo-core/src/railo/commons/lang/NumberUtil.java
2687
package railo.commons.lang; import railo.runtime.exp.ExpressionException; public class NumberUtil { public static int hexToInt(String s, int defaultValue) { try { return hexToInt(s); } catch (ExpressionException e) { return defaultValue; } } public static int hexToInt(String s) throws ExpressionException { int[] n = new int[s.length()]; char c; int sum = 0; int koef = 1; for(int i=n.length-1; i>=0; i--) { c = s.charAt(i); if(!((c>='0' && c<='9') || (c>='a' && c<='f'))) { throw new ExpressionException("invalid hex constant ["+c+"], hex constants are [0-9,a-f]"); } //System.out.println(c); switch (c) { case 48: n[i] = 0; break; case 49: n[i] = 1; break; case 50: n[i] = 2; break; case 51: n[i] = 3; break; case 52: n[i] = 4; break; case 53: n[i] = 5; break; case 54: n[i] = 6; break; case 55: n[i] = 7; break; case 56: n[i] = 8; break; case 57: n[i] = 9; break; case 97: n[i] = 10; break; case 98: n[i] = 11; break; case 99: n[i] = 12; break; case 100: n[i] = 13; break; case 101: n[i] = 14; break; case 102: n[i] = 15; break; } sum = sum + n[i]*koef; koef=koef*16; } return sum; } public static byte[] longToByteArray(long l) { byte[] ba=new byte[8]; for(int i=0; i<64; i+=8) { ba[i>>3] = new Long((l&(255L<<i))>>i).byteValue(); } return ba; } public static long byteArrayToLong(byte[] ba){ long l=0; for(int i=0; (i<8)&&(i<8); i++) { l |= (((long)ba[i])<<(i<<3))&(255L<<(i<<3)); } return l; } public static int randomRange(int min, int max) { return min + (int)(Math.random() * ((max - min) + 1)); } }
lgpl-2.1
oskopek/jfreechart-fse
src/main/java/org/jfree/data/time/DateRange.java
5244
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2011, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * -------------- * DateRange.java * -------------- * (C) Copyright 2002-2008, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): Bill Kelemen; * * Changes * ------- * 22-Apr-2002 : Version 1 based on code by Bill Kelemen (DG); * 07-Oct-2002 : Fixed errors reported by Checkstyle (DG); * 23-Sep-2003 : Minor Javadoc update (DG); * 28-May-2008 : Fixed problem with immutability (DG); * 01-Sep-2008 : Added getLowerMillis() and getUpperMillis() (DG); * */ package org.jfree.data.time; import java.io.Serializable; import java.text.DateFormat; import java.util.Date; import org.jfree.data.Range; /** * A range specified in terms of two <code>java.util.Date</code> objects. * Instances of this class are immutable. */ public class DateRange extends Range implements Serializable { /** For serialization. */ private static final long serialVersionUID = -4705682568375418157L; /** The lower bound for the range. */ private long lowerDate; /** The upper bound for the range. */ private long upperDate; /** * Default constructor. */ public DateRange() { this(new Date(0), new Date(1)); } /** * Constructs a new range. * * @param lower the lower bound (<code>null</code> not permitted). * @param upper the upper bound (<code>null</code> not permitted). */ public DateRange(Date lower, Date upper) { super(lower.getTime(), upper.getTime()); this.lowerDate = lower.getTime(); this.upperDate = upper.getTime(); } /** * Constructs a new range using two values that will be interpreted as * "milliseconds since midnight GMT, 1-Jan-1970". * * @param lower the lower (oldest) date. * @param upper the upper (most recent) date. */ public DateRange(double lower, double upper) { super(lower, upper); this.lowerDate = (long) lower; this.upperDate = (long) upper; } /** * Constructs a new range that is based on another {@link Range}. The * other range does not have to be a {@link DateRange}. If it is not, the * upper and lower bounds are evaluated as milliseconds since midnight * GMT, 1-Jan-1970. * * @param other the other range (<code>null</code> not permitted). */ public DateRange(Range other) { this(other.getLowerBound(), other.getUpperBound()); } /** * Returns the lower (earlier) date for the range. * * @return The lower date for the range. * * @see #getLowerMillis() */ public Date getLowerDate() { return new Date(this.lowerDate); } /** * Returns the lower bound of the range in milliseconds. * * @return The lower bound. * * @see #getLowerDate() * * @since 1.0.11 */ public long getLowerMillis() { return this.lowerDate; } /** * Returns the upper (later) date for the range. * * @return The upper date for the range. * * @see #getUpperMillis() */ public Date getUpperDate() { return new Date(this.upperDate); } /** * Returns the upper bound of the range in milliseconds. * * @return The upper bound. * * @see #getUpperDate() * * @since 1.0.11 */ public long getUpperMillis() { return this.upperDate; } /** * Returns a string representing the date range (useful for debugging). * * @return A string representing the date range. */ @Override public String toString() { DateFormat df = DateFormat.getDateTimeInstance(); return "[" + df.format(getLowerDate()) + " --> " + df.format(getUpperDate()) + "]"; } }
lgpl-2.1
lucee/unoffical-Lucee-no-jre
source/java/core/src/lucee/runtime/sql/old/ParseException.java
4165
/** * * Copyright (c) 2014, the Railo Company Ltd. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. * **/ package lucee.runtime.sql.old; public final class ParseException extends Exception { public ParseException(Token token, int ai[][], String as[]) { super(""); eol = System.getProperty("line.separator", "\n"); specialConstructor = true; currentToken = token; expectedTokenSequences = ai; tokenImage = as; } public ParseException() { eol = System.getProperty("line.separator", "\n"); specialConstructor = false; } public ParseException(String s) { super(s); eol = System.getProperty("line.separator", "\n"); specialConstructor = false; } @Override public String getMessage() { if(!specialConstructor) return super.getMessage(); String s = ""; int i = 0; for(int j = 0; j < expectedTokenSequences.length; j++) { if(i < expectedTokenSequences[j].length) i = expectedTokenSequences[j].length; for(int k = 0; k < expectedTokenSequences[j].length; k++) s = s + tokenImage[expectedTokenSequences[j][k]] + " "; if(expectedTokenSequences[j][expectedTokenSequences[j].length - 1] != 0) s = s + "..."; s = s + eol + " "; } String s1 = "Encountered \""; Token token = currentToken.next; for(int l = 0; l < i; l++) { if(l != 0) s1 = s1 + " "; if(token.kind == 0) { s1 = s1 + tokenImage[0]; break; } s1 = s1 + add_escapes(token.image); token = token.next; } s1 = s1 + "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn; s1 = s1 + "." + eol; if(expectedTokenSequences.length == 1) s1 = s1 + "Was expecting:" + eol + " "; else s1 = s1 + "Was expecting one of:" + eol + " "; s1 = s1 + s; return s1; } protected String add_escapes(String s) { StringBuffer stringbuffer = new StringBuffer(); for(int i = 0; i < s.length(); i++) { char c; switch(s.charAt(i)) { case 0: // '\0' break; case 8: // '\b' stringbuffer.append("\\b"); break; case 9: // '\t' stringbuffer.append("\\t"); break; case 10: // '\n' stringbuffer.append("\\n"); break; case 12: // '\f' stringbuffer.append("\\f"); break; case 13: // '\r' stringbuffer.append("\\r"); break; case 34: // '"' stringbuffer.append("\\\""); break; case 39: // '\'' stringbuffer.append("\\'"); break; case 92: // '\\' stringbuffer.append("\\\\"); break; default: if((c = s.charAt(i)) < ' ' || c > '~') { String s1 = "0000" + Integer.toString(c, 16); stringbuffer.append("\\u" + s1.substring(s1.length() - 4, s1.length())); } else { stringbuffer.append(c); } break; } } return stringbuffer.toString(); } protected boolean specialConstructor; public Token currentToken; public int expectedTokenSequences[][]; public String tokenImage[]; protected String eol; }
lgpl-2.1
janissl/languagetool
languagetool-wikipedia/src/main/java/org/languagetool/dev/dumpcheck/CompactStdoutHandler.java
2255
/* LanguageTool, a natural language style checker * Copyright (C) 2013 Daniel Naber (http://www.danielnaber.de) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package org.languagetool.dev.dumpcheck; import org.languagetool.Language; import org.languagetool.rules.RuleMatch; import org.languagetool.rules.patterns.AbstractPatternRule; import org.languagetool.tools.ContextTools; import java.util.List; /** * Print compact rule matches to STDOUT. * @since 3.3 */ class CompactStdoutHandler extends ResultHandler { private final ContextTools contextTools = new ContextTools(); CompactStdoutHandler(int maxSentences, int maxErrors) { super(maxSentences, maxErrors); contextTools.setContextSize(70); contextTools.setErrorMarkerStart("**"); contextTools.setErrorMarkerEnd("**"); contextTools.setEscapeHtml(false); } @Override protected void handleResult(Sentence sentence, List<RuleMatch> ruleMatches, Language language) { if (ruleMatches.size() > 0) { for (RuleMatch match : ruleMatches) { String ruleId = match.getRule().getId(); if (match.getRule() instanceof AbstractPatternRule) { AbstractPatternRule pRule = (AbstractPatternRule) match.getRule(); ruleId = pRule.getFullId(); } System.out.println(ruleId + ": " + contextTools.getContext(match.getFromPos(), match.getToPos(), sentence.getText())); checkMaxErrors(++errorCount); } } checkMaxSentences(++sentenceCount); } @Override public void close() throws Exception { } }
lgpl-2.1
kevintvh/Chronicle-Map
src/main/java/net/openhft/chronicle/map/UnaryOperator.java
1245
/* * Copyright (C) 2015 higherfrequencytrading.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License. * * 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 program. If not, see <http://www.gnu.org/licenses/>. */ package net.openhft.chronicle.map; import java.io.Serializable; /** * Represents a mutator that accepts one mutable argument, which it may alter and produces a result. * * <p>This is not functional as it can alter an argument. * * @param <T> the type of the mutable input */ public interface UnaryOperator<T> extends Serializable { /** * Applies this mutator to the given mutable argument. * * @param t the mutator argument * @return the result */ T update(T t); }
lgpl-3.0
gjroelofs/java-psd-library
psd-tool/src/psdtool/PsdView.java
1464
package psdtool; import psd.Layer; import psd.LayersContainer; import psd.Psd; import psd.parser.layer.additional.effects.PSDEffect; import javax.swing.*; import java.awt.*; public class PsdView extends JComponent { private static final long serialVersionUID = 1L; private Psd psd; public PsdView() { setPreferredSize(new Dimension(400, 400)); } public void setPsd(Psd psd) { this.psd = psd; setPreferredSize(new Dimension(psd.getWidth(), psd.getHeight())); repaint(); revalidate(); } @Override public void paintComponent(Graphics g) { if (psd != null) { paintLayersContainer((Graphics2D) g, psd, 1.0f); } } private void paintLayersContainer(Graphics2D g, LayersContainer container, float alpha) { for (int i = 0; i < container.getLayersCount(); i++) { Layer layer = container.getLayer(i); if (!layer.isVisible()) { continue; } Composite composite = g.getComposite(); float layerAlpha = alpha * layer.getAlpha() / 255.0f; g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, layerAlpha)); if (layer.getImage() != null) { g.drawImage(layer.getImage(), layer.getX(), layer.getY(), null); } g.setComposite(composite); paintLayersContainer(g, layer, layerAlpha); } } }
lgpl-3.0
ReneMuetti/TiC-Tooltips
java/squeek/tictooltips/helpers/ColorHelper.java
949
package squeek.tictooltips.helpers; import net.minecraft.util.EnumChatFormatting; public class ColorHelper { private static final EnumChatFormatting colorRange[] = { EnumChatFormatting.DARK_RED, EnumChatFormatting.RED, EnumChatFormatting.GOLD, EnumChatFormatting.YELLOW, EnumChatFormatting.DARK_GREEN, EnumChatFormatting.GREEN, EnumChatFormatting.AQUA }; public static String getRelativeColor(double val, double min, double max) { if (min == max) return EnumChatFormatting.RESET.toString(); else if ((max > min && val > max) || (min > max && val < max)) return EnumChatFormatting.WHITE.toString() + EnumChatFormatting.BOLD; else if ((max > min && val < min) || (min > max && val > min)) return colorRange[0].toString() + EnumChatFormatting.BOLD; int index = (int) (((val - min) / (max - min)) * (colorRange.length - 1)); return colorRange[Math.max(0, Math.min(colorRange.length - 1, index))].toString(); } }
unlicense
floodlight/loxigen-artifacts
openflowj/gen-src/main/java/org/projectfloodlight/openflow/protocol/ver12/OFBadActionCodeSerializerVer12.java
6063
// Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior University // Copyright (c) 2011, 2012 Open Networking Foundation // Copyright (c) 2012, 2013 Big Switch Networks, Inc. // This library was generated by the LoxiGen Compiler. // See the file LICENSE.txt which should have been included in the source distribution // Automatically generated by LOXI from template const_serializer.java // Do not modify package org.projectfloodlight.openflow.protocol.ver12; import org.projectfloodlight.openflow.protocol.*; import org.projectfloodlight.openflow.protocol.action.*; import org.projectfloodlight.openflow.protocol.actionid.*; import org.projectfloodlight.openflow.protocol.bsntlv.*; import org.projectfloodlight.openflow.protocol.errormsg.*; import org.projectfloodlight.openflow.protocol.meterband.*; import org.projectfloodlight.openflow.protocol.instruction.*; import org.projectfloodlight.openflow.protocol.instructionid.*; import org.projectfloodlight.openflow.protocol.match.*; import org.projectfloodlight.openflow.protocol.stat.*; import org.projectfloodlight.openflow.protocol.oxm.*; import org.projectfloodlight.openflow.protocol.oxs.*; import org.projectfloodlight.openflow.protocol.queueprop.*; import org.projectfloodlight.openflow.types.*; import org.projectfloodlight.openflow.util.*; import org.projectfloodlight.openflow.exceptions.*; import org.projectfloodlight.openflow.protocol.OFBadActionCode; import io.netty.buffer.ByteBuf; import com.google.common.hash.PrimitiveSink; public class OFBadActionCodeSerializerVer12 { public final static short BAD_TYPE_VAL = (short) 0x0; public final static short BAD_LEN_VAL = (short) 0x1; public final static short BAD_EXPERIMENTER_VAL = (short) 0x2; public final static short BAD_EXPERIMENTER_TYPE_VAL = (short) 0x3; public final static short BAD_OUT_PORT_VAL = (short) 0x4; public final static short BAD_ARGUMENT_VAL = (short) 0x5; public final static short EPERM_VAL = (short) 0x6; public final static short TOO_MANY_VAL = (short) 0x7; public final static short BAD_QUEUE_VAL = (short) 0x8; public final static short BAD_OUT_GROUP_VAL = (short) 0x9; public final static short MATCH_INCONSISTENT_VAL = (short) 0xa; public final static short UNSUPPORTED_ORDER_VAL = (short) 0xb; public final static short BAD_TAG_VAL = (short) 0xc; public final static short BAD_SET_TYPE_VAL = (short) 0xd; public final static short BAD_SET_LEN_VAL = (short) 0xe; public final static short BAD_SET_ARGUMENT_VAL = (short) 0xf; public static OFBadActionCode readFrom(ByteBuf bb) throws OFParseError { try { return ofWireValue(bb.readShort()); } catch (IllegalArgumentException e) { throw new OFParseError(e); } } public static void writeTo(ByteBuf bb, OFBadActionCode e) { bb.writeShort(toWireValue(e)); } public static void putTo(OFBadActionCode e, PrimitiveSink sink) { sink.putShort(toWireValue(e)); } public static OFBadActionCode ofWireValue(short val) { switch(val) { case BAD_TYPE_VAL: return OFBadActionCode.BAD_TYPE; case BAD_LEN_VAL: return OFBadActionCode.BAD_LEN; case BAD_EXPERIMENTER_VAL: return OFBadActionCode.BAD_EXPERIMENTER; case BAD_EXPERIMENTER_TYPE_VAL: return OFBadActionCode.BAD_EXPERIMENTER_TYPE; case BAD_OUT_PORT_VAL: return OFBadActionCode.BAD_OUT_PORT; case BAD_ARGUMENT_VAL: return OFBadActionCode.BAD_ARGUMENT; case EPERM_VAL: return OFBadActionCode.EPERM; case TOO_MANY_VAL: return OFBadActionCode.TOO_MANY; case BAD_QUEUE_VAL: return OFBadActionCode.BAD_QUEUE; case BAD_OUT_GROUP_VAL: return OFBadActionCode.BAD_OUT_GROUP; case MATCH_INCONSISTENT_VAL: return OFBadActionCode.MATCH_INCONSISTENT; case UNSUPPORTED_ORDER_VAL: return OFBadActionCode.UNSUPPORTED_ORDER; case BAD_TAG_VAL: return OFBadActionCode.BAD_TAG; case BAD_SET_TYPE_VAL: return OFBadActionCode.BAD_SET_TYPE; case BAD_SET_LEN_VAL: return OFBadActionCode.BAD_SET_LEN; case BAD_SET_ARGUMENT_VAL: return OFBadActionCode.BAD_SET_ARGUMENT; default: throw new IllegalArgumentException("Illegal wire value for type OFBadActionCode in version 1.2: " + val); } } public static short toWireValue(OFBadActionCode e) { switch(e) { case BAD_TYPE: return BAD_TYPE_VAL; case BAD_LEN: return BAD_LEN_VAL; case BAD_EXPERIMENTER: return BAD_EXPERIMENTER_VAL; case BAD_EXPERIMENTER_TYPE: return BAD_EXPERIMENTER_TYPE_VAL; case BAD_OUT_PORT: return BAD_OUT_PORT_VAL; case BAD_ARGUMENT: return BAD_ARGUMENT_VAL; case EPERM: return EPERM_VAL; case TOO_MANY: return TOO_MANY_VAL; case BAD_QUEUE: return BAD_QUEUE_VAL; case BAD_OUT_GROUP: return BAD_OUT_GROUP_VAL; case MATCH_INCONSISTENT: return MATCH_INCONSISTENT_VAL; case UNSUPPORTED_ORDER: return UNSUPPORTED_ORDER_VAL; case BAD_TAG: return BAD_TAG_VAL; case BAD_SET_TYPE: return BAD_SET_TYPE_VAL; case BAD_SET_LEN: return BAD_SET_LEN_VAL; case BAD_SET_ARGUMENT: return BAD_SET_ARGUMENT_VAL; default: throw new IllegalArgumentException("Illegal enum value for type OFBadActionCode in version 1.2: " + e); } } }
apache-2.0
zstackorg/zstack
sdk/src/main/java/org/zstack/sdk/VpcFirewallRuleTemplateInventory.java
4234
package org.zstack.sdk; import org.zstack.sdk.ActionType; import org.zstack.sdk.ProtocolType; import org.zstack.sdk.FirewallRuleState; public class VpcFirewallRuleTemplateInventory { public ActionType action; public void setAction(ActionType action) { this.action = action; } public ActionType getAction() { return this.action; } public ProtocolType protocol; public void setProtocol(ProtocolType protocol) { this.protocol = protocol; } public ProtocolType getProtocol() { return this.protocol; } public java.lang.String name; public void setName(java.lang.String name) { this.name = name; } public java.lang.String getName() { return this.name; } public java.lang.String destPort; public void setDestPort(java.lang.String destPort) { this.destPort = destPort; } public java.lang.String getDestPort() { return this.destPort; } public java.lang.String sourcePort; public void setSourcePort(java.lang.String sourcePort) { this.sourcePort = sourcePort; } public java.lang.String getSourcePort() { return this.sourcePort; } public java.lang.String sourceIp; public void setSourceIp(java.lang.String sourceIp) { this.sourceIp = sourceIp; } public java.lang.String getSourceIp() { return this.sourceIp; } public java.lang.String destIp; public void setDestIp(java.lang.String destIp) { this.destIp = destIp; } public java.lang.String getDestIp() { return this.destIp; } public java.lang.String allowStates; public void setAllowStates(java.lang.String allowStates) { this.allowStates = allowStates; } public java.lang.String getAllowStates() { return this.allowStates; } public java.lang.String tcpFlag; public void setTcpFlag(java.lang.String tcpFlag) { this.tcpFlag = tcpFlag; } public java.lang.String getTcpFlag() { return this.tcpFlag; } public java.lang.String icmpTypeName; public void setIcmpTypeName(java.lang.String icmpTypeName) { this.icmpTypeName = icmpTypeName; } public java.lang.String getIcmpTypeName() { return this.icmpTypeName; } public int ruleNumber; public void setRuleNumber(int ruleNumber) { this.ruleNumber = ruleNumber; } public int getRuleNumber() { return this.ruleNumber; } public boolean enableLog; public void setEnableLog(boolean enableLog) { this.enableLog = enableLog; } public boolean getEnableLog() { return this.enableLog; } public FirewallRuleState state; public void setState(FirewallRuleState state) { this.state = state; } public FirewallRuleState getState() { return this.state; } public boolean isDefault; public void setIsDefault(boolean isDefault) { this.isDefault = isDefault; } public boolean getIsDefault() { return this.isDefault; } public java.lang.String description; public void setDescription(java.lang.String description) { this.description = description; } public java.lang.String getDescription() { return this.description; } public java.sql.Timestamp createDate; public void setCreateDate(java.sql.Timestamp createDate) { this.createDate = createDate; } public java.sql.Timestamp getCreateDate() { return this.createDate; } public java.sql.Timestamp lastOpDate; public void setLastOpDate(java.sql.Timestamp lastOpDate) { this.lastOpDate = lastOpDate; } public java.sql.Timestamp getLastOpDate() { return this.lastOpDate; } public java.lang.String accountUuid; public void setAccountUuid(java.lang.String accountUuid) { this.accountUuid = accountUuid; } public java.lang.String getAccountUuid() { return this.accountUuid; } public java.lang.String uuid; public void setUuid(java.lang.String uuid) { this.uuid = uuid; } public java.lang.String getUuid() { return this.uuid; } }
apache-2.0
langfr/camunda-bpm-platform
qa/large-data-tests/src/test/java/org/camunda/bpm/qa/largedata/DeleteDeploymentCascadeTest.java
3970
/* * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH * under one or more contributor license agreements. See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. Camunda licenses this file to you under the Apache License, * Version 2.0; 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.camunda.bpm.qa.largedata; import static org.assertj.core.api.Assertions.assertThat; import java.util.List; import java.util.stream.Collectors; import org.camunda.bpm.engine.HistoryService; import org.camunda.bpm.engine.RepositoryService; import org.camunda.bpm.engine.history.HistoricProcessInstance; import org.camunda.bpm.engine.impl.db.sql.DbSqlSessionFactory; import org.camunda.bpm.engine.impl.util.CollectionUtil; import org.camunda.bpm.engine.repository.Deployment; import org.camunda.bpm.engine.test.ProcessEngineRule; import org.camunda.bpm.qa.largedata.util.EngineDataGenerator; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; public class DeleteDeploymentCascadeTest { @Rule public ProcessEngineRule processEngineRule = new ProcessEngineRule("camunda.cfg.xml"); protected static final String DATA_PREFIX = DeleteDeploymentCascadeTest.class.getSimpleName(); protected int GENERATE_PROCESS_INSTANCES_COUNT = 2500; protected RepositoryService repositoryService; protected HistoryService historyService; protected EngineDataGenerator generator; @Before public void init() { repositoryService = processEngineRule.getProcessEngine().getRepositoryService(); historyService = processEngineRule.getProcessEngine().getHistoryService(); // generate data generator = new EngineDataGenerator(processEngineRule.getProcessEngine(), GENERATE_PROCESS_INSTANCES_COUNT, DATA_PREFIX); generator.deployDefinitions(); generator.generateCompletedProcessInstanceData(); } @After public void teardown() { Deployment deployment = repositoryService.createDeploymentQuery().deploymentName(generator.getDeploymentName()).singleResult(); if (deployment != null) { List<HistoricProcessInstance> processInstances = historyService.createHistoricProcessInstanceQuery() .processDefinitionKey(generator.getAutoCompleteProcessKey()).list(); if (!processInstances.isEmpty()) { List<String> processInstanceIds = processInstances.stream().map(HistoricProcessInstance::getId).collect(Collectors.toList()); List<List<String>> partitions = CollectionUtil.partition(processInstanceIds, DbSqlSessionFactory.MAXIMUM_NUMBER_PARAMS); for (List<String> partition : partitions) { historyService.deleteHistoricProcessInstances(partition); } } repositoryService.deleteDeployment(deployment.getId(), false); } } @Test public void shouldDeleteCascadeWithLargeParameterCount() { // given Deployment deployment = repositoryService.createDeploymentQuery().deploymentName(generator.getDeploymentName()).singleResult(); // when repositoryService.deleteDeployment(deployment.getId(), true); // then deployment = repositoryService.createDeploymentQuery().deploymentName(generator.getDeploymentName()).singleResult(); assertThat(deployment).isNull(); List<HistoricProcessInstance> instances = historyService.createHistoricProcessInstanceQuery() .processDefinitionKey(generator.getAutoCompleteProcessKey()).list(); assertThat(instances).isEmpty(); } }
apache-2.0