answer
stringlengths 17
10.2M
|
|---|
package com.vrg.rapid;
import com.google.common.net.HostAndPort;
import com.vrg.rapid.pb.MembershipServiceGrpc;
import io.grpc.ClientInterceptor;
import io.grpc.MethodDescriptor;
import io.grpc.ServerInterceptor;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import javax.annotation.Nullable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Test public API
*/
public class ClusterTest {
private static final Logger GRPC_LOGGER;
private static final Logger NETTY_LOGGER;
private final Map<HostAndPort, Cluster> instances = new ConcurrentHashMap<>();
private final Map<HostAndPort, StaticFailureDetector> staticFds = new ConcurrentHashMap<>();
private final Map<HostAndPort, List<ServerInterceptor>> serverInterceptors = new ConcurrentHashMap<>();
private final Map<HostAndPort, List<ClientInterceptor>> clientInterceptors = new ConcurrentHashMap<>();
private boolean useStaticFd = false;
private boolean addMetadata = true;
@Nullable private Random random = null;
private long seed;
private int basePort;
@Nullable private AtomicInteger portCounter = null;
private RpcClient.Conf clientConf = new RpcClient.Conf();
static {
// gRPC and netty logs clutter the test output
GRPC_LOGGER = Logger.getLogger("io.grpc");
GRPC_LOGGER.setLevel(Level.OFF);
NETTY_LOGGER = Logger.getLogger("io.grpc.netty.NettyServerHandler");
NETTY_LOGGER.setLevel(Level.OFF);
}
@Rule
public final TestWatcher testWatcher = new TestWatcher() {
@Override
protected void failed(final Throwable e, final Description description) {
System.out.println("\u001B[31m [FAILED] [Seed: " + seed + "] " + description.getMethodName()
+ "\u001B[0m");
}
};
@Before
public void beforeTest() {
basePort = 1234;
portCounter = new AtomicInteger(basePort);
instances.clear();
seed = ThreadLocalRandom.current().nextLong();
random = new Random(seed);
clientConf = new RpcClient.Conf();
// Tests need to opt out of the in-process channel
RpcServer.USE_IN_PROCESS_SERVER = true;
RpcClient.USE_IN_PROCESS_CHANNEL = true;
MembershipService.FAILURE_DETECTOR_INTERVAL_IN_MS = 1000;
useStaticFd = false;
addMetadata = true;
staticFds.clear();
serverInterceptors.clear();
clientInterceptors.clear();
}
@After
public void afterTest() throws InterruptedException {
for (final Cluster cluster: instances.values()) {
cluster.shutdown();
}
}
/**
* Test with a single node joining through a seed.
*/
@Test(timeout = 30000)
public void singleNodeJoinsThroughSeed() throws IOException, InterruptedException, ExecutionException {
RpcServer.USE_IN_PROCESS_SERVER = false;
RpcClient.USE_IN_PROCESS_CHANNEL = false;
final HostAndPort seedHost = HostAndPort.fromParts("127.0.0.1", basePort);
createCluster(1, seedHost);
verifyCluster(1, seedHost);
extendCluster(1, seedHost);
verifyCluster(2, seedHost);
}
/**
* Test with K nodes joining the network through a single seed.
*/
@Test(timeout = 30000)
public void tenNodesJoinSequentially() throws IOException, InterruptedException {
// Explicitly test netty
RpcServer.USE_IN_PROCESS_SERVER = false;
RpcClient.USE_IN_PROCESS_CHANNEL = false;
final int numNodes = 10;
final HostAndPort seedHost = HostAndPort.fromParts("127.0.0.1", basePort);
createCluster(1, seedHost); // Only bootstrap a seed.
verifyCluster(1, seedHost);
for (int i = 0; i < numNodes; i++) {
extendCluster(1, seedHost);
waitAndVerifyAgreement(i + 2, 5, 1000, seedHost);
}
}
/**
* Identical to the previous test, but with more than K nodes joining in serial.
*/
@Test(timeout = 30000)
public void twentyNodesJoinSequentially() throws IOException, InterruptedException {
// Explicitly test netty
RpcServer.USE_IN_PROCESS_SERVER = false;
RpcClient.USE_IN_PROCESS_CHANNEL = false;
final int numNodes = 20;
final HostAndPort seedHost = HostAndPort.fromParts("127.0.0.1", basePort);
createCluster(1, seedHost); // Only bootstrap a seed.
verifyCluster(1, seedHost);
for (int i = 0; i < numNodes; i++) {
extendCluster(1, seedHost);
waitAndVerifyAgreement(i + 2, 5, 1000, seedHost);
}
}
/**
* Identical to the previous test, but with more than K nodes joining in parallel.
*
* The test starts with a single seed and all N - 1 subsequent nodes initiate their join protocol at the same
* time. This tests a single seed's ability to bootstrap a large cluster in one step.
*/
@Test(timeout = 150000)
public void hundredNodesJoinInParallel() throws IOException, InterruptedException {
addMetadata = false;
final int numNodes = 100; // Includes the size of the cluster
final HostAndPort seedHost = HostAndPort.fromParts("127.0.0.1", basePort);
createCluster(numNodes, seedHost);
verifyCluster(numNodes, seedHost);
verifyClusterMetadata(0);
}
/**
* This test starts with a single seed, and a wave where 50 subsequent nodes initiate their join protocol
* concurrently. Following this, a subsequent wave begins where 100 nodes then start together.
*/
@Test(timeout = 150000)
public void fiftyNodesJoinTwentyNodeCluster() throws IOException, InterruptedException {
RpcServer.USE_IN_PROCESS_SERVER = true;
RpcClient.USE_IN_PROCESS_CHANNEL = true;
final int numNodesPhase1 = 20;
final int numNodesPhase2 = 50;
final HostAndPort seedHost = HostAndPort.fromParts("127.0.0.1", basePort);
createCluster(numNodesPhase1, seedHost);
waitAndVerifyAgreement(numNodesPhase1, 10, 100, seedHost);
extendCluster(numNodesPhase2, seedHost);
waitAndVerifyAgreement(numNodesPhase1 + numNodesPhase2, 10, 1000, seedHost);
}
/**
* This test starts with a 4 node cluster. We then fail a single node to see if the monitoring mechanism
* identifies the failing node and arrives at a decision to remove it.
*/
@Test(timeout = 30000)
public void oneFailureOutOfFiveNodes() throws IOException, InterruptedException {
useFastFailureDetectionTimeouts();
final int numNodes = 5;
final HostAndPort seedHost = HostAndPort.fromParts("127.0.0.1", basePort);
createCluster(numNodes, seedHost);
verifyCluster(numNodes, seedHost);
final HostAndPort nodeToFail = HostAndPort.fromParts("127.0.0.1", basePort + 2);
failSomeNodes(Collections.singletonList(nodeToFail));
waitAndVerifyAgreement(numNodes - 1, 10, 1000, seedHost);
verifyNumClusterInstances(numNodes - 1);
}
/**
* This test starts with a 30 node cluster, then fails 5 nodes while an additional 10 join.
*/
@Test(timeout = 30000)
public void concurrentNodeJoinsAndFails() throws IOException, InterruptedException {
useFastFailureDetectionTimeouts();
final int numNodes = 30;
final int failingNodes = 5;
final int phaseTwojoiners = 10;
final HostAndPort seedHost = HostAndPort.fromParts("127.0.0.1", basePort);
createCluster(numNodes, seedHost);
verifyCluster(numNodes, seedHost);
failSomeNodes(IntStream.range(basePort + 2, basePort + 2 + failingNodes)
.mapToObj(i -> HostAndPort.fromParts("127.0.0.1", i))
.collect(Collectors.toList()));
extendCluster(phaseTwojoiners, seedHost);
waitAndVerifyAgreement(numNodes - failingNodes + phaseTwojoiners, 20, 1000, seedHost);
verifyNumClusterInstances(numNodes - failingNodes + phaseTwojoiners);
}
/**
* This test starts with a 5 node cluster, then joins two waves of six nodes each.
*/
@Test(timeout = 30000)
public void concurrentNodeJoinsNetty() throws IOException, InterruptedException {
RpcServer.USE_IN_PROCESS_SERVER = false;
RpcClient.USE_IN_PROCESS_CHANNEL = false;
final int numNodes = 5;
final int phaseOneJoiners = 6;
final int phaseTwojoiners = 6;
final HostAndPort seedHost = HostAndPort.fromParts("127.0.0.1", basePort);
createCluster(numNodes, seedHost);
verifyCluster(numNodes, seedHost);
final Random r = new Random();
for (int i = 0; i < phaseOneJoiners / 2; i++) {
final List<HostAndPort> keysAsArray = new ArrayList<>(instances.keySet());
extendCluster(2, keysAsArray.get(r.nextInt(instances.size())));
}
Thread.sleep(100);
for (int i = 0; i < phaseTwojoiners; i++) {
extendCluster(1, seedHost);
}
waitAndVerifyAgreement(numNodes + phaseOneJoiners + phaseTwojoiners, 20, 1000, seedHost);
verifyNumClusterInstances(numNodes + phaseOneJoiners + phaseTwojoiners);
}
/**
* This test starts with a 50 node cluster. We then fail 16 nodes to see if the monitoring mechanism
* identifies the crashed nodes, and arrives at a decision.
*
*/
@Test(timeout = 30000)
public void twelveFailuresOutOfFiftyNodes() throws IOException, InterruptedException {
useFastFailureDetectionTimeouts();
final int numNodes = 50;
final int failingNodes = 12;
final HostAndPort seedHost = HostAndPort.fromParts("127.0.0.1", basePort);
createCluster(numNodes, seedHost);
verifyCluster(numNodes, seedHost);
failSomeNodes(IntStream.range(basePort + 2, basePort + 2 + failingNodes)
.mapToObj(i -> HostAndPort.fromParts("127.0.0.1", i))
.collect(Collectors.toList()));
waitAndVerifyAgreement(numNodes - failingNodes, 30, 1000, seedHost);
verifyNumClusterInstances(numNodes - failingNodes);
}
/**
* This test starts with a 50 node cluster. We then use the static failure detector to fail
* all edges to 3 nodes.
*/
@Test(timeout = 30000)
public void failTenRandomNodes() throws IOException, InterruptedException {
useStaticFd = true;
final int numNodes = 50;
final int numFailingNodes = 10;
final HostAndPort seedHost = HostAndPort.fromParts("127.0.0.1", basePort);
createCluster(numNodes, seedHost);
verifyCluster(numNodes, seedHost);
// Fail the first 3 nodes.
final Set<HostAndPort> failingNodes = getRandomHosts(numFailingNodes);
staticFds.values().forEach(e -> e.addFailedNodes(failingNodes));
waitAndVerifyAgreement(numNodes - failingNodes.size(), 20, 1000, seedHost);
// Nodes do not actually shutdown(), but are detected faulty. The faulty nodes have active
// cluster instances and identify themselves as kicked out.
verifyNumClusterInstances(numNodes);
}
/**
* This test starts with a 50 node cluster. We then randomly fail at most 10 randomly selected nodes.
*/
@Test
public void injectAsymmetricDrops() throws IOException, InterruptedException {
useFastFailureDetectionTimeouts();
final int numNodes = 50;
final int numFailingNodes = 10;
final HostAndPort seedHost = HostAndPort.fromParts("127.0.0.1", basePort);
// These nodes will drop the first 100 probe requests they receive
final Set<HostAndPort> failedNodes =
getRandomHosts(basePort + 1, basePort + numNodes, numFailingNodes);
// Since the random function returns a set of failed nodes,
// we may have less than numFailedNodes entries in the set
failedNodes.forEach(host -> dropFirstNAtServer(host, 100, MembershipServiceGrpc.METHOD_RECEIVE_PROBE));
createCluster(numNodes, seedHost);
waitAndVerifyAgreement(numNodes - failedNodes.size(), 10, 1000, seedHost);
verifyNumClusterInstances(numNodes);
}
/**
* This test starts with a node joining a 1 node cluster. We drop phase 2 messages at the seed
* such that RPC-level retries of the first join attempt eventually get through.
*/
@Test(timeout = 30000)
public void phase2MessageDropsRpcRetries() throws IOException, InterruptedException {
useShortJoinTimeouts();
final HostAndPort seedHost = HostAndPort.fromParts("127.0.0.1", basePort);
// Drop join-phase-2 attempts by nextNode, but only enough that the RPC retries make it past
dropFirstNAtServer(seedHost, (clientConf.RPC_DEFAULT_RETRIES) - 1,
MembershipServiceGrpc.METHOD_RECEIVE_JOIN_PHASE2MESSAGE);
createCluster(1, seedHost);
extendCluster(1, seedHost);
waitAndVerifyAgreement(2, 15, 1000, seedHost);
verifyNumClusterInstances(2);
}
/**
* This test starts with a node joining a 1 node cluster. We drop phase 2 messages at the seed
* such that RPC-level retries of the first join attempt fail, and the client re-initiates a join.
*/
@Test(timeout = 30000)
public void phase2JoinAttemptRetry() throws IOException, InterruptedException {
useShortJoinTimeouts();
final HostAndPort seedHost = HostAndPort.fromParts("127.0.0.1", basePort);
// Drop join-phase-2 attempts by nextNode such that it re-attempts a join under a new configuration
dropFirstNAtServer(seedHost, (clientConf.RPC_DEFAULT_RETRIES) + 1,
MembershipServiceGrpc.METHOD_RECEIVE_JOIN_PHASE2MESSAGE);
createCluster(1, seedHost);
extendCluster(1, seedHost);
waitAndVerifyAgreement(2, 15, 1000, seedHost);
verifyNumClusterInstances(2);
}
/**
* By the time a joiner issues a join-phase2-message, we change the configuration.
*/
@Test(timeout = 30000)
public void phase2JoinAttemptRetryWithConfigChange() throws IOException, InterruptedException {
final HostAndPort seedHost = HostAndPort.fromParts("127.0.0.1", basePort);
final HostAndPort joinerHost = HostAndPort.fromParts("127.0.0.1", basePort + 1);
// Drop join-phase-2 attempts by nextNode such that it re-attempts a join under a new configuration
createCluster(1, seedHost);
// The next host to join will have its join-phase2-message blocked.
final CountDownLatch latch = blockAtClient(joinerHost, MembershipServiceGrpc.METHOD_RECEIVE_JOIN_PHASE2MESSAGE);
extendClusterNonBlocking(1, seedHost);
// The following node is now free to join. This will render the configuration received by the previous
// joiner node stale
extendCluster(1, seedHost);
latch.countDown();
waitAndVerifyAgreement(3, 15, 1000, seedHost);
verifyNumClusterInstances(3);
}
/**
* Shutdown a node and rejoin multiple times.
*/
@Test(timeout = 30000)
public void testRejoinSingleNode() throws IOException, InterruptedException {
useFastFailureDetectionTimeouts();
final HostAndPort seedHost = HostAndPort.fromParts("127.0.0.1", basePort);
final HostAndPort leavingHost = HostAndPort.fromParts("127.0.0.1", basePort + 1);
createCluster(10, seedHost);
// Shutdown and rejoin twice
for (int i = 0; i < 2; i++) {
final Cluster cluster = instances.remove(leavingHost);
cluster.shutdown();
waitAndVerifyAgreement(9, 20, 500, seedHost);
extendCluster(leavingHost, seedHost);
waitAndVerifyAgreement(10, 20, 500, seedHost);
}
}
/**
* Shutdown a node and rejoin before the failure detectors kick it out
*/
@Test(timeout = 30000)
public void testRejoinSingleNodeSameConfiguration() throws IOException, InterruptedException {
useShortJoinTimeouts();
useFastFailureDetectionTimeouts();
final HostAndPort seedHost = HostAndPort.fromParts("127.0.0.1", basePort);
final HostAndPort rejoiningHost = HostAndPort.fromParts("127.0.0.1", basePort + 1);
createCluster(10, seedHost);
// Shutdown and rejoin once
Cluster cluster = null;
try {
cluster = instances.remove(rejoiningHost);
cluster.shutdown();
try {
buildCluster(rejoiningHost).join(seedHost);
fail();
} catch (final Cluster.JoinException ignored) {
}
waitAndVerifyAgreement(9, 10, 1000, seedHost);
cluster = buildCluster(rejoiningHost).join(seedHost);
waitAndVerifyAgreement(10, 10, 500, seedHost);
} finally {
if (cluster != null) {
cluster.shutdown();
}
}
}
/**
* Shutdown a node and rejoin multiple times.
*/
@Test(timeout = 30000)
public void testRejoinMultipleNodes() throws IOException, InterruptedException {
useFastFailureDetectionTimeouts();
final HostAndPort seedHost = HostAndPort.fromParts("127.0.0.1", basePort);
final int numNodes = 30;
final int failNodes = 5;
createCluster(numNodes, seedHost);
final ExecutorService executor = Executors.newWorkStealingPool(failNodes);
final CountDownLatch latch = new CountDownLatch(failNodes);
for (int j = 0; j < failNodes; j++) {
final int inc = j;
executor.execute(() -> {
// Shutdown and rejoin thrice
try {
for (int i = 0; i < 3; i++) {
final HostAndPort leavingHost = HostAndPort.fromParts("127.0.0.1", basePort + 1 + inc);
final Cluster cluster = instances.remove(leavingHost);
try {
cluster.shutdown();
waitAndVerifyAgreement(numNodes - failNodes, 20, 500, seedHost);
extendCluster(leavingHost, seedHost);
waitAndVerifyAgreement(numNodes, 20, 500, seedHost);
} catch (final InterruptedException e) {
fail();
}
}
} finally {
latch.countDown();
}
});
}
latch.await();
waitAndVerifyAgreement(numNodes, 10, 250, seedHost);
}
/**
* Creates a cluster of size {@code numNodes} with a seed {@code seedHost}.
*
* @param numNodes cluster size
* @param seedHost HostAndPort that represents the seed node to initialize and be used as the contact point
* for subsequent joiners.
* @throws IOException Thrown if the Cluster.start() or join() methods throw an IOException when trying
* to register an RpcServer.
*/
private void createCluster(final int numNodes, final HostAndPort seedHost) throws IOException {
final Cluster seed = buildCluster(seedHost).start();
instances.put(seedHost, seed);
assertEquals(seed.getMemberlist().size(), 1);
if (numNodes >= 2) {
extendCluster(numNodes - 1, seedHost);
}
}
/**
* Add {@code numNodes} instances to a cluster.
*
* @param numNodes cluster size
* @param seedHost HostAndPort that represents the seed node to initialize and be used as the contact point
* for subsequent joiners.
*/
private void extendCluster(final int numNodes, final HostAndPort seedHost) {
final ExecutorService executor = Executors.newWorkStealingPool(numNodes);
try {
final CountDownLatch latch = new CountDownLatch(numNodes);
for (int i = 0; i < numNodes; i++) {
executor.execute(() -> {
try {
final HostAndPort joiningHost =
HostAndPort.fromParts("127.0.0.1", portCounter.incrementAndGet());
final Cluster nonSeed = buildCluster(joiningHost).join(seedHost);
instances.put(joiningHost, nonSeed);
} catch (final InterruptedException | IOException e) {
e.printStackTrace();
fail();
} finally {
latch.countDown();
}
});
}
latch.await();
} catch (final InterruptedException e) {
e.printStackTrace();
fail();
} finally {
executor.shutdown();
}
}
/**
* Add {@code numNodes} instances to a cluster.
*
* @param joiningNode HostAndPort that represents the node joining.
* @param seedHost HostAndPort that represents the seed node to initialize and be used as the contact point
* for subsequent joiners.
*/
private void extendCluster(final HostAndPort joiningNode, final HostAndPort seedHost) {
final ExecutorService executor = Executors.newWorkStealingPool(1);
try {
final CountDownLatch latch = new CountDownLatch(1);
executor.execute(() -> {
try {
final Cluster nonSeed = buildCluster(joiningNode).join(seedHost);
instances.put(joiningNode, nonSeed);
} catch (final InterruptedException | IOException e) {
fail();
} finally {
latch.countDown();
}
});
latch.await();
} catch (final InterruptedException e) {
e.printStackTrace();
fail();
} finally {
executor.shutdown();
}
}
/**
* Add {@code numNodes} instances to a cluster without waiting for their join methods to return
*
* @param numNodes cluster size
* @param seedHost HostAndPort that represents the seed node to initialize and be used as the contact point
* for subsequent joiners.
*/
private void extendClusterNonBlocking(final int numNodes, final HostAndPort seedHost) {
final ExecutorService executor = Executors.newWorkStealingPool(numNodes);
try {
for (int i = 0; i < numNodes; i++) {
executor.execute(() -> {
try {
final HostAndPort joiningHost =
HostAndPort.fromParts("127.0.0.1", portCounter.incrementAndGet());
final Cluster nonSeed = buildCluster(joiningHost).join(seedHost);
instances.put(joiningHost, nonSeed);
} catch (final InterruptedException | IOException e) {
e.printStackTrace();
fail();
}
});
}
} finally {
executor.shutdown();
}
}
/**
* Fail a set of nodes in a cluster by calling shutdown().
*
* @param nodesToFail list of HostAndPort objects representing the nodes to fail
*/
private void failSomeNodes(final List<HostAndPort> nodesToFail) {
final ExecutorService executor = Executors.newWorkStealingPool(nodesToFail.size());
try {
final CountDownLatch latch = new CountDownLatch(nodesToFail.size());
for (final HostAndPort nodeToFail : nodesToFail) {
executor.execute(() -> {
try {
assertTrue(nodeToFail + " not in instances", instances.containsKey(nodeToFail));
instances.get(nodeToFail).shutdown();
instances.remove(nodeToFail);
} catch (final InterruptedException e) {
fail();
} finally {
latch.countDown();
}
});
}
latch.await();
} catch (final InterruptedException e) {
e.printStackTrace();
fail();
} finally {
executor.shutdown();
}
}
/**
* Verify that all nodes in the cluster are of size {@code expectedSize} and have an identical
* list of members as the seed node.
*
* @param expectedSize expected size of each cluster
* @param seedHost seed node to validate the cluster view against
*/
private void verifyCluster(final int expectedSize, final HostAndPort seedHost) {
for (final Cluster cluster : instances.values()) {
assertEquals(cluster.toString(), expectedSize, cluster.getMemberlist().size());
assertEquals(cluster.getMemberlist(), instances.get(seedHost).getMemberlist());
if (addMetadata) {
assertEquals(cluster.toString(), expectedSize, cluster.getClusterMetadata().size());
}
}
}
/**
* Verify that all nodes in the cluster are of size {@code expectedSize} and have an identical
* list of members as the seed node.
*
* @param expectedSize expected size of each cluster
*/
private void verifyClusterMetadata(final int expectedSize) {
for (final Cluster cluster : instances.values()) {
assertEquals(cluster.getClusterMetadata().size(), expectedSize);
}
}
/**
* Verify the number of Cluster instances that managed to start.
*
* @param expectedSize expected size of each cluster
*/
private void verifyNumClusterInstances(final int expectedSize) {
assertEquals(expectedSize, instances.size());
}
/**
* Verify whether the cluster has converged {@code maxTries} times with a delay of @{code intervalInMs}
* between attempts. This is used to give failure detector logic some time to kick in.
*
* @param expectedSize expected size of each cluster
* @param maxTries number of tries to checkMonitoree if the cluster has stabilized.
* @param intervalInMs the time duration between checks.
* @param seedNode the seed node to validate the cluster membership against
*/
private void waitAndVerifyAgreement(final int expectedSize, final int maxTries, final int intervalInMs,
final HostAndPort seedNode) throws InterruptedException {
int tries = maxTries;
while (--tries > 0) {
boolean ready = true;
for (final Cluster cluster : instances.values()) {
if (!(cluster.getMemberlist().size() == expectedSize
&& cluster.getMemberlist().equals(instances.get(seedNode).getMemberlist()))) {
ready = false;
}
}
if (!ready) {
Thread.sleep(intervalInMs);
} else {
break;
}
}
verifyCluster(expectedSize, seedNode);
}
// Helper that provides a list of N random nodes that have already been added to the instances map
private Set<HostAndPort> getRandomHosts(final int N) {
assert random != null;
final List<Map.Entry<HostAndPort, Cluster>> entries = new ArrayList<>(instances.entrySet());
Collections.shuffle(entries);
return random.ints(instances.size(), 0, N)
.mapToObj(i -> entries.get(i).getKey())
.collect(Collectors.toSet());
}
// Helper that provides a list of N random nodes from portStart to portEnd
private Set<HostAndPort> getRandomHosts(final int portStart, final int portEnd, final int N) {
assert random != null;
return random.ints(N, portStart, portEnd)
.mapToObj(i -> HostAndPort.fromParts("127.0.0.1", i))
.collect(Collectors.toSet());
}
// Helper to use static-failure-detectors and inject interceptors
private Cluster.Builder buildCluster(final HostAndPort host) {
Cluster.Builder builder = new Cluster.Builder(host).setRpcClientConf(clientConf);
if (useStaticFd) {
final StaticFailureDetector fd = new StaticFailureDetector(new HashSet<>());
builder = builder.setLinkFailureDetector(fd);
staticFds.put(host, fd);
}
if (serverInterceptors.containsKey(host)) {
builder = builder.setServerInterceptors(serverInterceptors.get(host));
}
if (clientInterceptors.containsKey(host)) {
builder = builder.setClientInterceptors(clientInterceptors.get(host));
}
if (addMetadata) {
builder = builder.setMetadata(Collections.singletonMap("Key", host.toString()));
}
return builder;
}
// Helper that drops the first N requests at a server of a given type
private <T, E> void dropFirstNAtServer(final HostAndPort host, final int N,
final MethodDescriptor<T, E> messageType) {
serverInterceptors.computeIfAbsent(host, (k) -> new ArrayList<>(1))
.add(new ServerDropInterceptors.FirstN<>(N, messageType));
}
// Helper that delays requests of a given type at the client
private <T, E> CountDownLatch blockAtClient(final HostAndPort host, final MethodDescriptor<T, E> messageType) {
final CountDownLatch latch = new CountDownLatch(1);
clientInterceptors.computeIfAbsent(host, (k) -> new ArrayList<>(1))
.add(new ClientInterceptors.Delayer<>(latch, messageType));
return latch;
}
// This speeds up the retry attempts during the join protocol
private void useShortJoinTimeouts() {
clientConf.RPC_TIMEOUT_MS = 100;
clientConf.RPC_JOIN_PHASE_2_TIMEOUT = 500; // use short timeouts
}
// This speeds up failure detection when using the PingPongFailureDetector
private void useFastFailureDetectionTimeouts() {
clientConf.RPC_PROBE_TIMEOUT = 200;
MembershipService.FAILURE_DETECTOR_INTERVAL_IN_MS = 200;
}
}
|
package org.neo4j.kernel.ha;
import java.util.HashMap;
import java.util.Map;
import org.neo4j.kernel.CommonFactories;
import org.neo4j.kernel.IdGeneratorFactory;
import org.neo4j.kernel.IdType;
import org.neo4j.kernel.ha.zookeeper.ZooKeeperException;
import org.neo4j.kernel.impl.nioneo.store.IdGenerator;
import org.neo4j.kernel.impl.nioneo.store.IdRange;
import org.neo4j.kernel.impl.nioneo.store.NeoStore;
public class SlaveIdGenerator implements IdGenerator
{
private static final long VALUE_REPRESENTING_NULL = -1;
public static class SlaveIdGeneratorFactory implements IdGeneratorFactory
{
private final Broker broker;
private final ResponseReceiver receiver;
private final Map<IdType, IdGenerator> generators = new HashMap<IdType, IdGenerator>();
private final IdGeneratorFactory localFactory =
CommonFactories.defaultIdGeneratorFactory();
public SlaveIdGeneratorFactory( Broker broker, ResponseReceiver receiver )
{
this.broker = broker;
this.receiver = receiver;
}
public IdGenerator open( String fileName, int grabSize, IdType idType, long highestIdInUse )
{
IdGenerator localIdGenerator = localFactory.open( fileName, grabSize,
idType, highestIdInUse );
IdGenerator generator = new SlaveIdGenerator( idType, highestIdInUse, broker, receiver,
localIdGenerator );
generators.put( idType, generator );
return generator;
}
public void create( String fileName )
{
localFactory.create( fileName );
}
public IdGenerator get( IdType idType )
{
return generators.get( idType );
}
public void updateIdGenerators( NeoStore store )
{
store.updateIdGenerators();
}
};
private final Broker broker;
private final ResponseReceiver receiver;
private volatile long highestIdInUse;
private volatile long defragCount;
private IdRangeIterator idQueue = new IdRangeIterator( new IdRange( new long[0], 0, 0 ) );
private final IdType idType;
private final IdGenerator localIdGenerator;
public SlaveIdGenerator( IdType idType, long highestIdInUse, Broker broker,
ResponseReceiver receiver, IdGenerator localIdGenerator )
{
this.idType = idType;
this.broker = broker;
this.receiver = receiver;
this.localIdGenerator = localIdGenerator;
}
public void close()
{
this.localIdGenerator.close();
}
public void freeId( long id )
{
}
public long getHighId()
{
return Math.max( this.localIdGenerator.getHighId(), highestIdInUse );
}
public long getNumberOfIdsInUse()
{
return Math.max( this.localIdGenerator.getNumberOfIdsInUse(), highestIdInUse-defragCount );
}
public synchronized long nextId()
{
try
{
long nextId = nextLocalId();
if ( nextId == VALUE_REPRESENTING_NULL )
{
// If we dont have anymore grabbed ids from master, grab a bunch
IdAllocation allocation = broker.getMaster().first().allocateIds( idType );
nextId = storeLocally( allocation );
}
return nextId;
}
catch ( ZooKeeperException e )
{
receiver.newMaster( null, e );
throw e;
}
catch ( HaCommunicationException e )
{
receiver.newMaster( null, e );
throw e;
}
}
public IdRange nextIdBatch( int size )
{
throw new UnsupportedOperationException( "Should never be called" );
}
private long storeLocally( IdAllocation allocation )
{
this.highestIdInUse = allocation.getHighestIdInUse();
this.defragCount = allocation.getDefragCount();
this.idQueue = new IdRangeIterator( allocation.getIdRange() );
updateLocalIdGenerator();
return idQueue.next();
}
private void updateLocalIdGenerator()
{
long localHighId = this.localIdGenerator.getHighId();
if ( this.highestIdInUse > localHighId )
{
this.localIdGenerator.setHighId( this.highestIdInUse );
}
}
private long nextLocalId()
{
return this.idQueue.next();
}
public void setHighId( long id )
{
this.localIdGenerator.setHighId( id );
}
public long getDefragCount()
{
return this.defragCount;
}
private static class IdRangeIterator
{
private int position = 0;
private final long[] defrag;
private final long start;
private final int length;
IdRangeIterator( IdRange idRange )
{
this.defrag = idRange.getDefragIds();
this.start = idRange.getRangeStart();
this.length = idRange.getRangeLength();
}
long next()
{
try
{
if ( position < defrag.length )
{
return defrag[position];
}
else
{
int offset = position - defrag.length;
return ( offset < length ) ? ( start + offset ) : VALUE_REPRESENTING_NULL;
}
}
finally
{
++position;
}
}
}
}
|
// PrairieReader.java
package loci.formats.in;
import java.io.File;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Vector;
import loci.common.DataTools;
import loci.common.DateTools;
import loci.common.Location;
import loci.common.RandomAccessInputStream;
import loci.common.xml.BaseHandler;
import loci.common.xml.XMLTools;
import loci.formats.CoreMetadata;
import loci.formats.FormatException;
import loci.formats.FormatReader;
import loci.formats.FormatTools;
import loci.formats.MetadataTools;
import loci.formats.meta.MetadataStore;
import loci.formats.tiff.IFD;
import loci.formats.tiff.TiffParser;
import ome.xml.model.primitives.PositiveFloat;
import ome.xml.model.primitives.PositiveInteger;
import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;
public class PrairieReader extends FormatReader {
// -- Constants --
public static final String[] CFG_SUFFIX = {"cfg"};
public static final String[] XML_SUFFIX = {"xml"};
public static final String[] PRAIRIE_SUFFIXES = {"cfg", "xml"};
// Private tags present in Prairie TIFF files
// IMPORTANT NOTE: these are the same as Metamorph's private tags - therefore,
// it is likely that Prairie TIFF files will be incorrectly
// identified unless the XML or CFG file is specified
private static final int PRAIRIE_TAG_1 = 33628;
private static final int PRAIRIE_TAG_2 = 33629;
private static final int PRAIRIE_TAG_3 = 33630;
// -- Fields --
/** List of files in the current dataset */
private String[] files;
/** Helper reader for opening images */
private TiffReader tiff;
/** Names of the associated XML files */
private String xmlFile, cfgFile;
private boolean readXML = false, readCFG = false;
private Vector<String> f, gains, offsets;
private double pixelSizeX, pixelSizeY;
private String date, laserPower;
private String microscopeModel;
private String objectiveManufacturer;
private PositiveInteger magnification;
private String immersion;
private Double lensNA;
private Double waitTime;
private Vector<Double> positionX = new Vector<Double>();
private Vector<Double> positionY = new Vector<Double>();
private Vector<Double> positionZ = new Vector<Double>();
private Vector<String> channels = new Vector<String>();
private Hashtable<String, Double> relativeTimes =
new Hashtable<String, Double>();
private Double zoom;
// -- Constructor --
/** Constructs a new Prairie TIFF reader. */
public PrairieReader() {
super("Prairie TIFF", new String[] {"tif", "tiff", "cfg", "xml"});
domains = new String[] {FormatTools.LM_DOMAIN};
hasCompanionFiles = true;
datasetDescription = "One .xml file, one .cfg file, and one or more " +
".tif/.tiff files";
}
// -- IFormatReader API methods --
/* @see loci.formats.IFormatReader#isSingleFile(String) */
public boolean isSingleFile(String id) throws FormatException, IOException {
return false;
}
/* @see loci.formats.IFormatReader#isThisType(String, boolean) */
public boolean isThisType(String name, boolean open) {
if (!open) return false; // not allowed to touch the file system
Location file = new Location(name).getAbsoluteFile();
Location parent = file.getParentFile();
String prefix = file.getName();
if (prefix.indexOf(".") != -1) {
prefix = prefix.substring(0, prefix.lastIndexOf("."));
}
if (checkSuffix(name, CFG_SUFFIX)) {
if (prefix.lastIndexOf("Config") == -1) return false;
prefix = prefix.substring(0, prefix.lastIndexOf("Config"));
}
// check for appropriately named XML file
Location xml = new Location(parent, prefix + ".xml");
while (!xml.exists() && prefix.indexOf("_") != -1) {
prefix = prefix.substring(0, prefix.lastIndexOf("_"));
xml = new Location(parent, prefix + ".xml");
}
boolean validXML = false;
try {
RandomAccessInputStream xmlStream =
new RandomAccessInputStream(xml.getAbsolutePath());
validXML = isThisType(xmlStream);
xmlStream.close();
}
catch (IOException e) {
LOGGER.trace("Failed to check XML file's type", e);
}
return xml.exists() && super.isThisType(name, false) && validXML;
}
/* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */
public boolean isThisType(RandomAccessInputStream stream) throws IOException {
final int blockLen = (int) Math.min(1048608, stream.length());
if (!FormatTools.validStream(stream, blockLen, false)) return false;
String s = stream.readString(blockLen);
if (s.indexOf("xml") != -1 && s.indexOf("PV") != -1) return true;
TiffParser tp = new TiffParser(stream);
IFD ifd = tp.getFirstIFD();
if (ifd == null) return false;
String software = null;
try {
software = ifd.getIFDStringValue(IFD.SOFTWARE);
}
catch (FormatException exc) {
return false; // no software tag, or tag is wrong type
}
if (software == null) return false;
if (software.indexOf("Prairie") < 0) return false; // not Prairie software
return ifd.containsKey(new Integer(PRAIRIE_TAG_1)) &&
ifd.containsKey(new Integer(PRAIRIE_TAG_2)) &&
ifd.containsKey(new Integer(PRAIRIE_TAG_3));
}
/* @see loci.formats.IFormatReader#fileGroupOption(String) */
public int fileGroupOption(String id) throws FormatException, IOException {
return FormatTools.MUST_GROUP;
}
/* @see loci.formats.IFormatReader#getSeriesUsedFiles(boolean) */
public String[] getSeriesUsedFiles(boolean noPixels) {
FormatTools.assertId(currentId, true, 1);
if (noPixels) {
return new String[] {xmlFile, cfgFile};
}
Vector<String> s = new Vector<String>();
if (files != null) {
for (String file : files) {
s.add(file);
}
}
if (xmlFile != null) s.add(xmlFile);
if (cfgFile != null) s.add(cfgFile);
return s.toArray(new String[s.size()]);
}
/* @see loci.formats.IFormatReader#getOptimalTileWidth() */
public int getOptimalTileWidth() {
FormatTools.assertId(currentId, true, 1);
return tiff.getOptimalTileWidth();
}
/* @see loci.formats.IFormatReader#getOptimalTileHeight() */
public int getOptimalTileHeight() {
FormatTools.assertId(currentId, true, 1);
return tiff.getOptimalTileHeight();
}
/**
* @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int)
*/
public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h)
throws FormatException, IOException
{
FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h);
tiff.setId(files[no]);
return tiff.openBytes(0, buf, x, y, w, h);
}
/* @see loci.formats.IFormatReader#close(boolean) */
public void close(boolean fileOnly) throws IOException {
super.close(fileOnly);
if (tiff != null) tiff.close(fileOnly);
if (!fileOnly) {
xmlFile = cfgFile = null;
tiff = null;
files = null;
readXML = false;
readCFG = false;
f = gains = offsets = null;
pixelSizeX = pixelSizeY = 0;
date = laserPower = null;
microscopeModel = null;
objectiveManufacturer = null;
magnification = null;
immersion = null;
lensNA = null;
positionX.clear();
positionY.clear();
positionZ.clear();
channels.clear();
zoom = null;
waitTime = null;
relativeTimes.clear();
}
}
// -- Internal FormatReader API methods --
/* @see loci.formats.IFormatReader#initFile(String) */
protected void initFile(String id) throws FormatException, IOException {
if (metadata == null) metadata = new Hashtable();
if (core == null) core = new CoreMetadata[] {new CoreMetadata()};
if (tiff == null) {
tiff = new TiffReader();
}
if (checkSuffix(id, PRAIRIE_SUFFIXES)) {
// we have been given the XML file that lists TIFF files (best case)
if (checkSuffix(id, XML_SUFFIX)) {
LOGGER.info("Parsing XML");
super.initFile(id);
xmlFile = id;
readXML = true;
}
else if (checkSuffix(id, CFG_SUFFIX)) {
LOGGER.info("Parsing CFG");
cfgFile = id;
readCFG = true;
currentId = id;
}
f = new Vector<String>();
gains = new Vector<String>();
offsets = new Vector<String>();
String xml = XMLTools.sanitizeXML(DataTools.readFile(id)).trim();
if (checkSuffix(id, XML_SUFFIX)) {
core[0].imageCount = 0;
}
DefaultHandler handler = new PrairieHandler();
XMLTools.parseXML(xml, handler);
boolean minimumMetadata =
getMetadataOptions().getMetadataLevel() == MetadataLevel.MINIMUM;
MetadataStore store = makeFilterMetadata();
if (checkSuffix(id, XML_SUFFIX)) {
core[0].sizeT = getImageCount() / (getSizeZ() * getSizeC());
files = new String[f.size()];
f.copyInto(files);
if (tiff == null) {
tiff = new TiffReader();
}
tiff.setId(files[0]);
LOGGER.info("Populating metadata");
if (getSizeZ() == 0) core[0].sizeZ = 1;
if (getSizeT() == 0) core[0].sizeT = 1;
core[0].dimensionOrder = "XYCZT";
core[0].pixelType = FormatTools.UINT16;
core[0].rgb = false;
core[0].interleaved = false;
core[0].littleEndian = tiff.isLittleEndian();
core[0].indexed = tiff.isIndexed();
core[0].falseColor = false;
MetadataTools.populatePixels(store, this, !minimumMetadata);
if (date != null) {
date = DateTools.formatDate(date, "MM/dd/yyyy h:mm:ss a");
if (date != null) store.setImageAcquiredDate(date, 0);
}
if (!minimumMetadata) {
// link Instrument and Image
String instrumentID = MetadataTools.createLSID("Instrument", 0);
store.setInstrumentID(instrumentID, 0);
store.setImageInstrumentRef(instrumentID, 0);
if (pixelSizeX > 0) {
store.setPixelsPhysicalSizeX(new PositiveFloat(pixelSizeX), 0);
}
else {
LOGGER.warn("Expected positive value for PhysicalSizeX; got {}",
pixelSizeX);
}
if (pixelSizeY > 0) {
store.setPixelsPhysicalSizeY(new PositiveFloat(pixelSizeY), 0);
}
else {
LOGGER.warn("Expected positive value for PhysicalSizeY; got {}",
pixelSizeY);
}
for (int i=0; i<getSizeC(); i++) {
String gain = i < gains.size() ? gains.get(i) : null;
String offset = i < offsets.size() ? offsets.get(i) : null;
if (offset != null) {
try {
store.setDetectorSettingsOffset(new Double(offset), 0, i);
}
catch (NumberFormatException e) { }
}
if (gain != null) {
try {
store.setDetectorSettingsGain(new Double(gain), 0, i);
}
catch (NumberFormatException e) { }
}
// link DetectorSettings to an actual Detector
String detectorID = MetadataTools.createLSID("Detector", 0, i);
store.setDetectorID(detectorID, 0, i);
store.setDetectorSettingsID(detectorID, 0, i);
store.setDetectorType(getDetectorType("Other"), 0, i);
store.setDetectorZoom(zoom, 0, i);
if (i < channels.size()) {
store.setChannelName(channels.get(i), 0, i);
}
}
for (int i=0; i<getImageCount(); i++) {
int[] zct = getZCTCoords(i);
int index = FormatTools.getIndex(getDimensionOrder(), getSizeZ(),
1, getSizeT(), getImageCount() / getSizeC(), zct[0], 0, zct[2]);
double xPos = positionX.get(index);
double yPos = positionY.get(index);
double zPos = positionZ.get(index);
if (!Double.isNaN(xPos)) store.setPlanePositionX(xPos, 0, i);
if (!Double.isNaN(yPos)) store.setPlanePositionY(yPos, 0, i);
if (!Double.isNaN(zPos)) store.setPlanePositionZ(zPos, 0, i);
store.setPlaneDeltaT(
relativeTimes.get(String.valueOf(i + 1)), 0, i);
}
if (microscopeModel != null) {
store.setMicroscopeModel(microscopeModel, 0);
}
String objective = MetadataTools.createLSID("Objective", 0, 0);
store.setObjectiveID(objective, 0, 0);
store.setImageObjectiveSettingsID(objective, 0);
if (magnification != null) {
store.setObjectiveNominalMagnification(magnification, 0, 0);
}
store.setObjectiveManufacturer(objectiveManufacturer, 0, 0);
store.setObjectiveImmersion(getImmersion(immersion), 0, 0);
store.setObjectiveCorrection(getCorrection("Other"), 0, 0);
store.setObjectiveLensNA(lensNA, 0, 0);
if (laserPower != null) {
String laser = MetadataTools.createLSID("LightSource", 0 ,0);
store.setLaserID(laser, 0, 0);
try {
store.setLaserPower(new Double(laserPower), 0, 0);
}
catch (NumberFormatException e) { }
}
}
}
else if (checkSuffix(id, CFG_SUFFIX)) {
store.setPixelsTimeIncrement(waitTime, 0);
}
if (!readXML || !readCFG) {
File file = new File(id).getAbsoluteFile();
File parent = file.getParentFile();
String[] listing = file.exists() ? parent.list() :
Location.getIdMap().keySet().toArray(new String[0]);
for (String name : listing) {
if ((!readXML && checkSuffix(name, XML_SUFFIX)) ||
(readXML && checkSuffix(name, CFG_SUFFIX)))
{
String dir = "";
if (file.exists()) {
dir = parent.getPath();
if (!dir.endsWith(File.separator)) dir += File.separator;
}
initFile(dir + name);
}
}
}
}
else {
// we have been given a TIFF file - reinitialize with the proper XML file
if (isGroupFiles()) {
LOGGER.info("Finding XML file");
Location file = new Location(id).getAbsoluteFile();
Location parent = file.getParentFile();
String[] listing = parent.list();
for (String name : listing) {
if (checkSuffix(name, PRAIRIE_SUFFIXES)) {
initFile(new Location(parent, name).getAbsolutePath());
return;
}
}
}
else {
files = new String[] {id};
tiff.setId(files[0]);
core = tiff.getCoreMetadata();
metadataStore = tiff.getMetadataStore();
Hashtable globalMetadata = tiff.getGlobalMetadata();
for (Object key : globalMetadata.keySet()) {
addGlobalMeta(key.toString(), globalMetadata.get(key));
}
}
}
if (currentId == null) currentId = id;
}
// -- Helper classes --
/** SAX handler for parsing XML. */
public class PrairieHandler extends BaseHandler {
public void startElement(String uri, String localName, String qName,
Attributes attributes)
{
if (qName.equals("PVScan")) {
date = attributes.getValue("date");
}
else if (qName.equals("Frame")) {
String index = attributes.getValue("index");
if (index != null) {
int zIndex = Integer.parseInt(index);
if (zIndex > getSizeZ()) core[0].sizeZ++;
}
relativeTimes.put(index,
new Double(attributes.getValue("relativeTime")));
}
else if (qName.equals("File")) {
core[0].imageCount++;
File current = new File(currentId).getAbsoluteFile();
String dir = "";
if (current.exists()) {
dir = current.getPath();
dir = dir.substring(0, dir.lastIndexOf(File.separator) + 1);
}
f.add(dir + attributes.getValue("filename"));
String ch = attributes.getValue("channel");
String channelName = attributes.getValue("channelName");
if (channelName == null) channelName = ch;
if (ch != null) {
int cIndex = Integer.parseInt(ch);
if (cIndex > getSizeC() && !channels.contains(channelName)) {
core[0].sizeC++;
channels.add(channelName);
}
}
}
else if (qName.equals("Key")) {
String key = attributes.getValue("key");
String value = attributes.getValue("value");
addGlobalMeta(key, value);
if (key.equals("pixelsPerLine")) {
core[0].sizeX = Integer.parseInt(value);
}
else if (key.equals("linesPerFrame")) {
core[0].sizeY = Integer.parseInt(value);
}
else if (key.equals("micronsPerPixel_XAxis")) {
try {
pixelSizeX = Double.parseDouble(value);
}
catch (NumberFormatException e) { }
}
else if (key.equals("micronsPerPixel_YAxis")) {
try {
pixelSizeY = Double.parseDouble(value);
}
catch (NumberFormatException e) { }
}
else if (key.equals("objectiveLens")) {
String[] tokens = value.split(" ");
if (tokens.length > 0) {
objectiveManufacturer = tokens[0];
}
if (tokens.length > 1) {
String mag = tokens[1].toLowerCase().replaceAll("x", "");
try {
Integer m = new Integer(mag);
if (m > 0) {
magnification = new PositiveInteger(m);
}
else {
LOGGER.warn(
"Expected positive value for NominalMagnification; got {}",
m);
}
}
catch (NumberFormatException e) { }
}
if (tokens.length > 2) {
immersion = tokens[2];
}
}
else if (key.equals("objectiveLensNA")) {
try {
lensNA = new Double(value);
}
catch (NumberFormatException e) { }
}
else if (key.equals("imagingDevice")) {
microscopeModel = value;
}
else if (key.startsWith("pmtGain_")) gains.add(value);
else if (key.startsWith("pmtOffset_")) offsets.add(value);
else if (key.equals("laserPower_0")) laserPower = value;
else if (key.equals("positionCurrent_XAxis")) {
try {
positionX.add(new Double(value));
addGlobalMeta("X position for position #" + positionX.size(),
value);
}
catch (NumberFormatException e) {
positionX.add(Double.NaN);
}
}
else if (key.equals("positionCurrent_YAxis")) {
try {
positionY.add(new Double(value));
addGlobalMeta("Y position for position #" + positionY.size(),
value);
}
catch (NumberFormatException e) {
positionY.add(Double.NaN);
}
}
else if (key.equals("positionCurrent_ZAxis")) {
try {
positionZ.add(new Double(value));
addGlobalMeta("Z position for position #" + positionZ.size(),
value);
}
catch (NumberFormatException e) {
positionZ.add(Double.NaN);
}
}
else if (key.equals("opticalZoom")) {
try {
zoom = new Double(value);
}
catch (NumberFormatException e) { }
}
else if (key.equals("bitDepth")) {
core[0].bitsPerPixel = Integer.parseInt(value);
}
}
else if (qName.equals("PVTSeriesElementWait")) {
try {
waitTime = new Double(attributes.getValue("waitTime"));
}
catch (NumberFormatException e) { }
}
}
}
}
|
package timely;
import static com.google.common.util.concurrent.Uninterruptibles.sleepUninterruptibly;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.Socket;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import org.apache.accumulo.core.client.Connector;
import org.apache.accumulo.core.client.ZooKeeperInstance;
import org.apache.accumulo.core.client.lexicoder.DoubleLexicoder;
import org.apache.accumulo.core.client.security.tokens.PasswordToken;
import org.apache.accumulo.core.data.Key;
import org.apache.accumulo.core.data.Value;
import org.apache.accumulo.core.iterators.IteratorUtil.IteratorScope;
import org.apache.accumulo.core.security.Authorizations;
import org.apache.accumulo.minicluster.MiniAccumuloCluster;
import org.apache.accumulo.minicluster.MiniAccumuloConfig;
import org.apache.commons.io.IOUtils;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.TemporaryFolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.JavaType;
import timely.api.model.Metric;
import timely.api.model.Tag;
import timely.api.query.request.QueryRequest;
import timely.api.query.request.QueryRequest.SubQuery;
import timely.api.query.response.QueryResponse;
import timely.test.IntegrationTest;
import timely.util.JsonUtil;
@Category(IntegrationTest.class)
public class TimelyIntegrationTest {
private static final Logger LOG = LoggerFactory.getLogger(TimelyIntegrationTest.class);
private static final Long TEST_TIME = System.currentTimeMillis();
@ClassRule
public static final TemporaryFolder temp = new TemporaryFolder();
private static MiniAccumuloCluster mac = null;
private static File conf = null;
@BeforeClass
public static void beforeClass() throws Exception {
temp.create();
final MiniAccumuloConfig macConfig = new MiniAccumuloConfig(temp.newFolder("mac"), "secret");
mac = new MiniAccumuloCluster(macConfig);
mac.start();
conf = temp.newFile("config.properties");
try (FileWriter writer = new FileWriter(conf)) {
writer.write(Configuration.IP + "=127.0.0.1\n");
writer.write(Configuration.PUT_PORT + "=54321\n");
writer.write(Configuration.QUERY_PORT + "=54322\n");
writer.write(Configuration.ZOOKEEPERS + "=" + mac.getZooKeepers() + "\n");
writer.write(Configuration.INSTANCE_NAME + "=" + mac.getInstanceName() + "\n");
writer.write(Configuration.USERNAME + "=root\n");
writer.write(Configuration.PASSWORD + "=secret\n");
}
}
@AfterClass
public static void afterClass() throws Exception {
mac.stop();
}
@Before
public void setup() throws Exception {
Connector con = mac.getConnector("root", "secret");
con.tableOperations().list().forEach(t -> {
if (t.startsWith("timely")) {
try {
con.tableOperations().delete(t);
} catch (Exception e) {
}
}
});
}
@Test
public void testPut() throws Exception {
final TestServer m = new TestServer(conf);
try (Socket sock = new Socket("127.0.0.1", 54321);
PrintWriter writer = new PrintWriter(sock.getOutputStream(), true);) {
writer.write("put sys.cpu.user " + TEST_TIME + " 1.0 tag1=value1 tag2=value2\n");
writer.flush();
while (1 != m.getPutRequests().getCount()) {
Thread.sleep(5);
}
Assert.assertEquals(1, m.getPutRequests().getResponses().size());
Assert.assertEquals(Metric.class, m.getPutRequests().getResponses().get(0).getClass());
final Metric actual = (Metric) m.getPutRequests().getResponses().get(0);
final Metric expected = new Metric();
expected.setMetric("sys.cpu.user");
expected.setTimestamp(TEST_TIME);
expected.setValue(1.0);
final List<Tag> tags = new ArrayList<>();
tags.add(new Tag("tag1", "value1"));
tags.add(new Tag("tag2", "value2"));
expected.setTags(tags);
Assert.assertEquals(expected, actual);
} finally {
m.shutdown();
}
}
@Test
public void testPutMultiple() throws Exception {
final TestServer m = new TestServer(conf);
try (Socket sock = new Socket("127.0.0.1", 54321);
PrintWriter writer = new PrintWriter(sock.getOutputStream(), true);) {
writer.write("put sys.cpu.user " + TEST_TIME + " 1.0 tag1=value1 tag2=value2\n" + "put sys.cpu.idle "
+ (TEST_TIME + 1) + " 1.0 tag3=value3 tag4=value4\n");
writer.flush();
while (2 != m.getPutRequests().getCount()) {
Thread.sleep(5);
}
Assert.assertEquals(2, m.getPutRequests().getResponses().size());
Assert.assertEquals(Metric.class, m.getPutRequests().getResponses().get(0).getClass());
Metric actual = (Metric) m.getPutRequests().getResponses().get(0);
Metric expected = new Metric();
expected.setMetric("sys.cpu.user");
expected.setTimestamp(TEST_TIME);
expected.setValue(1.0);
List<Tag> tags = new ArrayList<>();
tags.add(new Tag("tag1", "value1"));
tags.add(new Tag("tag2", "value2"));
expected.setTags(tags);
Assert.assertEquals(expected, actual);
Assert.assertEquals(Metric.class, m.getPutRequests().getResponses().get(1).getClass());
actual = (Metric) m.getPutRequests().getResponses().get(1);
expected = new Metric();
expected.setMetric("sys.cpu.idle");
expected.setTimestamp(TEST_TIME + 1);
expected.setValue(1.0);
tags = new ArrayList<>();
tags.add(new Tag("tag3", "value3"));
tags.add(new Tag("tag4", "value4"));
expected.setTags(tags);
Assert.assertEquals(expected, actual);
} finally {
m.shutdown();
}
}
@Test
public void testPutInvalidTimestamp() throws Exception {
final TestServer m = new TestServer(conf);
try (Socket sock = new Socket("127.0.0.1", 54321);
PrintWriter writer = new PrintWriter(sock.getOutputStream(), true);
BufferedReader reader = new BufferedReader(new InputStreamReader(sock.getInputStream()));) {
writer.write("put sys.cpu.user " + TEST_TIME + "Z" + " 1.0 tag1=value1 tag2=value2\n");
writer.flush();
sleepUninterruptibly(1, TimeUnit.SECONDS);
Assert.assertEquals(0, m.getPutRequests().getCount());
} finally {
m.shutdown();
}
}
@Test
public void testPersistence() throws Exception {
final Server m = new Server(conf);
try {
put("sys.cpu.user " + TEST_TIME + " 1.0 tag1=value1 tag2=value2", "sys.cpu.idle " + (TEST_TIME + 1)
+ " 1.0 tag3=value3 tag4=value4", "sys.cpu.idle " + (TEST_TIME + 2)
+ " 1.0 tag3=value3 tag4=value4");
sleepUninterruptibly(5, TimeUnit.SECONDS);
} finally {
m.shutdown();
}
final ZooKeeperInstance inst = new ZooKeeperInstance(mac.getClientConfig());
final Connector connector = inst.getConnector("root", new PasswordToken("secret".getBytes(UTF_8)));
assertTrue(connector.namespaceOperations().exists("timely"));
assertTrue(connector.tableOperations().exists("timely.metrics"));
assertTrue(connector.tableOperations().exists("timely.meta"));
int count = 0;
final DoubleLexicoder valueDecoder = new DoubleLexicoder();
for (final Entry<Key, Value> entry : connector.createScanner("timely.metrics", Authorizations.EMPTY)) {
LOG.info("Entry: " + entry);
final double value = valueDecoder.decode(entry.getValue().get());
assertEquals(1.0, value, 1e-9);
count++;
}
assertEquals(6, count);
count = 0;
for (final Entry<Key, Value> entry : connector.createScanner("timely.meta", Authorizations.EMPTY)) {
LOG.info("Meta entry: " + entry);
count++;
}
assertEquals(10, count);
// count w/out versioning iterator to make sure that the optimization
// for writing is working
connector.tableOperations().removeIterator("timely.meta", "vers", EnumSet.of(IteratorScope.scan));
// wait for zookeeper propagation
sleepUninterruptibly(3, TimeUnit.SECONDS);
count = 0;
for (final Entry<Key, Value> entry : connector.createScanner("timely.meta", Authorizations.EMPTY)) {
LOG.info("Meta no vers iter: " + entry);
count++;
}
assertEquals(10, count);
}
@Test
public void testSuggest() throws Exception {
final Server m = new Server(conf);
try {
put("sys.cpu.user " + TEST_TIME + " 1.0 tag1=value1 tag2=value2", "sys.cpu.idle " + (TEST_TIME + 1)
+ " 1.0 tag3=value3 tag4=value4", "sys.cpu.idle " + (TEST_TIME + 2)
+ " 1.0 tag3=value3 tag4=value4", "zzzz 1234567892 1.0 host=localhost");
sleepUninterruptibly(10, TimeUnit.SECONDS);
String suggest = "http://localhost:54322/api/suggest?";
// Test prefix matching
String result = query(suggest + "type=metrics&q=sys&max=10");
assertEquals("[\"sys.cpu.idle\",\"sys.cpu.user\"]", result);
// Test max
result = query(suggest + "type=metrics&q=sys&max=1");
assertEquals("[\"sys.cpu.idle\"]", result);
// Test empty query
result = query(suggest + "type=metrics&max=10");
assertEquals("[\"sys.cpu.idle\",\"sys.cpu.user\",\"zzzz\"]", result);
// Test skipping over initial metrics
result = query(suggest + "type=metrics&q=z&max=10");
assertEquals("[\"zzzz\"]", result);
} finally {
m.shutdown();
}
}
@Test
public void testMetrics() throws Exception {
final Server m = new Server(conf);
try {
put("sys.cpu.user " + TEST_TIME + " 1.0 tag1=value1 tag2=value2", "sys.cpu.idle " + (TEST_TIME + 1)
+ " 1.0 tag3=value3 tag4=value4", "sys.cpu.idle " + (TEST_TIME + 2)
+ " 1.0 tag3=value3 tag4=value4", "zzzz 1234567892 1.0 host=localhost");
sleepUninterruptibly(10, TimeUnit.SECONDS);
String metrics = "http://localhost:54322/api/metrics";
// Test prefix matching
String result = query(metrics);
assertTrue(result.contains("<td>sys.cpu.user</td>"));
assertTrue(result.contains("<td>tag1=value1 tag2=value2 </td>"));
assertTrue(result.contains("<td>sys.cpu.idle</td>"));
assertTrue(result.contains("<td>tag3=value3 tag4=value4 </td>"));
assertTrue(result.contains("<td>zzzz</td>"));
assertTrue(result.contains("<td>host=localhost </td>"));
} finally {
m.shutdown();
}
}
@Test
public void testLookup() throws Exception {
final Server m = new Server(conf);
try {
put("sys.cpu.user " + TEST_TIME + " 1.0 tag1=value1 tag2=value2", "sys.cpu.user " + (TEST_TIME + 1)
+ " 1.0 tag3=value3", "sys.cpu.idle " + (TEST_TIME + 1) + " 1.0 tag3=value3 tag4=value4",
"sys.cpu.idle " + (TEST_TIME + 2) + " 1.0 tag3=value3 tag4=value4");
sleepUninterruptibly(8, TimeUnit.SECONDS);
String suggest = "http://localhost:54322/api/search/lookup?";
// Test a known query
String result = query(suggest + "m=sys.cpu.idle%7Btag3%3D*%7D");
assertTrue(result, result.indexOf("\"results\":[{\"tags\":{\"tag3\":\"value3\"}") >= 0);
// Test a fail
result = query(suggest + "m=sys.cpu.idle%7Btag3%3Dstupid%7D");
assertTrue(result.indexOf("\"results\":[]") >= 0);
// Test multiple results
result = query(suggest + "m=sys.cpu.idle%7Btag3%3D*,tag4%3D*%7D");
assertTrue(result, result.indexOf("\"results\":[{\"tags\":{\"tag3\":\"value3\"}") >= 0);
assertTrue(result, result.indexOf("{\"tags\":{\"tag4\":\"value4\"}") >= 0);
// Find a tag only in the metric that matches
result = query(suggest + "m=sys.cpu.idle%7Btag1%3D*%7D");
assertTrue(result, result.indexOf("\"results\":[]") >= 0);
} finally {
m.shutdown();
}
}
@Test
public void testQueryWithMsResolution() throws Exception {
final Server m = new Server(conf);
try {
put("sys.cpu.user " + TEST_TIME + " 1.0 tag1=value1 tag2=value2", "sys.cpu.user " + (TEST_TIME + 1)
+ " 1.0 tag3=value3", "sys.cpu.idle " + (TEST_TIME + 2) + " 1.0 tag3=value3 tag4=value4",
"sys.cpu.idle " + (TEST_TIME + 1000) + " 3.0 tag3=value3 tag4=value4");
sleepUninterruptibly(8, TimeUnit.SECONDS);
QueryRequest request = new QueryRequest();
request.setStart(TEST_TIME);
request.setEnd(TEST_TIME + 6000);
request.setMsResolution(true);
SubQuery subQuery = new SubQuery();
subQuery.setMetric("sys.cpu.idle");
subQuery.setTags(Collections.singletonMap("tag3", "value3"));
subQuery.setDownsample(Optional.of("1s-max"));
request.addQuery(subQuery);
List<QueryResponse> response = query("http://127.0.0.1:54322/api/query", request);
assertEquals(1, response.size());
Map<String, String> tags = response.get(0).getTags();
assertEquals(1, tags.size());
assertTrue(tags.containsKey("tag3"));
assertTrue(tags.get("tag3").equals("value3"));
Map<String, Object> dps = response.get(0).getDps();
assertEquals(2, dps.size());
Iterator<Entry<String, Object>> entries = dps.entrySet().iterator();
Entry<String, Object> entry = entries.next();
// We are downsampling to 1 second by default, which is why the
// times in the results end with ms of the start parameter.
assertEquals(TEST_TIME.toString(), entry.getKey());
assertEquals(1.0, entry.getValue());
entry = entries.next();
assertEquals(Long.toString(TEST_TIME + 1000), entry.getKey());
assertEquals(3.0, entry.getValue());
} finally {
m.shutdown();
}
}
@Test
public void testQueryWithoutMsResolution() throws Exception {
final Server m = new Server(conf);
try {
put("sys.cpu.user " + TEST_TIME + " 1.0 tag1=value1 tag2=value2", "sys.cpu.user " + (TEST_TIME + 1)
+ " 1.0 tag3=value3", "sys.cpu.idle " + (TEST_TIME + 2) + " 1.0 tag3=value3 tag4=value4",
"sys.cpu.idle " + (TEST_TIME + 1000) + " 3.0 tag3=value3 tag4=value4");
sleepUninterruptibly(8, TimeUnit.SECONDS);
QueryRequest request = new QueryRequest();
request.setStart(TEST_TIME);
request.setEnd(TEST_TIME + 6000);
SubQuery subQuery = new SubQuery();
subQuery.setMetric("sys.cpu.idle");
subQuery.setTags(Collections.singletonMap("tag3", "value3"));
subQuery.setDownsample(Optional.of("1s-max"));
request.addQuery(subQuery);
List<QueryResponse> response = query("http://127.0.0.1:54322/api/query", request);
assertEquals(1, response.size());
Map<String, String> tags = response.get(0).getTags();
assertEquals(1, tags.size());
assertTrue(tags.containsKey("tag3"));
assertTrue(tags.get("tag3").equals("value3"));
Map<String, Object> dps = response.get(0).getDps();
assertEquals(2, dps.size());
Iterator<Entry<String, Object>> entries = dps.entrySet().iterator();
Entry<String, Object> entry = entries.next();
assertEquals(Long.toString((TEST_TIME / 1000)), entry.getKey());
assertEquals(1.0, entry.getValue());
entry = entries.next();
assertEquals(Long.toString((TEST_TIME / 1000) + 1), entry.getKey());
assertEquals(3.0, entry.getValue());
} finally {
m.shutdown();
}
}
@Test
public void testQueryWithNoTags() throws Exception {
final Server m = new Server(conf);
try {
put("sys.cpu.user " + TEST_TIME + " 1.0 tag1=value1 tag2=value2", "sys.cpu.user " + (TEST_TIME + 1)
+ " 1.0 tag3=value3", "sys.cpu.idle " + (TEST_TIME + 2) + " 1.0 tag3=value3 tag4=value4",
"sys.cpu.idle " + (TEST_TIME + 1000) + " 3.0 tag3=value3 tag4=value4");
sleepUninterruptibly(8, TimeUnit.SECONDS);
QueryRequest request = new QueryRequest();
request.setStart(TEST_TIME);
request.setEnd(TEST_TIME + 6000);
SubQuery subQuery = new SubQuery();
subQuery.setMetric("sys.cpu.idle");
subQuery.setDownsample(Optional.of("1s-max"));
request.addQuery(subQuery);
List<QueryResponse> response = query("http://127.0.0.1:54322/api/query", request);
assertEquals(1, response.size());
Map<String, String> tags = response.get(0).getTags();
assertEquals(0, tags.size());
Map<String, Object> dps = response.get(0).getDps();
assertEquals(2, dps.size());
Iterator<Entry<String, Object>> entries = dps.entrySet().iterator();
Entry<String, Object> entry = entries.next();
assertEquals(Long.toString((TEST_TIME / 1000)), entry.getKey());
assertEquals(1.0, entry.getValue());
entry = entries.next();
assertEquals(Long.toString((TEST_TIME / 1000) + 1), entry.getKey());
assertEquals(3.0, entry.getValue());
} finally {
m.shutdown();
}
}
@Test(expected = IOException.class)
public void testQueryWithNoMatchingTags() throws Exception {
final Server m = new Server(conf);
try {
put("sys.cpu.user " + TEST_TIME + " 1.0 tag1=value1 tag2=value2 rack=r1", "sys.cpu.user " + (TEST_TIME + 1)
+ " 1.0 tag3=value3 rack=r2", "sys.cpu.idle " + (TEST_TIME + 2)
+ " 1.0 tag3=value3 tag4=value4 rack=r1", "sys.cpu.idle " + (TEST_TIME + 1000)
+ " 3.0 tag3=value3 tag4=value4 rack=r2");
sleepUninterruptibly(8, TimeUnit.SECONDS);
QueryRequest request = new QueryRequest();
request.setStart(TEST_TIME);
request.setEnd(TEST_TIME + 6000);
SubQuery subQuery = new SubQuery();
subQuery.setMetric("sys.cpu.idle");
subQuery.setTags(Collections.singletonMap("rack", "r3"));
request.addQuery(subQuery);
query("http://127.0.0.1:54322/api/query", request);
} finally {
m.shutdown();
}
}
@Test
public void testQueryWithTagWildcard() throws Exception {
final Server m = new Server(conf);
try {
put("sys.cpu.user " + TEST_TIME + " 1.0 tag1=value1 tag2=value2 rack=r1", "sys.cpu.user " + (TEST_TIME + 1)
+ " 1.0 tag3=value3 rack=r2", "sys.cpu.idle " + (TEST_TIME + 2)
+ " 1.0 tag3=value3 tag4=value4 rack=r1", "sys.cpu.idle " + (TEST_TIME + 1000)
+ " 3.0 tag3=value3 tag4=value4 rack=r2");
sleepUninterruptibly(8, TimeUnit.SECONDS);
QueryRequest request = new QueryRequest();
request.setStart(TEST_TIME);
request.setEnd(TEST_TIME + 6000);
SubQuery subQuery = new SubQuery();
subQuery.setMetric("sys.cpu.idle");
subQuery.setTags(Collections.singletonMap("rack", "r*"));
subQuery.setDownsample(Optional.of("1s-max"));
request.addQuery(subQuery);
List<QueryResponse> response = query("http://127.0.0.1:54322/api/query", request);
assertEquals(2, response.size());
QueryResponse response1 = response.get(0);
Map<String, String> tags = response1.getTags();
assertEquals(1, tags.size());
assertTrue(tags.containsKey("rack"));
assertTrue(tags.get("rack").equals("r2"));
Map<String, Object> dps = response1.getDps();
assertEquals(1, dps.size());
Iterator<Entry<String, Object>> entries = dps.entrySet().iterator();
Entry<String, Object> entry = entries.next();
assertEquals(Long.toString((TEST_TIME / 1000) + 1), entry.getKey());
assertEquals(3.0, entry.getValue());
QueryResponse response2 = response.get(1);
Map<String, String> tags2 = response2.getTags();
assertEquals(1, tags2.size());
assertTrue(tags2.containsKey("rack"));
assertTrue(tags2.get("rack").equals("r1"));
Map<String, Object> dps2 = response2.getDps();
assertEquals(1, dps2.size());
Iterator<Entry<String, Object>> entries2 = dps2.entrySet().iterator();
Entry<String, Object> entry2 = entries2.next();
assertEquals(Long.toString((TEST_TIME / 1000)), entry2.getKey());
assertEquals(1.0, entry2.getValue());
} finally {
m.shutdown();
}
}
@Test
public void testQueryWithTagWildcard2() throws Exception {
final Server m = new Server(conf);
try {
put("sys.cpu.user " + TEST_TIME + " 1.0 tag1=value1 tag2=value2 rack=r1", "sys.cpu.user " + (TEST_TIME + 1)
+ " 1.0 tag3=value3 rack=r2", "sys.cpu.idle " + (TEST_TIME + 2)
+ " 1.0 tag3=value3 tag4=value4 rack=r1", "sys.cpu.idle " + (TEST_TIME + 1000)
+ " 3.0 tag3=value3 tag4=value4 rack=r2");
sleepUninterruptibly(8, TimeUnit.SECONDS);
QueryRequest request = new QueryRequest();
request.setStart(TEST_TIME);
request.setEnd(TEST_TIME + 6000);
SubQuery subQuery = new SubQuery();
subQuery.setMetric("sys.cpu.idle");
subQuery.setTags(Collections.singletonMap("rack", "*"));
subQuery.setDownsample(Optional.of("1s-max"));
request.addQuery(subQuery);
List<QueryResponse> response = query("http://127.0.0.1:54322/api/query", request);
assertEquals(2, response.size());
QueryResponse response1 = response.get(0);
Map<String, String> tags = response1.getTags();
assertEquals(1, tags.size());
assertTrue(tags.containsKey("rack"));
assertTrue(tags.get("rack").equals("r2"));
Map<String, Object> dps = response1.getDps();
assertEquals(1, dps.size());
Iterator<Entry<String, Object>> entries = dps.entrySet().iterator();
Entry<String, Object> entry = entries.next();
assertEquals(Long.toString((TEST_TIME / 1000) + 1), entry.getKey());
assertEquals(3.0, entry.getValue());
QueryResponse response2 = response.get(1);
Map<String, String> tags2 = response2.getTags();
assertEquals(1, tags2.size());
assertTrue(tags2.containsKey("rack"));
assertTrue(tags2.get("rack").equals("r1"));
Map<String, Object> dps2 = response2.getDps();
assertEquals(1, dps2.size());
Iterator<Entry<String, Object>> entries2 = dps2.entrySet().iterator();
Entry<String, Object> entry2 = entries2.next();
assertEquals(Long.toString((TEST_TIME / 1000)), entry2.getKey());
assertEquals(1.0, entry2.getValue());
} finally {
m.shutdown();
}
}
private void put(String... lines) throws Exception {
StringBuffer format = new StringBuffer();
for (String line : lines) {
format.append("put ");
format.append(line);
format.append("\n");
}
try (Socket sock = new Socket("127.0.0.1", 54321);
PrintWriter writer = new PrintWriter(sock.getOutputStream(), true);) {
writer.write(format.toString());
writer.flush();
}
}
private String query(String getRequest) throws Exception {
URL url = new URL(getRequest);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
int responseCode = con.getResponseCode();
assertEquals(200, responseCode);
String result = IOUtils.toString(con.getInputStream(), UTF_8);
LOG.info("Result is {}", result);
return result;
}
private List<QueryResponse> query(String location, QueryRequest request) throws Exception {
URL url = new URL(location);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setRequestProperty("Content-Type", "application/json");
String requestJSON = JsonUtil.getObjectMapper().writeValueAsString(request);
con.setRequestProperty("Content-Length", String.valueOf(requestJSON.length()));
OutputStream wr = con.getOutputStream();
wr.write(requestJSON.getBytes(UTF_8));
int responseCode = con.getResponseCode();
String result = IOUtils.toString(con.getInputStream(), UTF_8);
LOG.info("Result is {}", result);
assertEquals(200, responseCode);
JavaType type = JsonUtil.getObjectMapper().getTypeFactory()
.constructCollectionType(List.class, QueryResponse.class);
return JsonUtil.getObjectMapper().readValue(result, type);
}
}
|
package com.parc.ccn.data.security;
import java.sql.Timestamp;
import java.util.Arrays;
import javax.xml.stream.XMLStreamException;
import com.parc.ccn.data.util.DataUtils;
import com.parc.ccn.data.util.GenericXMLEncodable;
import com.parc.ccn.data.util.XMLDecoder;
import com.parc.ccn.data.util.XMLEncodable;
import com.parc.ccn.data.util.XMLEncoder;
public class LinkAuthenticator extends GenericXMLEncodable implements XMLEncodable, Comparable<LinkAuthenticator> {
public static final String LINK_AUTHENTICATOR_ELEMENT = "LinkAuthenticator";
public static final String NAME_COMPONENT_COUNT_ELEMENT = "NameComponentCount";
protected static final String TIMESTAMP_ELEMENT = "Timestamp";
protected static final String CONTENT_TYPE_ELEMENT = "Type";
protected static final String CONTENT_DIGEST_ELEMENT = "ContentDigest";
protected PublisherID _publisher = null;
protected Integer _nameComponentCount = null;
protected Timestamp _timestamp = null;
protected SignedInfo.ContentType _type = null;
protected byte [] _contentDigest = null; // encoded DigestInfo
public LinkAuthenticator(
PublisherID publisher,
Integer nameComponentCount,
Timestamp timestamp,
SignedInfo.ContentType type,
byte [] contentDigest) {
super();
this._publisher = publisher;
this._nameComponentCount = nameComponentCount;
if (null != timestamp) {
// Lower resolution of time to only what we can represent on the wire;
// this allows decode(encode(timestamp)) == timestamp
this._timestamp = DataUtils.roundTimestamp(timestamp);
}
this._type = type;
this._contentDigest = contentDigest;
}
public LinkAuthenticator(PublisherID publisher) {
super();
this._publisher = publisher;
}
public LinkAuthenticator() {}
public boolean empty() {
return (emptyPublisher() &&
emptyNameComponentCount() &&
emptyTimestamp() &&
emptyContentType() &&
emptyContentDigest());
}
public boolean emptyPublisher() {
if ((null != publisherID()) && (0 != publisher().length))
return false;
return true;
}
public boolean emptyNameComponentCount() {
return (null == _nameComponentCount);
}
public boolean emptyContentDigest() {
if ((null != contentDigest()) && (0 != contentDigest().length))
return false;
return true;
}
public boolean emptyContentType() {
return (null == _type);
}
public boolean emptyTimestamp() {
return (null == _timestamp);
}
public byte[] contentDigest() {
return _contentDigest;
}
public void contentDigest(byte[] hash) {
_contentDigest = hash;
}
public byte[] publisher() {
return _publisher.id();
}
public PublisherID.PublisherType publisherType() {
return _publisher.type();
}
public PublisherID publisherID() {
return _publisher;
}
public void publisher(byte[] publisher, PublisherID.PublisherType publisherType) {
this._publisher = new PublisherID(publisher, publisherType);
}
public int nameComponentCount() { return _nameComponentCount; }
public void nameComponentCount(int nameComponentCount) { _nameComponentCount = new Integer(nameComponentCount); }
public void clearNameComponentCount() { _nameComponentCount = null; }
public Timestamp timestamp() {
return _timestamp;
}
public void timestamp(Timestamp timestamp) {
if (null != timestamp) {
// Lower resolution of time to only what we can represent on the wire;
// this allows decode(encode(timestamp)) == timestamp
this._timestamp = DataUtils.roundTimestamp(timestamp);
}
}
public SignedInfo.ContentType type() {
return _type;
}
public void type(SignedInfo.ContentType type) {
this._type = type;
}
public void decode(XMLDecoder decoder) throws XMLStreamException {
decoder.readStartElement(LINK_AUTHENTICATOR_ELEMENT);
if (PublisherID.peek(decoder)) {
_publisher = new PublisherID();
_publisher.decode(decoder);
}
if (decoder.peekStartElement(NAME_COMPONENT_COUNT_ELEMENT)) {
_nameComponentCount = decoder.readIntegerElement(NAME_COMPONENT_COUNT_ELEMENT);
}
if (decoder.peekStartElement(TIMESTAMP_ELEMENT)) {
_timestamp = decoder.readDateTime(TIMESTAMP_ELEMENT);
}
if (decoder.peekStartElement(CONTENT_TYPE_ELEMENT)) {
String strType = decoder.readUTF8Element(CONTENT_TYPE_ELEMENT);
_type = SignedInfo.nameToType(strType);
if (null == _type) {
throw new XMLStreamException("Cannot parse authenticator type: " + strType);
}
}
if (decoder.peekStartElement(CONTENT_DIGEST_ELEMENT)) {
_contentDigest = decoder.readBinaryElement(CONTENT_DIGEST_ELEMENT);
if (null == _contentDigest) {
throw new XMLStreamException("Cannot parse content hash.");
}
}
decoder.readEndElement();
}
public void encode(XMLEncoder encoder) throws XMLStreamException {
if (!validate()) {
throw new XMLStreamException("Cannot encode " + this.getClass().getName() + ": field values missing.");
}
encoder.writeStartElement(LINK_AUTHENTICATOR_ELEMENT);
if (!emptyPublisher()) {
publisherID().encode(encoder);
}
if (!emptyNameComponentCount()) {
encoder.writeIntegerElement(NAME_COMPONENT_COUNT_ELEMENT, nameComponentCount());
}
if (!emptyTimestamp()) {
encoder.writeDateTime(TIMESTAMP_ELEMENT, timestamp());
}
if (!emptyContentType()) {
encoder.writeElement(CONTENT_TYPE_ELEMENT, SignedInfo.typeToName(type()));
}
if (!emptyContentDigest()) {
encoder.writeElement(CONTENT_DIGEST_ELEMENT, contentDigest());
}
encoder.writeEndElement();
}
public boolean validate() {
// any of the fields could be null when used
// as a partial-match pattern
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Arrays.hashCode(_contentDigest);
result = prime
* result
+ ((_nameComponentCount == null) ? 0 : _nameComponentCount
.hashCode());
result = prime * result
+ ((_publisher == null) ? 0 : _publisher.hashCode());
result = prime * result
+ ((_timestamp == null) ? 0 : _timestamp.hashCode());
result = prime * result + ((_type == null) ? 0 : _type.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;
LinkAuthenticator other = (LinkAuthenticator) obj;
if (!Arrays.equals(_contentDigest, other._contentDigest))
return false;
if (_nameComponentCount == null) {
if (other._nameComponentCount != null)
return false;
} else if (!_nameComponentCount.equals(other._nameComponentCount))
return false;
if (_publisher == null) {
if (other._publisher != null)
return false;
} else if (!_publisher.equals(other._publisher))
return false;
if (_timestamp == null) {
if (other._timestamp != null)
return false;
} else if (!_timestamp.equals(other._timestamp))
return false;
if (_type == null) {
if (other._type != null)
return false;
} else if (!_type.equals(other._type))
return false;
return true;
}
public int compareTo(LinkAuthenticator other) {
int result = 0;
if (this == other)
return 0;
if (other == null)
return -1;
result = DataUtils.compare(_contentDigest, other._contentDigest);
if (0 != result)
return result;
if (_nameComponentCount == null) {
if (other._nameComponentCount != null)
return -1;
} else {
result = _nameComponentCount.compareTo(other._nameComponentCount);
if (0 != result)
return result;
}
if (_publisher == null) {
if (other._publisher != null)
return -1;
} else {
result = _publisher.compareTo(other._publisher);
if (0 != result)
return result;
}
if (_timestamp == null) {
if (other._timestamp != null)
return -1;
} else {
result = _timestamp.compareTo(other._timestamp);
if (0 != result)
return result;
}
if (_type == null) {
if (other._type != null)
return -1;
} else {
result = _type.compareTo(other._type);
if (0 != result)
return result;
}
return 0;
}
}
|
package com.parc.ccn.security.crypto.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.Key;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1OctetString;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DEREncodable;
import org.bouncycastle.asn1.DERObject;
import org.bouncycastle.asn1.DEROutputStream;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.asn1.x509.X509Extensions;
import com.parc.ccn.data.util.DataUtils;
import com.parc.ccn.security.crypto.CCNDigestHelper;
/**
* @author D.K. Smetters
*
* Collection of crypto utility functions specific to bouncy castle.
*/
public class CryptoUtil {
public static byte [] encode(DEREncodable encodable) throws CertificateEncodingException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
DEROutputStream dos = new DEROutputStream(baos);
dos.writeObject(encodable);
dos.close();
} catch (IOException ex) {
throw new CertificateEncodingException("Cannot encode: " + ex.toString());
}
return baos.toByteArray();
}
public static DERObject decode(byte [] decodable) throws CertificateEncodingException {
DERObject dobj = null;
try {
ByteArrayInputStream bais = new ByteArrayInputStream(decodable);
ASN1InputStream dis = new ASN1InputStream(bais);
dobj = dis.readObject();
dis.close();
} catch (IOException ex) {
throw new CertificateEncodingException("Cannot encode: " + ex.toString());
}
return dobj;
}
public static PublicKey getPublicKey(SubjectPublicKeyInfo spki)
throws CertificateEncodingException, NoSuchAlgorithmException,
InvalidKeySpecException {
// Reencode SubjectPublicKeyInfo, let java decode it.
byte [] encodedKey = encode(spki);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(encodedKey);
String algorithmOID=
spki.getAlgorithmId().getObjectId().getId();
String algorithm = OIDLookup.getCipherName(algorithmOID);
if (algorithm == null) {
throw new CertificateEncodingException("Unknown key algorithm!");
}
KeyFactory fact = KeyFactory.getInstance(algorithm);
return fact.generatePublic(keySpec);
}
public static PublicKey getPublicKey(byte [] derEncodedPublicKey) throws
InvalidKeySpecException,
CertificateEncodingException, NoSuchAlgorithmException {
// Problem is, we need the algorithm identifier inside
// the key to decode it. So in essence we need to
// decode it twice.
DERObject genericObject = decode(derEncodedPublicKey);
if (!(genericObject instanceof ASN1Sequence)) {
throw new InvalidKeySpecException("This object is not a public key!");
}
// At this point it might also be a certificate, or
// any number of things.
SubjectPublicKeyInfo spki =
new SubjectPublicKeyInfo((ASN1Sequence)genericObject);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(derEncodedPublicKey);
String algorithmOID=
spki.getAlgorithmId().getObjectId().getId();
String algorithm = OIDLookup.getCipherName(algorithmOID);
if (algorithm == null) {
throw new NoSuchAlgorithmException("Unknown key algorithm: " + algorithmOID);
}
KeyFactory fact = KeyFactory.getInstance(algorithm);
return fact.generatePublic(keySpec);
}
public static X509Certificate getCertificate(byte [] encodedCert) throws CertificateException {
// Will make default provider's certificate if it has one.
CertificateFactory cf = CertificateFactory.getInstance("X.509");
return (X509Certificate)cf.generateCertificate(
new ByteArrayInputStream(encodedCert));
}
private CryptoUtil() {
super();
}
/**
* Generates a CertID -- the digest of the DER encoding
* of a java.security.cert.Certificate
*/
public static byte [] generateCertID(String digestAlg, Certificate cert) throws CertificateEncodingException {
byte [] id = null;
try {
byte [] encoding = cert.getEncoded();
id = DigestHelper.digest(digestAlg, encoding);
} catch (java.security.NoSuchAlgorithmException ex) {
// DKS --big configuration problem
throw new RuntimeException("Error: can't find " + digestAlg + "! " + ex.toString());
}
return id;
}
public static byte [] generateCertID(Certificate cert) throws CertificateEncodingException {
return generateCertID(CCNDigestHelper.DEFAULT_DIGEST_ALGORITHM, cert);
}
/**
* Generates a KeyID -- the digest of the DER encoding
* of a SubjectPublicKeyInfo, or of a raw encoding of a
* symmetric key.
*/
public static byte [] generateKeyID(String digestAlg, Key key) {
byte [] id = null;
try {
byte [] encoding = key.getEncoded();
id = DigestHelper.digest(digestAlg, encoding);
} catch (java.security.NoSuchAlgorithmException ex) {
// DKS --big configuration problem
throw new RuntimeException("Error: can't find " + digestAlg + "! " + ex.toString());
}
return id;
}
public static byte [] generateKeyID(Key key) {
return generateKeyID(CCNDigestHelper.DEFAULT_DIGEST_ALGORITHM, key);
}
public static String getKeyIDString(String digestAlg, Key key) {
byte[] keyID = generateKeyID(digestAlg, key);
return DataUtils.printHexBytes(keyID);
}
public static String getKeyIDString(Key key) {
return getKeyIDString(CCNDigestHelper.DEFAULT_DIGEST_ALGORITHM,key);
}
/**
* Get the keyID from a CA certificate to use as the key id in an AuthorityKeyIdentifier
* extension for certificates issued by that CA. This should come out of the SubjectKeyIdentifier
* extension of the certificate if present. If that extension is missing, this function
* will return null, and generateKeyID can be used to generate a new key id.
**/
public static byte [] getKeyIDFromCertificate(X509Certificate issuerCert)
throws IOException, CertificateEncodingException {
byte [] keyIDExtensionValue = issuerCert.getExtensionValue(X509Extensions.SubjectKeyIdentifier.toString());
if (null == keyIDExtensionValue)
return null;
// extension should decode to an OCTET STRING containing the key id.
DERObject decodedValue = decode(keyIDExtensionValue);
if (!(decodedValue instanceof ASN1OctetString)) {
throw new CertificateEncodingException("Cannot parse SubjectKeyIdentifier extension!");
}
// now decode the inner octet string to get key ID
DERObject keyID = decode(((ASN1OctetString)decodedValue).getOctets());
if (!(keyID instanceof ASN1OctetString)) {
throw new CertificateEncodingException("Cannot parse SubjectKeyIdentifier extension!");
}
return ((ASN1OctetString)keyID).getOctets();
}
}
|
package test.ccn.library.io;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.DigestInputStream;
import java.security.DigestOutputStream;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.util.Random;
import java.util.logging.Level;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.IllegalBlockSizeException;
import javax.xml.stream.XMLStreamException;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import com.parc.ccn.Library;
import com.parc.ccn.config.SystemConfiguration;
import com.parc.ccn.data.ContentName;
import com.parc.ccn.data.ContentObject;
import com.parc.ccn.data.security.PublisherPublicKeyDigest;
import com.parc.ccn.data.security.SignedInfo;
import com.parc.ccn.data.security.SignedInfo.ContentType;
import com.parc.ccn.library.CCNLibrary;
import com.parc.ccn.library.io.CCNInputStream;
import com.parc.ccn.library.io.CCNOutputStream;
import com.parc.ccn.library.profiles.SegmentationProfile;
import com.parc.ccn.library.profiles.VersioningProfile;
import com.parc.ccn.security.crypto.ContentKeys;
public class CCNSecureInputStreamTest {
static ContentName defaultStreamName;
static ContentName encrName;
static int encrLength;
static ContentKeys encrKeys;
static byte [] encrDigest;
static byte [] encrData;
static CCNLibrary outputLibrary;
static CCNLibrary inputLibrary;
static final int BUF_SIZE = 4096;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
Library.logger().setLevel(Level.FINER);
SystemConfiguration.setDebugFlag(SystemConfiguration.DEBUGGING_FLAGS.DEBUG_SIGNATURES, true);
Random randBytes = new Random(); // doesn't need to be secure
outputLibrary = CCNLibrary.open();
inputLibrary = CCNLibrary.open();
// Write a set of output
defaultStreamName = ContentName.fromNative("/test/stream/versioning/LongOutput.bin");
encrName = VersioningProfile.versionName(defaultStreamName);
encrLength = 25*1024+301;
encrKeys = ContentKeys.generateRandomKeys();
encrDigest = writeFileFloss(encrName, encrLength, randBytes, encrKeys);
}
/**
* Trick to get around lack of repo. We want the test below to read data out of
* ccnd. Problem is to do that, we have to get it into ccnd. This pre-loads
* ccnd with data by "flossing" it -- starting up a reader thread that will
* pull our generated data into ccnd for us, where it will wait till we read
* it back out.
* @param completeName
* @param fileLength
* @param randBytes
* @return
* @throws XMLStreamException
* @throws IOException
* @throws NoSuchAlgorithmException
* @throws InterruptedException
*/
public static byte [] writeFileFloss(ContentName completeName, int fileLength, Random randBytes, ContentKeys keys) throws XMLStreamException, IOException, NoSuchAlgorithmException, InterruptedException {
CCNOutputStream stockOutputStream = new CCNOutputStream(completeName, null, null, null, keys, outputLibrary);
DigestOutputStream digestStreamWrapper = new DigestOutputStream(stockOutputStream, MessageDigest.getInstance("SHA1"));
ByteArrayOutputStream data = new ByteArrayOutputStream();
byte [] bytes = new byte[BUF_SIZE];
int elapsed = 0;
int nextBufSize = 0;
boolean firstBuf = true;
System.out.println("Writing file: " + completeName + " bytes: " + fileLength);
final double probFlush = .1;
while (elapsed < fileLength) {
nextBufSize = ((fileLength - elapsed) > BUF_SIZE) ? BUF_SIZE : (fileLength - elapsed);
randBytes.nextBytes(bytes);
digestStreamWrapper.write(bytes, 0, nextBufSize);
data.write(bytes, 0, nextBufSize);
elapsed += nextBufSize;
if (firstBuf) {
startReader(completeName, fileLength, keys);
firstBuf = false;
}
System.out.println(completeName + " wrote " + elapsed + " out of " + fileLength + " bytes.");
if (randBytes.nextDouble() < probFlush) {
System.out.println("Flushing buffers.");
digestStreamWrapper.flush();
}
}
digestStreamWrapper.close();
System.out.println("Finished writing file " + completeName);
encrData = data.toByteArray();
return digestStreamWrapper.getMessageDigest().digest();
}
public static Thread startReader(final ContentName completeName, final int fileLength, final ContentKeys keys) {
Thread t = new Thread(){
public void run() {
try {
readFile(completeName, fileLength, keys);
} catch (Exception e) {
e.printStackTrace();
Assert.fail("Class setup failed! " + e.getClass().getName() + ": " + e.getMessage());
}
}
};
t.start();
return t;
}
public static byte [] readFile(ContentName completeName, int fileLength, ContentKeys keys) throws XMLStreamException, IOException {
CCNInputStream inputStream = new CCNInputStream(completeName, null, null, keys, null);
System.out.println("Reading file : " + completeName);
return readFile(inputStream, fileLength);
}
public static byte [] readFile(InputStream inputStream, int fileLength) throws IOException, XMLStreamException {
System.out.println("Entering READFILE");
DigestInputStream dis = null;
try {
dis = new DigestInputStream(inputStream, MessageDigest.getInstance("SHA1"));
} catch (NoSuchAlgorithmException e) {
Library.logger().severe("No SHA1 available!");
Assert.fail("No SHA1 available!");
}
int elapsed = 0;
int read = 0;
byte [] bytes = new byte[BUF_SIZE];
while (elapsed < fileLength) {
System.out.println("elapsed = " + elapsed + " fileLength=" + fileLength);
read = dis.read(bytes);
System.out.println("read returned " + read + ". elapsed = " + elapsed);
if (read < 0) {
System.out.println("EOF read at " + elapsed + " bytes out of " + fileLength);
break;
} else if (read == 0) {
System.out.println("0 bytes read at " + elapsed + " bytes out of " + fileLength);
try {
Thread.sleep(10);
} catch (InterruptedException e) {
}
}
elapsed += read;
System.out.println(" read " + elapsed + " bytes out of " + fileLength);
}
return dis.getMessageDigest().digest();
}
/**
* Test cipher encryption & decryption work
*/
@Test
public void cipherEncryptDecrypt() throws InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
Cipher c = encrKeys.getSegmentEncryptionCipher(null, 0);
byte [] d = c.doFinal(encrData);
c = encrKeys.getSegmentDecryptionCipher(null, 0);
d = c.doFinal(d);
// check we get identical data back out
Assert.assertArrayEquals(encrData, d);
}
/**
* Test cipher stream encryption & decryption work
* @throws IOException
*/
@Test
public void cipherStreamEncryptDecrypt() throws InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, IOException {
Cipher c = encrKeys.getSegmentEncryptionCipher(null, 0);
InputStream is = new ByteArrayInputStream(encrData, 0, encrData.length);
is = new CipherInputStream(is, c);
byte [] cipherText = new byte[4096];
for(int total = 0, res = 0; res >= 0 && total < 4096; total+=res)
res = is.read(cipherText,total,4096-total);
c = encrKeys.getSegmentDecryptionCipher(null, 0);
is = new ByteArrayInputStream(cipherText);
is = new CipherInputStream(is, c);
byte [] output = new byte[4096];
for(int total = 0, res = 0; res >= 0 && total < 4096; total+=res)
res = is.read(output,total,4096-total);
// check we get identical data back out
byte [] input = new byte[Math.min(4096, encrLength)];
System.arraycopy(encrData, 0, input, 0, input.length);
Assert.assertArrayEquals(input, output);
}
/**
* Test content encryption & decryption work
* @throws IOException
*/
@Test
public void contentEncryptDecrypt() throws InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, IOException {
// create an encrypted content block
Cipher c = encrKeys.getSegmentEncryptionCipher(null, 0);
InputStream is = new ByteArrayInputStream(encrData, 0, encrData.length);
is = new CipherInputStream(is, c);
ContentName rootName = SegmentationProfile.segmentRoot(encrName);
PublisherPublicKeyDigest publisher = outputLibrary.getDefaultPublisher();
PrivateKey signingKey = outputLibrary.keyManager().getSigningKey(publisher);
byte [] finalBlockID = SegmentationProfile.getSegmentID(1);
ContentObject co = new ContentObject(SegmentationProfile.segmentName(rootName, 0),
new SignedInfo(publisher, null, ContentType.ENCR, outputLibrary.keyManager().getKeyLocator(signingKey), new Integer(300), finalBlockID),
is, 4096);
// attempt to decrypt the data
c = encrKeys.getSegmentDecryptionCipher(null, 0);
is = new CipherInputStream(new ByteArrayInputStream(co.content()), c);
byte [] output = new byte[co.contentLength()];
for(int total = 0, res = 0; res >= 0 && total < output.length; total+=res)
res = is.read(output, total, output.length-total);
// check we get identical data back out
byte [] input = new byte[Math.min(4096, co.contentLength())];
System.arraycopy(encrData, 0, input, 0, input.length);
Assert.assertArrayEquals(input, output);
}
/**
* Test basic stream encryption & decryption work, and that using different keys for decryption fails
*/
@Test
public void streamEncryptDecrypt() throws XMLStreamException, IOException {
// check we get identical data back out
System.out.println("Reading CCNInputStream from "+encrName);
CCNInputStream vfirst = new CCNInputStream(encrName, null, null, encrKeys, inputLibrary);
byte [] readDigest = readFile(vfirst, encrLength);
Assert.assertArrayEquals(encrDigest, readDigest);
// check things fail if we use different keys
ContentKeys keys2 = ContentKeys.generateRandomKeys();
CCNInputStream v2 = new CCNInputStream(encrName, null, null, keys2, inputLibrary);
byte [] readDigest2 = readFile(v2, encrLength);
Assert.assertFalse(encrDigest.equals(readDigest2));
}
/**
* seek forward, read, seek back, read and check the results
* do it for different size parts of the data
*/
@Test
public void seeking() throws XMLStreamException, IOException, NoSuchAlgorithmException {
// check really small seeks/reads (smaller than 1 Cipher block)
doSeeking(10);
// check small seeks (but bigger than 1 Cipher block)
doSeeking(600);
// check large seeks (multiple ContentObjects)
doSeeking(4096*5+350);
}
private void doSeeking(int length) throws XMLStreamException, IOException, NoSuchAlgorithmException {
System.out.println("Reading CCNInputStream from "+encrName);
CCNInputStream i = new CCNInputStream(encrName, null, null, encrKeys, inputLibrary);
// make sure we start mid ContentObject and past the first Cipher block
int start = ((int) (encrLength*0.3) % 4096) +600;
i.seek(start);
readAndCheck(i, start, length);
i.seek(start);
readAndCheck(i, start, length);
}
private void readAndCheck(CCNInputStream i, int start, int length)
throws IOException, XMLStreamException, NoSuchAlgorithmException {
byte [] origData = new byte[length];
System.arraycopy(encrData, start, origData, 0, length);
byte [] readData = new byte[length];
i.read(readData);
Assert.assertArrayEquals(origData, readData);
}
/**
* Test that skipping while reading an encrypted stream works
* Tries small/medium/large skips
*/
@Test
public void skipping() throws XMLStreamException, IOException, NoSuchAlgorithmException {
// read some data, skip some data, read some more data
System.out.println("Reading CCNInputStream from "+encrName);
CCNInputStream inStream = new CCNInputStream(encrName, null, null, encrKeys, inputLibrary);
int start = (int) (encrLength*0.3);
// check first part reads correctly
readAndCheck(inStream, 0, start);
// skip a short bit (less than 1 cipher block)
inStream.skip(10);
start += 10;
// check second part reads correctly
readAndCheck(inStream, start, 100);
start += 100;
// skip a medium bit (more than than 1 cipher block)
inStream.skip(600);
start += 600;
// check third part reads correctly
readAndCheck(inStream, start, 600);
start += 600;
// skip a bug bit (more than than 1 Content object)
inStream.skip(600+4096*2);
start += 600+4096*2;
// check fourth part reads correctly
readAndCheck(inStream, start, 600);
}
}
|
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:19-07-02");
this.setApiVersion("15.2.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* @param partnerId Impersonated partner id
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* @param ks Kaltura API session
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param sessionId Kaltura API session
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param responseProfile Response profile - this attribute will be automatically unset after every API call.
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
}
|
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:20-08-14");
this.setApiVersion("16.8.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* @param partnerId Impersonated partner id
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* @param ks Kaltura API session
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param sessionId Kaltura API session
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param responseProfile Response profile - this attribute will be automatically unset after every API call.
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
}
|
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platforms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:21-05-13");
this.setApiVersion("17.1.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* @param partnerId Impersonated partner id
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* @param ks Kaltura API session
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param sessionId Kaltura API session
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param responseProfile Response profile - this attribute will be automatically unset after every API call.
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
}
|
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:18-01-06");
this.setApiVersion("3.3.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* @param partnerId Impersonated partner id
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* @param ks Kaltura API session
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param sessionId Kaltura API session
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param responseProfile Response profile - this attribute will be automatically unset after every API call.
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
}
|
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platforms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:22-07-14");
this.setApiVersion("18.9.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* @param partnerId Impersonated partner id
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* @param ks Kaltura API session
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param sessionId Kaltura API session
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param responseProfile Response profile - this attribute will be automatically unset after every API call.
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
}
|
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platforms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:21-12-19");
this.setApiVersion("17.16.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* @param partnerId Impersonated partner id
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* @param ks Kaltura API session
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param sessionId Kaltura API session
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param responseProfile Response profile - this attribute will be automatically unset after every API call.
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
}
|
/*
* $Id: Organ.java,v 1.21 2009-06-04 18:49:09 pandyas Exp $
*
* $Log: not supported by cvs2svn $
* Revision 1.20 2009/06/04 16:59:08 pandyas
* getting ready for QA build
*
* Revision 1.19 2009/06/04 15:03:07 pandyas
* testing preferred description in new methods
*
* Revision 1.18 2009/05/20 17:07:20 pandyas
* modified for gforge #17325 Upgrade caMOD to use caBIO 4.x and EVS 4.x to get data
*
* Revision 1.17 2006/10/31 17:55:24 pandyas
* Organ returns the EVS Preferred displayName
* if the conceptCode = 000000, then return the name just like disease. This is needed for JAX data from MTB.
*
* Revision 1.16 2006/04/17 19:13:46 pandyas
* caMod 2.1 OM changes and added log/id header
*
*/
package gov.nih.nci.camod.domain;
import gov.nih.nci.camod.util.EvsTreeUtil;
import java.io.Serializable;
import gov.nih.nci.camod.util.Duplicatable;
import gov.nih.nci.camod.util.HashCodeUtil;
public class Organ extends BaseObject implements Comparable, Serializable, Duplicatable
{
private static final long serialVersionUID = 3259095453799404851L;
private String name;
private String conceptCode;
/**
* @return Returns the name.
*/
public String getName()
{
return name;
}
/**
* @param name
* The name to set.
*/
public void setName(String name)
{
this.name = name;
}
/**
* @return Returns the conceptCode.
*/
public String getConceptCode()
{
return conceptCode;
}
/**
* @param conceptCode
* The conceptCode to set.
*/
public void setConceptCode(String conceptCode)
{
this.conceptCode = conceptCode;
}
/**
* @return Returns the EVS Preferred displayName
* if the conceptCode = 000000, then return the name
* Added code to get the name when EVS is down *
*/
public String getEVSPreferredDescription()
{
String thePreferedDesc = null;
if ("000000".equals(conceptCode) || "C000000".equals(conceptCode))
{
thePreferedDesc = name;
}
else
{
String conceptDetails = EvsTreeUtil.getConceptDetails(null, conceptCode);
if(conceptDetails != null && conceptDetails.length() > 0){
thePreferedDesc = conceptDetails;
System.out.println("Organ retrieved from EVS: " + thePreferedDesc);
} else {
thePreferedDesc = name;
System.out.println("Organ retrieved from caMOD: " + thePreferedDesc);
}
}
return thePreferedDesc;
}
/**
* @see java.lang.Object#toString()
*/
public String toString()
{
String result = super.toString() + " - ";
result += this.getName();
return result;
}
public boolean equals(Object o)
{
if (!super.equals(o))
return false;
if (!(this.getClass().isInstance(o)))
return false;
final Organ obj = (Organ) o;
if (HashCodeUtil.notEqual(this.getName(), obj.getName()))
return false;
return true;
}
public int hashCode()
{
int result = HashCodeUtil.SEED;
result = HashCodeUtil.hash(result, this.getName());
return result + super.hashCode();
}
public int compareTo(Object o)
{
// compare by evs description name if possible, otherwise organ name
if ((o instanceof Organ) && (this.getEVSPreferredDescription() != null) && (((Organ) o).getEVSPreferredDescription() != null))
{
int result = this.getEVSPreferredDescription().compareTo(((Organ) o).getEVSPreferredDescription());
if (result != 0)
{
return result;
}
}
else if ((o instanceof Organ) && (this.getName() != null) && (((Organ) o).getName() != null))
{
int result = this.getName().compareTo(((Organ) o).getName());
if (result != 0)
{
return result;
}
}
return super.compareTo(o);
}
}
|
package br.senac.tads.pi3a.dao;
import br.senac.tads.pi3a.model.Cliente;
/**
*
* @author Elton
*/
public class DaoCliente extends AbstractDao {
public DaoCliente() {
}
public DaoCliente(Cliente model) {
super(model);
}
}
|
package org.spongycastle.openpgp;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.spongycastle.bcpg.BCPGInputStream;
import org.spongycastle.bcpg.PacketTags;
import org.spongycastle.bcpg.PublicSubkeyPacket;
import org.spongycastle.bcpg.SecretKeyPacket;
import org.spongycastle.bcpg.SecretSubkeyPacket;
import org.spongycastle.bcpg.TrustPacket;
import org.spongycastle.openpgp.operator.KeyFingerPrintCalculator;
import org.spongycastle.openpgp.operator.PBESecretKeyDecryptor;
import org.spongycastle.openpgp.operator.PBESecretKeyEncryptor;
import org.spongycastle.util.Iterable;
/**
* Class to hold a single master secret key and its subkeys.
* <p>
* Often PGP keyring files consist of multiple master keys, if you are trying to process
* or construct one of these you should use the {@link PGPSecretKeyRingCollection} class.
*/
public class PGPSecretKeyRing
extends PGPKeyRing
implements Iterable<PGPSecretKey>
{
List keys;
List extraPubKeys;
PGPSecretKeyRing(List keys)
{
this(keys, new ArrayList());
}
private PGPSecretKeyRing(List keys, List extraPubKeys)
{
this.keys = keys;
this.extraPubKeys = extraPubKeys;
}
public PGPSecretKeyRing(
byte[] encoding,
KeyFingerPrintCalculator fingerPrintCalculator)
throws IOException, PGPException
{
this(new ByteArrayInputStream(encoding), fingerPrintCalculator);
}
public PGPSecretKeyRing(
InputStream in,
KeyFingerPrintCalculator fingerPrintCalculator)
throws IOException, PGPException
{
this.keys = new ArrayList();
this.extraPubKeys = new ArrayList();
BCPGInputStream pIn = wrap(in);
int initialTag = pIn.nextPacketTag();
if (initialTag != PacketTags.SECRET_KEY && initialTag != PacketTags.SECRET_SUBKEY)
{
throw new IOException(
"secret key ring doesn't start with secret key tag: " +
"tag 0x" + Integer.toHexString(initialTag));
}
SecretKeyPacket secret = (SecretKeyPacket)pIn.readPacket();
// ignore GPG comment packets if found.
while (pIn.nextPacketTag() == PacketTags.EXPERIMENTAL_2)
{
pIn.readPacket();
}
TrustPacket trust = readOptionalTrustPacket(pIn);
// revocation and direct signatures
List keySigs = readSignaturesAndTrust(pIn);
List ids = new ArrayList();
List idTrusts = new ArrayList();
List idSigs = new ArrayList();
readUserIDs(pIn, ids, idTrusts, idSigs);
keys.add(new PGPSecretKey(secret, new PGPPublicKey(secret.getPublicKeyPacket(), trust, keySigs, ids, idTrusts, idSigs, fingerPrintCalculator)));
// Read subkeys
while (pIn.nextPacketTag() == PacketTags.SECRET_SUBKEY
|| pIn.nextPacketTag() == PacketTags.PUBLIC_SUBKEY)
{
if (pIn.nextPacketTag() == PacketTags.SECRET_SUBKEY)
{
SecretSubkeyPacket sub = (SecretSubkeyPacket)pIn.readPacket();
// ignore GPG comment packets if found.
while (pIn.nextPacketTag() == PacketTags.EXPERIMENTAL_2)
{
pIn.readPacket();
}
TrustPacket subTrust = readOptionalTrustPacket(pIn);
List sigList = readSignaturesAndTrust(pIn);
keys.add(new PGPSecretKey(sub, new PGPPublicKey(sub.getPublicKeyPacket(), subTrust, sigList, fingerPrintCalculator)));
}
else
{
PublicSubkeyPacket sub = (PublicSubkeyPacket)pIn.readPacket();
TrustPacket subTrust = readOptionalTrustPacket(pIn);
List sigList = readSignaturesAndTrust(pIn);
extraPubKeys.add(new PGPPublicKey(sub, subTrust, sigList, fingerPrintCalculator));
}
}
}
/**
* Return the public key for the master key.
*
* @return PGPPublicKey
*/
public PGPPublicKey getPublicKey()
{
return ((PGPSecretKey)keys.get(0)).getPublicKey();
}
/**
* Return the public key referred to by the passed in keyID if it
* is present.
*
* @param keyID
* @return PGPPublicKey
*/
public PGPPublicKey getPublicKey(
long keyID)
{
PGPSecretKey key = getSecretKey(keyID);
if (key != null)
{
return key.getPublicKey();
}
for (int i = 0; i != extraPubKeys.size(); i++)
{
PGPPublicKey k = (PGPPublicKey)keys.get(i);
if (keyID == k.getKeyID())
{
return k;
}
}
return null;
}
/**
* Return an iterator containing all the public keys.
*
* @return Iterator
*/
public Iterator<PGPPublicKey> getPublicKeys()
{
List pubKeys = new ArrayList();
for (Iterator it = getSecretKeys(); it.hasNext();)
{
pubKeys.add(((PGPSecretKey)it.next()).getPublicKey());
}
pubKeys.addAll(extraPubKeys);
return Collections.unmodifiableList(pubKeys).iterator();
}
/**
* Return the master private key.
*
* @return PGPSecretKey
*/
public PGPSecretKey getSecretKey()
{
return ((PGPSecretKey)keys.get(0));
}
/**
* Return an iterator containing all the secret keys.
*
* @return Iterator
*/
public Iterator<PGPSecretKey> getSecretKeys()
{
return Collections.unmodifiableList(keys).iterator();
}
public PGPSecretKey getSecretKey(
long keyId)
{
for (int i = 0; i != keys.size(); i++)
{
PGPSecretKey k = (PGPSecretKey)keys.get(i);
if (keyId == k.getKeyID())
{
return k;
}
}
return null;
}
/**
* Return an iterator of the public keys in the secret key ring that
* have no matching private key. At the moment only personal certificate data
* appears in this fashion.
*
* @return iterator of unattached, or extra, public keys.
*/
public Iterator<PGPPublicKey> getExtraPublicKeys()
{
return extraPubKeys.iterator();
}
public byte[] getEncoded()
throws IOException
{
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
this.encode(bOut);
return bOut.toByteArray();
}
public void encode(
OutputStream outStream)
throws IOException
{
for (int i = 0; i != keys.size(); i++)
{
PGPSecretKey k = (PGPSecretKey)keys.get(i);
k.encode(outStream);
}
for (int i = 0; i != extraPubKeys.size(); i++)
{
PGPPublicKey k = (PGPPublicKey)extraPubKeys.get(i);
k.encode(outStream);
}
}
/**
* Support method for Iterable where available.
*/
public Iterator<PGPSecretKey> iterator()
{
return getSecretKeys();
}
/**
* Replace the public key set on the secret ring with the corresponding key off the public ring.
*
* @param secretRing secret ring to be changed.
* @param publicRing public ring containing the new public key set.
*/
public static PGPSecretKeyRing replacePublicKeys(PGPSecretKeyRing secretRing, PGPPublicKeyRing publicRing)
{
List newList = new ArrayList(secretRing.keys.size());
for (Iterator it = secretRing.keys.iterator(); it.hasNext();)
{
PGPSecretKey sk = (PGPSecretKey)it.next();
PGPPublicKey pk = publicRing.getPublicKey(sk.getKeyID());
newList.add(PGPSecretKey.replacePublicKey(sk, pk));
}
return new PGPSecretKeyRing(newList);
}
/**
* Return a copy of the passed in secret key ring, with the private keys (where present) associated with the master key and sub keys
* are encrypted using a new password and the passed in algorithm.
*
* @param ring the PGPSecretKeyRing to be copied.
* @param oldKeyDecryptor the current decryptor based on the current password for key.
* @param newKeyEncryptor a new encryptor based on a new password for encrypting the secret key material.
* @return the updated key ring.
*/
public static PGPSecretKeyRing copyWithNewPassword(
PGPSecretKeyRing ring,
PBESecretKeyDecryptor oldKeyDecryptor,
PBESecretKeyEncryptor newKeyEncryptor)
throws PGPException
{
List newKeys = new ArrayList(ring.keys.size());
for (Iterator keys = ring.getSecretKeys(); keys.hasNext();)
{
PGPSecretKey key = (PGPSecretKey)keys.next();
if (key.isPrivateKeyEmpty())
{
newKeys.add(key);
}
else
{
newKeys.add(PGPSecretKey.copyWithNewPassword(key, oldKeyDecryptor, newKeyEncryptor));
}
}
return new PGPSecretKeyRing(newKeys, ring.extraPubKeys);
}
/**
* Returns a new key ring with the secret key passed in either added or
* replacing an existing one with the same key ID.
*
* @param secRing the secret key ring to be modified.
* @param secKey the secret key to be added.
* @return a new secret key ring.
*/
public static PGPSecretKeyRing insertSecretKey(
PGPSecretKeyRing secRing,
PGPSecretKey secKey)
{
List keys = new ArrayList(secRing.keys);
boolean found = false;
boolean masterFound = false;
for (int i = 0; i != keys.size();i++)
{
PGPSecretKey key = (PGPSecretKey)keys.get(i);
if (key.getKeyID() == secKey.getKeyID())
{
found = true;
keys.set(i, secKey);
}
if (key.isMasterKey())
{
masterFound = true;
}
}
if (!found)
{
if (secKey.isMasterKey())
{
if (masterFound)
{
throw new IllegalArgumentException("cannot add a master key to a ring that already has one");
}
keys.add(0, secKey);
}
else
{
keys.add(secKey);
}
}
return new PGPSecretKeyRing(keys, secRing.extraPubKeys);
}
/**
* Returns a new key ring with the secret key passed in removed from the
* key ring.
*
* @param secRing the secret key ring to be modified.
* @param secKey the secret key to be removed.
* @return a new secret key ring, or null if secKey is not found.
*/
public static PGPSecretKeyRing removeSecretKey(
PGPSecretKeyRing secRing,
PGPSecretKey secKey)
{
List keys = new ArrayList(secRing.keys);
boolean found = false;
for (int i = 0; i < keys.size();i++)
{
PGPSecretKey key = (PGPSecretKey)keys.get(i);
if (key.getKeyID() == secKey.getKeyID())
{
found = true;
keys.remove(i);
}
}
if (!found)
{
return null;
}
return new PGPSecretKeyRing(keys, secRing.extraPubKeys);
}
public static PGPSecretKeyRing constructDummyFromPublic(PGPPublicKeyRing pubRing) {
return constructDummyFromPublic(pubRing, null);
}
public static PGPSecretKeyRing constructDummyFromPublic(PGPPublicKeyRing pubRing, byte[] cardSerial) {
List keys = new ArrayList();
for (int i = 0; i < pubRing.keys.size();i++)
{
PGPPublicKey pubKey = (PGPPublicKey)pubRing.keys.get(i);
PGPSecretKey secKey;
if (cardSerial != null) {
secKey = PGPSecretKey.constructGnuDummyKey(pubKey, cardSerial);
} else {
secKey = PGPSecretKey.constructGnuDummyKey(pubKey);
}
keys.add(secKey);
}
return new PGPSecretKeyRing(keys);
}
}
|
package uk.ac.ox.oucs.vle.proxy;
import java.net.URLEncoder;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.component.api.ServerConfigurationService;
import org.sakaiproject.email.api.EmailService;
import org.sakaiproject.event.api.Event;
import org.sakaiproject.event.api.EventTrackingService;
import org.sakaiproject.event.api.NotificationService;
import org.sakaiproject.portal.api.PortalService;
import org.sakaiproject.site.api.SiteService;
import org.sakaiproject.site.api.ToolConfiguration;
import org.sakaiproject.tool.api.Placement;
import org.sakaiproject.tool.api.ToolManager;
import org.sakaiproject.user.api.User;
import org.sakaiproject.user.api.UserDirectoryService;
import org.sakaiproject.user.api.UserNotDefinedException;
import uk.ac.ox.oucs.vle.AdditionalUserDetails;
import uk.ac.ox.oucs.vle.SakaiProxy;
import uk.ac.ox.oucs.vle.UserProxy;
/**
* This is the actual Sakai proxy which talks to the Sakai services.
* @author buckett
*
*/
public class SakaiProxyImpl implements SakaiProxy {
private final static Log log = LogFactory.getLog(SakaiProxyImpl.class);
private UserDirectoryService userService;
private EmailService emailService;
private EventTrackingService eventService;
private ToolManager toolManager;
private ServerConfigurationService serverConfigurationService;
private SiteService siteService;
private PortalService portalService;
private AdditionalUserDetails additionalUserDetails;
private String fromAddress;
public void setUserService(UserDirectoryService userService) {
this.userService = userService;
}
public void setEmailService(EmailService emailService) {
this.emailService = emailService;
}
public void setEventService(EventTrackingService eventService) {
this.eventService = eventService;
}
public void setToolManager(ToolManager toolManager) {
this.toolManager = toolManager;
}
public void setSiteService(SiteService siteService) {
this.siteService = siteService;
}
public void setPortalService(PortalService portalService) {
this.portalService = portalService;
}
public void setAdditionalUserDetails(AdditionalUserDetails additionalUserDetails) {
this.additionalUserDetails = additionalUserDetails;
}
public void setServerConfigurationService(ServerConfigurationService serverConfigurationService) {
this.serverConfigurationService = serverConfigurationService;
}
public void init() {
if (fromAddress == null) {
fromAddress = serverConfigurationService.getString("course-signup.from", null);
}
}
public UserProxy getCurrentUser() {
User sakaiUser = userService.getCurrentUser();
UserProxy user = wrapUserProxy(sakaiUser);
return user;
}
public UserProxy findUserById(String id) {
try {
return wrapUserProxy(userService.getUser(id));
} catch (UserNotDefinedException unde) {
return null;
}
}
public UserProxy findStudentById(String id) {
try {
return wrapStudentProxy(userService.getUser(id));
} catch (UserNotDefinedException unde) {
return null;
}
}
public UserProxy findUserByEmail(String email) {
Collection<User> users = userService.findUsersByEmail(email);
if (users.size() == 0) {
return null;
} else {
if (users.size() > 1) {
log.warn("More than one user found with email: "+ email);
}
return wrapUserProxy(users.iterator().next());
}
}
public UserProxy findUserByEid(String eid) {
try {
return wrapUserProxy(userService.getUserByAid(eid));
} catch (UserNotDefinedException unde) {
return null;
}
}
public void sendEmail(String to, String subject, String body) {
String from = fromAddress;
if (from == null) {
from = getCurrentUser().getEmail();
}
emailService.send(
from, // from address
to, // to address
subject, // subject
body, // message body
null, // header to string
null, // Reply to string
null // Additional headers
);
}
public void logEvent(String resourceId, String eventType, String placementId) {
Placement placement = getPlacement(placementId);
String context = placement.getContext();
String resource = "/coursesignup/group/"+ resourceId;
Event event = eventService.newEvent(eventType, resource, context, false, NotificationService.NOTI_OPTIONAL);
eventService.post(event);
}
/**
* Just get the current placement.
* @return The current placement.
* @throws RunTimeException If there isn't a current placement, this happens
* when a request comes through that isn't processed by the portal.
*/
public Placement getPlacement(String placementId) {
Placement placement = null;
if (null == placementId) {
placement = toolManager.getCurrentPlacement();
} else {
placement = siteService.findTool(placementId);
}
if (placement == null) {
throw new RuntimeException("No current tool placement set.");
}
return placement;
}
@SuppressWarnings("unchecked")
private UserProxy wrapUserProxy(User sakaiUser) {
if(sakaiUser == null) {
return null;
}
List<String> units = sakaiUser.getProperties().getPropertyList("units");
return new UserProxy(sakaiUser.getId(), sakaiUser.getEid(),
sakaiUser.getFirstName(), sakaiUser.getLastName(), sakaiUser.getDisplayName(),
sakaiUser.getEmail(),
sakaiUser.getDisplayId(),
sakaiUser.getProperties().getProperty("oakOSSID"),
sakaiUser.getProperties().getProperty("yearOfStudy"),
sakaiUser.getProperties().getProperty("oakStatus"),
sakaiUser.getProperties().getProperty("primaryOrgUnit"),
null,
(units == null)?Collections.EMPTY_LIST:units);
}
private UserProxy wrapStudentProxy(User sakaiUser) {
if(sakaiUser == null) {
return null;
}
List<String> units = sakaiUser.getProperties().getPropertyList("units");
return new UserProxy(sakaiUser.getId(), sakaiUser.getEid(),
sakaiUser.getFirstName(), sakaiUser.getLastName(), sakaiUser.getDisplayName(),
sakaiUser.getEmail(),
sakaiUser.getDisplayId(),
sakaiUser.getProperties().getProperty("oakOSSID"),
sakaiUser.getProperties().getProperty("yearOfStudy"),
sakaiUser.getProperties().getProperty("oakStatus"),
sakaiUser.getProperties().getProperty("primaryOrgUnit"),
additionalUserDetails.getDegreeProgram(sakaiUser.getEid()),
(units == null)?Collections.EMPTY_LIST:units);
}
public String getAdminUrl() {
return getUrl("/static/admin.jsp");
}
public String getConfirmUrl(String signupId) {
return getConfirmUrl(signupId, null);
}
public String getConfirmUrl(String signupId, String placementId) {
return getUrl("/static/pending.jsp#"+ signupId, placementId);
}
public String getDirectUrl(String courseId) {
return getUrl("/static/index.jsp?openCourse="+ courseId);
}
public String getApproveUrl(String signupId) {
return getApproveUrl(signupId, null);
}
public String getApproveUrl(String signupId, String placementId) {
return getUrl("/static/approve.jsp#"+ signupId, placementId);
}
public String getAdvanceUrl(String signupId, String status, String placementId) {
String urlSafe = encode(signupId+"$"+status+"$"+getPlacement(placementId).getId());
return serverConfigurationService.getServerUrl() +
"/course-signup/rest/signup/advance/"+urlSafe;
}
public String encode(String uncoded) {
byte[] encrypted = encrypt(uncoded);
String base64String = new String(Base64.encodeBase64(encrypted));
return base64String.replace('+','-').replace('/','_');
}
public String uncode(String encoded) {
String base64String = encoded.replace('-','+').replace('_','/');
byte[] encrypted = Base64.decodeBase64(base64String.getBytes());
return decrypt(encrypted);
}
public String getMyUrl() {
return getMyUrl(null);
}
public String getMyUrl(String placementId) {
return getUrl("/static/my.jsp", placementId);
}
private String getUrl(String toolState) {
return getUrl(toolState, null);
}
private String getUrl(String toolState, String placementId) {
Placement currentPlacement = getPlacement(placementId);
//String siteId = currentPlacement.getContext();
ToolConfiguration toolConfiguration = siteService.findTool(currentPlacement.getId());
String pageUrl = toolConfiguration.getContainingPage().getUrl();
Map<String, String[]> encodedToolState = portalService.encodeToolState(currentPlacement.getId(), toolState);
StringBuilder params = new StringBuilder();
for (Entry<String, String[]> entry : encodedToolState.entrySet()) {
for(String value: entry.getValue()) {
params.append("&");
params.append(entry.getKey());
params.append("=");
params.append(URLEncoder.encode(value));
}
}
if (params.length() > 0) {
pageUrl += "?"+ params.substring(1); // Trim the leading &
}
return pageUrl;
}
protected String getSecretKey() {
return serverConfigurationService.getString("aes.secret.key", "se1?r2eFM8rC5u2K");
}
protected byte[] encrypt(String string) {
SecretKeySpec skeySpec = new SecretKeySpec(getSecretKey().getBytes(), "AES");
try {
// Instantiate the cipher
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] bytes = cipher.doFinal(string.getBytes());
return bytes;
} catch (Exception e) {
System.out.println("encrypt Exception ["+e.getLocalizedMessage()+"]");
}
return null;
}
protected String decrypt(byte[] bytes) {
SecretKeySpec skeySpec = new SecretKeySpec(getSecretKey().getBytes(), "AES");
try {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] original = cipher.doFinal(bytes);
return new String(original);
} catch (Exception e) {
System.out.println("decrypt Exception ["+e.getLocalizedMessage()+"]");
}
return null;
}
}
|
package org.pdxfinder.utilities;
import org.apache.commons.cli.Option;
import org.pdxfinder.dao.*;
import org.pdxfinder.repositories.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import java.time.Instant;
import java.util.Collection;
import java.util.Date;
import java.util.Set;
/**
* The hope was to put a lot of reused repository actions into one place ie find
* or create a node or create a node with that requires a number of 'child'
* nodes that are terms
*
* @author sbn
*/
@Component
public class LoaderUtils {
public static Option loadAll = new Option("LoadAll", false, "Load all PDX Finder data");
private TumorTypeRepository tumorTypeRepository;
private BackgroundStrainRepository backgroundStrainRepository;
private ImplantationTypeRepository implantationTypeRepository;
private ImplantationSiteRepository implantationSiteRepository;
private ExternalDataSourceRepository externalDataSourceRepository;
private PatientRepository patientRepository;
private ModelCreationRepository modelCreationRepository;
private TissueRepository tissueRepository;
private PatientSnapshotRepository patientSnapshotRepository;
private SampleRepository sampleRepository;
private MarkerRepository markerRepository;
private MarkerAssociationRepository markerAssociationRepository;
private MolecularCharacterizationRepository molecularCharacterizationRepository;
private PdxPassageRepository pdxPassageRepository;
private QualityAssuranceRepository qualityAssuranceRepository;
private OntologyTermRepository ontologyTermRepository;
private SpecimenRepository specimenRepository;
private PlatformRepository platformRepository;
private PlatformAssociationRepository platformAssociationRepository;
private final static Logger log = LoggerFactory.getLogger(LoaderUtils.class);
public LoaderUtils(TumorTypeRepository tumorTypeRepository,
BackgroundStrainRepository backgroundStrainRepository,
ImplantationTypeRepository implantationTypeRepository,
ImplantationSiteRepository implantationSiteRepository,
ExternalDataSourceRepository externalDataSourceRepository,
PatientRepository patientRepository,
ModelCreationRepository modelCreationRepository,
TissueRepository tissueRepository,
PatientSnapshotRepository patientSnapshotRepository,
SampleRepository sampleRepository,
MarkerRepository markerRepository,
MarkerAssociationRepository markerAssociationRepository,
MolecularCharacterizationRepository molecularCharacterizationRepository,
PdxPassageRepository pdxPassageRepository,
QualityAssuranceRepository qualityAssuranceRepository,
OntologyTermRepository ontologyTermRepository,
SpecimenRepository specimenRepository,
PlatformRepository platformRepository,
PlatformAssociationRepository platformAssociationRepository) {
Assert.notNull(tumorTypeRepository, "tumorTypeRepository cannot be null");
Assert.notNull(backgroundStrainRepository, "backgroundStrainRepository cannot be null");
Assert.notNull(implantationTypeRepository, "implantationTypeRepository cannot be null");
Assert.notNull(implantationSiteRepository, "implantationSiteRepository cannot be null");
Assert.notNull(externalDataSourceRepository, "externalDataSourceRepository cannot be null");
Assert.notNull(patientRepository, "patientRepository cannot be null");
Assert.notNull(modelCreationRepository, "modelCreationRepository cannot be null");
Assert.notNull(tissueRepository, "tissueRepository cannot be null");
Assert.notNull(patientSnapshotRepository, "patientSnapshotRepository cannot be null");
Assert.notNull(sampleRepository, "sampleRepository cannot be null");
Assert.notNull(markerRepository, "markerRepository cannot be null");
Assert.notNull(markerAssociationRepository, "markerAssociationRepository cannot be null");
Assert.notNull(molecularCharacterizationRepository, "molecularCharacterizationRepository cannot be null");
this.tumorTypeRepository = tumorTypeRepository;
this.backgroundStrainRepository = backgroundStrainRepository;
this.implantationTypeRepository = implantationTypeRepository;
this.implantationSiteRepository = implantationSiteRepository;
this.externalDataSourceRepository = externalDataSourceRepository;
this.patientRepository = patientRepository;
this.modelCreationRepository = modelCreationRepository;
this.tissueRepository = tissueRepository;
this.patientSnapshotRepository = patientSnapshotRepository;
this.sampleRepository = sampleRepository;
this.markerRepository = markerRepository;
this.markerAssociationRepository = markerAssociationRepository;
this.molecularCharacterizationRepository = molecularCharacterizationRepository;
this.pdxPassageRepository = pdxPassageRepository;
this.qualityAssuranceRepository = qualityAssuranceRepository;
this.ontologyTermRepository = ontologyTermRepository;
this.specimenRepository = specimenRepository;
this.platformRepository = platformRepository;
this.platformAssociationRepository = platformAssociationRepository;
}
public ExternalDataSource getExternalDataSource(String abbr, String name, String description) {
ExternalDataSource eDS = externalDataSourceRepository.findByAbbreviation(abbr);
if (eDS == null) {
log.info("External data source '{}' not found. Creating", abbr);
eDS = new ExternalDataSource(
name,
abbr,
description,
Date.from(Instant.now()));
externalDataSourceRepository.save(eDS);
}
return eDS;
}
public ModelCreation createModelCreation(String pdxId, ImplantationSite implantationSite, ImplantationType implantationType, Sample sample, BackgroundStrain backgroundStrain, QualityAssurance qa) {
ModelCreation modelCreation = modelCreationRepository.findBySourcePdxId(pdxId);
if (modelCreation != null) {
log.info("Deleting existing ModelCreation " + pdxId);
modelCreationRepository.delete(modelCreation);
}
modelCreation = new ModelCreation(pdxId, implantationSite, implantationType, sample, backgroundStrain, qa);
modelCreationRepository.save(modelCreation);
return modelCreation;
}
public ModelCreation createModelCreation(String pdxId, String implantationSiteStr, String implantationTypeStr, Sample sample, BackgroundStrain backgroundStrain, QualityAssurance qa) {
ImplantationSite implantationSite = this.getImplantationSite(implantationSiteStr);
ImplantationType implantationType = this.getImplantationType(implantationTypeStr);
ModelCreation modelCreation = modelCreationRepository.findBySourcePdxId(pdxId);
if (modelCreation != null) {
log.info("Deleting existing ModelCreation " + pdxId);
modelCreationRepository.delete(modelCreation);
}
modelCreation = new ModelCreation(pdxId, implantationSite, implantationType, sample, backgroundStrain, qa);
modelCreationRepository.save(modelCreation);
return modelCreation;
}
public Collection<ModelCreation> getAllModels(){
return this.modelCreationRepository.getAllModels();
}
public PatientSnapshot getPatientSnapshot(String externalId, String sex, String race, String ethnicity, String age, ExternalDataSource externalDataSource) {
Patient patient = patientRepository.findByExternalId(externalId);
PatientSnapshot patientSnapshot = null;
if (patient == null) {
log.info("Patient '{}' not found. Creating", externalId);
patient = this.getPatient(externalId, sex, race, ethnicity, externalDataSource);
patientSnapshot = new PatientSnapshot(patient, age);
patientSnapshotRepository.save(patientSnapshot);
} else {
patientSnapshot = this.getPatientSnapshot(patient, age);
}
return patientSnapshot;
}
public PatientSnapshot getPatientSnapshot(Patient patient, String age) {
PatientSnapshot patientSnapshot = null;
Set<PatientSnapshot> pSnaps = patientSnapshotRepository.findByPatient(patient.getExternalId());
loop:
for (PatientSnapshot ps : pSnaps) {
if (ps.getAge().equals(age)) {
patientSnapshot = ps;
break loop;
}
}
if (patientSnapshot == null) {
log.info("PatientSnapshot for patient '{}' at age '{}' not found. Creating", patient.getExternalId(), age);
patientSnapshot = new PatientSnapshot(patient, age);
patientSnapshotRepository.save(patientSnapshot);
}
return patientSnapshot;
}
public PatientSnapshot getPatientSnapshot(String patientId, String age, String dataSource){
PatientSnapshot ps = patientSnapshotRepository.findByPatientIdAndDataSourceAndAge(patientId, dataSource, age);
return ps;
}
public Patient getPatient(String externalId, String sex, String race, String ethnicity, ExternalDataSource externalDataSource) {
Patient patient = patientRepository.findByExternalId(externalId);
if (patient == null) {
log.info("Patient '{}' not found. Creating", externalId);
patient = new Patient(externalId, sex, race, ethnicity, externalDataSource);
patientRepository.save(patient);
}
return patient;
}
public Patient getPatientBySampleId(String sampleId){
return patientRepository.findBySampleId(sampleId);
}
public PatientSnapshot getPatientSnapshotByModelId(String modelId){
return patientSnapshotRepository.findByModelId(modelId);
}
public Sample getSample(String sourceSampleId, String typeStr, String diagnosis, String originStr, String sampleSiteStr, String extractionMethod, String classification, Boolean normalTissue, ExternalDataSource externalDataSource) {
TumorType type = this.getTumorType(typeStr);
Tissue origin = this.getTissue(originStr);
Tissue sampleSite = this.getTissue(sampleSiteStr);
Sample sample = sampleRepository.findBySourceSampleId(sourceSampleId);
if (sample == null) {
sample = new Sample(sourceSampleId, type, diagnosis, origin, sampleSite, extractionMethod, classification, normalTissue, externalDataSource);
sampleRepository.save(sample);
}
return sample;
}
public Sample getSampleBySourceSampleId(String sourceSampleId){
Sample sample = sampleRepository.findBySourceSampleId(sourceSampleId);
return sample;
}
public Sample getMouseSample(ModelCreation model, String specimenId, String dataSource, int passage, String sampleId){
Specimen specimen = this.getSpecimen(model, specimenId, dataSource, passage);
Sample sample = null;
if(specimen.getSample() == null){
sample = new Sample();
sample.setSourceSampleId(sampleId);
sampleRepository.save(sample);
}
else{
sample = specimen.getSample();
}
return sample;
}
public Sample getSampleBySourcePdxId(String pdxId){
return sampleRepository.findBySourcePdxId(pdxId);
}
public void saveSample(Sample sample){
sampleRepository.save(sample);
}
public ImplantationSite getImplantationSite(String iSite) {
ImplantationSite site = implantationSiteRepository.findByName(iSite);
if (site == null) {
log.info("Implantation Site '{}' not found. Creating.", iSite);
site = new ImplantationSite(iSite);
implantationSiteRepository.save(site);
}
return site;
}
public ImplantationType getImplantationType(String iType) {
ImplantationType type = implantationTypeRepository.findByName(iType);
if (type == null) {
log.info("Implantation Site '{}' not found. Creating.", iType);
type = new ImplantationType(iType);
implantationTypeRepository.save(type);
}
return type;
}
public Tissue getTissue(String t) {
Tissue tissue = tissueRepository.findByName(t);
if (tissue == null) {
log.info("Tissue '{}' not found. Creating.", t);
tissue = new Tissue(t);
tissueRepository.save(tissue);
}
return tissue;
}
public TumorType getTumorType(String name) {
TumorType tumorType = tumorTypeRepository.findByName(name);
if (tumorType == null) {
log.info("TumorType '{}' not found. Creating.", name);
tumorType = new TumorType(name);
tumorTypeRepository.save(tumorType);
}
return tumorType;
}
public BackgroundStrain getBackgroundStrain(String symbol, String name, String description, String url) {
BackgroundStrain bgStrain = backgroundStrainRepository.findByName(name);
if (bgStrain == null) {
log.info("Background Strain '{}' not found. Creating", name);
bgStrain = new BackgroundStrain(symbol, name, description, url);
backgroundStrainRepository.save(bgStrain);
}
return bgStrain;
}
// is this bad? ... probably..
public Marker getMarker(String symbol) {
return this.getMarker(symbol, symbol);
}
public Marker getMarker(String symbol, String name) {
Marker marker = markerRepository.findByName(name);
if (marker == null && symbol != null) {
marker = markerRepository.findBySymbol(symbol);
}
if (marker == null) {
log.info("Marker '{}' not found. Creating", name);
marker = new Marker(symbol, name);
marker = markerRepository.save(marker);
}
return marker;
}
public Marker getMarkerByEnsemblId(String id){
Marker marker = markerRepository.findByEnsemblId(id);
if (marker == null) {
log.info("Marker '{}' not found. Creating ensemble", id);
marker = new Marker();
marker.setEnsemblId(id);
marker = markerRepository.save(marker);
}
return marker;
}
public MarkerAssociation getMarkerAssociation(String type, String markerSymbol, String markerName) {
Marker m = this.getMarker(markerSymbol, markerName);
MarkerAssociation ma = markerAssociationRepository.findByTypeAndMarkerName(type, m.getName());
if (ma == null && m.getSymbol() != null) {
ma = markerAssociationRepository.findByTypeAndMarkerSymbol(type, m.getSymbol());
}
if (ma == null) {
ma = new MarkerAssociation(type, m);
markerAssociationRepository.save(ma);
}
return ma;
}
// wow this is misleading it doesn't do anyting!
public void deleteAllByEDSName(String edsName) throws Exception {
throw new Exception("Nothing deleted. Method not implemented!");
}
public void savePatientSnapshot(PatientSnapshot ps) {
patientSnapshotRepository.save(ps);
}
public void saveMolecularCharacterization(MolecularCharacterization mc) {
molecularCharacterizationRepository.save(mc);
}
public void saveQualityAssurance(QualityAssurance qa) {
if (qa != null) {
if (null == qualityAssuranceRepository.findFirstByTechnologyAndDescriptionAndValidationTechniques(qa.getTechnology(), qa.getDescription(), qa.getValidationTechniques())) {
qualityAssuranceRepository.save(qa);
}
}
}
public void savePdxPassage(PdxPassage pdxPassage){
pdxPassageRepository.save(pdxPassage);
}
public PdxPassage getPassage(ModelCreation model, String dataSource, int passage){
PdxPassage pass = pdxPassageRepository.findByPassageAndModelIdAndDataSource(passage, model.getSourcePdxId(), dataSource);
if(pass == null){
pass = new PdxPassage(model, passage);
pdxPassageRepository.save(pass);
}
return pass;
}
public Specimen getSpecimen(String id){
Specimen specimen = specimenRepository.findByExternalId(id);
if(specimen == null){
specimen = new Specimen();
specimen.setExternalId(id);
}
return specimen;
}
public Specimen getSpecimen(ModelCreation model, String specimenId, String dataSource, int passage){
PdxPassage pass = this.getPassage(model, dataSource, passage);
Specimen specimen = specimenRepository.findByModelIdAndDataSourceAndSpecimenIdAndPassage(model.getSourcePdxId(), dataSource, specimenId, pass.getPassage());
if(specimen == null){
specimen = new Specimen();
specimen.setExternalId(specimenId);
specimen.setPdxPassage(pass);
specimenRepository.save(specimen);
}
return specimen;
}
public void saveSpecimen(Specimen specimen){
specimenRepository.save(specimen);
}
public OntologyTerm getOntologyTerm(String url, String label){
OntologyTerm ot = ontologyTermRepository.findByUrl(url);
if(ot == null){
ot = new OntologyTerm(url, label);
ontologyTermRepository.save(ot);
}
return ot;
}
public OntologyTerm getOntologyTerm(String url){
OntologyTerm ot = ontologyTermRepository.findByUrl(url);
return ot;
}
public OntologyTerm getOntologyTermByLabel(String label){
OntologyTerm ot = ontologyTermRepository.findByLabel(label);
return ot;
}
public Collection<OntologyTerm> getAllOntologyTerms() {
return ontologyTermRepository.findAll();
}
public Collection<OntologyTerm> getAllOntologyTermsWithNotZeroDirectMapping(){
return ontologyTermRepository.findAllWithNotZeroDirectMappingNumber();
}
public Collection<OntologyTerm> getAllDirectParents(String termUrl){
return ontologyTermRepository.findAllDirectParents(termUrl);
}
public int getIndirectMappingNumber(String label) {
return ontologyTermRepository.getIndirectMappingNumber(label);
}
public int getDirectMappingNumber(String label) {
Set<OntologyTerm> otset = ontologyTermRepository.getDistinctSubTreeNodes(label);
int mapNum = 0;
for (OntologyTerm ot : otset) {
mapNum += ot.getDirectMappedSamplesNumber();
}
return mapNum;
}
public int getOntologyTermNumber(){
return ontologyTermRepository.getOntologyTermNumber();
}
public Collection<OntologyTerm> getAllOntologyTermsFromTo(int from, int to) {
return ontologyTermRepository.findAllFromTo(from, to);
}
public void saveOntologyTerm(OntologyTerm ot){
ontologyTermRepository.save(ot);
}
public void saveMarker(Marker marker) {
markerRepository.save(marker);
}
public Collection<Marker> getAllMarkers() {
return markerRepository.findAllMarkers();
}
public Collection<Marker> getAllHumanMarkers() {
return markerRepository.findAllHumanMarkers();
}
public Platform getPlatform(String name, ExternalDataSource eds) {
Platform p = platformRepository.findByNameAndDataSource(name, eds.getName());
if (p == null) {
p = new Platform();
p.setName(name);
p.setExternalDataSource(eds);
platformRepository.save(p);
}
return p;
}
public PlatformAssociation createPlatformAssociation(Platform p, Marker m) {
if (platformAssociationRepository == null) {
System.out.println("PAR is null");
}
if (p == null) {
System.out.println("Platform is null");
}
if (p.getExternalDataSource() == null) {
System.out.println("P.EDS is null");
}
if (m == null) {
System.out.println("Marker is null");
}
PlatformAssociation pa = platformAssociationRepository.findByPlatformAndMarker(p.getName(), p.getExternalDataSource().getName(), m.getSymbol());
if (pa == null) {
pa = new PlatformAssociation();
pa.setPlatform(p);
pa.setMarker(m);
platformAssociationRepository.save(pa);
}
return pa;
}
}
|
package mil.nga.giat.mage.sdk.fetch;
import android.content.Context;
import android.util.Log;
import com.google.common.io.ByteStreams;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import mil.nga.giat.mage.sdk.connectivity.ConnectivityUtility;
import mil.nga.giat.mage.sdk.datastore.DaoStore;
import mil.nga.giat.mage.sdk.datastore.layer.Layer;
import mil.nga.giat.mage.sdk.datastore.layer.LayerHelper;
import mil.nga.giat.mage.sdk.datastore.staticfeature.StaticFeature;
import mil.nga.giat.mage.sdk.datastore.staticfeature.StaticFeatureHelper;
import mil.nga.giat.mage.sdk.datastore.staticfeature.StaticFeatureProperty;
import mil.nga.giat.mage.sdk.datastore.user.Event;
import mil.nga.giat.mage.sdk.datastore.user.EventHelper;
import mil.nga.giat.mage.sdk.exceptions.StaticFeatureException;
import mil.nga.giat.mage.sdk.http.resource.LayerResource;
import mil.nga.giat.mage.sdk.login.LoginTaskFactory;
public class StaticFeatureServerFetch extends AbstractServerFetch {
public interface OnStaticLayersListener {
void onStaticLayersLoaded(Collection<Layer> layers);
}
private LayerResource layerResource;
public StaticFeatureServerFetch(Context context) {
super(context);
layerResource = new LayerResource(context);
}
private static final String LOG_NAME = StaticFeatureServerFetch.class.getName();
private static final String FEATURE_TYPE = "Feature";
private Boolean isCanceled = Boolean.FALSE;
// TODO test that icons are pulled correctly
public List<Layer> fetch(boolean deleteLocal, OnStaticLayersListener listener) {
List<Layer> newLayers = new ArrayList<>();
// if you are disconnect, skip this
if(!ConnectivityUtility.isOnline(mContext) || LoginTaskFactory.getInstance(mContext).isLocalLogin()) {
Log.d(LOG_NAME, "Disconnected, not pulling static layers.");
return newLayers;
}
Event event = EventHelper.getInstance(mContext).getCurrentEvent();
Log.d(LOG_NAME, "Pulling static layers for event " + event.getName());
try {
LayerHelper layerHelper = LayerHelper.getInstance(mContext);
if (deleteLocal) {
layerHelper.deleteAll(FEATURE_TYPE);
}
Collection<Layer> remoteLayers = layerResource.getLayers(event);
// get local layers
Collection<Layer> localLayers = layerHelper.readAll(FEATURE_TYPE);
Map<String, Layer> remoteIdToLayer = new HashMap<>(localLayers.size());
for(Layer layer : localLayers){
remoteIdToLayer.put(layer.getRemoteId(), layer);
}
for (Layer remoteLayer : remoteLayers) {
if (!localLayers.contains(remoteLayer)) {
layerHelper.create(remoteLayer);
} else {
Layer localLayer = remoteIdToLayer.get(remoteLayer.getRemoteId());
if(!remoteLayer.getEvent().equals(localLayer.getEvent())) {
layerHelper.delete(localLayer.getId());
layerHelper.create(remoteLayer);
}
}
}
newLayers.addAll(layerHelper.readAll(FEATURE_TYPE));
if (listener != null) {
listener.onStaticLayersLoaded(newLayers);
}
} catch (Exception e) {
Log.e(LOG_NAME, "Problem creating layers.", e);
}
return newLayers;
}
public void load(OnStaticLayersListener listener, Layer layer) {
try {
if (!layer.isLoaded()) {
StaticFeatureHelper staticFeatureHelper = StaticFeatureHelper.getInstance(mContext);
try {
Log.i(LOG_NAME, "Loading static features for layer " + layer.getName() + ".");
Collection<StaticFeature> staticFeatures = layerResource.getFeatures(layer);
// Pull down the icons
Collection<String> failedIconUrls = new ArrayList<>();
for (StaticFeature staticFeature : staticFeatures) {
StaticFeatureProperty property = staticFeature.getPropertiesMap().get("styleiconstyleiconhref");
if (property != null) {
String iconUrlString = property.getValue();
if (failedIconUrls.contains(iconUrlString)) {
continue;
}
if (iconUrlString != null) {
File iconFile = null;
try {
URL iconUrl = new URL(iconUrlString);
String filename = iconUrl.getFile();
// remove leading /
if (filename != null) {
filename = filename.trim();
while (filename.startsWith("/")) {
filename = filename.substring(1, filename.length());
}
}
iconFile = new File(mContext.getFilesDir() + "/icons/staticfeatures", filename);
if (!iconFile.exists()) {
iconFile.getParentFile().mkdirs();
iconFile.createNewFile();
InputStream inputStream = layerResource.getFeatureIcon(iconUrlString);
if (inputStream != null) {
ByteStreams.copy(inputStream, new FileOutputStream(iconFile));
staticFeature.setLocalPath(iconFile.getAbsolutePath());
}
} else {
staticFeature.setLocalPath(iconFile.getAbsolutePath());
}
} catch (Exception e) {
// this block should never flow exceptions up! Log for now.
Log.w(LOG_NAME, "Could not get icon.", e);
failedIconUrls.add(iconUrlString);
if (iconFile != null && iconFile.exists()) {
iconFile.delete();
}
}
}
}
}
layer = staticFeatureHelper.createAll(staticFeatures, layer);
try {
layer.setLoaded(true);
LayerHelper.getInstance(mContext).update(layer);
} catch (Exception e) {
throw new StaticFeatureException("Unable to update the layer to loaded: " + layer.getName());
}
Log.i(LOG_NAME, "Loaded static features for layer " + layer.getName());
if(listener != null){
List<Layer> layers = new ArrayList<>(1);
layers.add(layer);
listener.onStaticLayersLoaded(layers);
}
} catch (StaticFeatureException e) {
Log.e(LOG_NAME, "Problem creating static features.", e);
}
}
} catch (Exception e) {
Log.e(LOG_NAME, "Problem loading layers.", e);
}
}
public void destroy() {
isCanceled = true;
}
}
|
package org.xtreemfs.common.benchmark;
import org.xtreemfs.foundation.logging.Logging;
import org.xtreemfs.pbrpc.generatedinterfaces.DIR;
import org.xtreemfs.utils.DefaultDirConfig;
import java.io.IOException;
import java.util.concurrent.ConcurrentLinkedQueue;
import static org.xtreemfs.common.benchmark.BenchmarkUtils.BenchmarkType;
import static org.xtreemfs.foundation.logging.Logging.LEVEL_INFO;
import static org.xtreemfs.foundation.logging.Logging.logMessage;
/**
* Controller for the benchmark library.
* <p/>
*
* The {@link Controller}, the {@link ConfigBuilder} and {@link Config} represent the API to the benchmark library.
*
* @author jensvfischer
*
*/
public class Controller {
private Config config;
private ClientManager clientManager;
private VolumeManager volumeManager;
/**
* Create a new controller object.
*
* @param config
* The parameters to be used for the benchmark.
*/
public Controller(Config config) throws Exception {
this.config = config;
this.clientManager = new ClientManager(config);
this.volumeManager = new VolumeManager(config, clientManager.getNewClient());
}
/**
* Create and open the volumes needed for the benchmarks. <br/>
* If the volumeNames given are already existing volumes, the volumes are only opened. <br/>
*
* @param volumeNames
* the volumes to be created/opened
* @throws Exception
*/
public void setupVolumes(String... volumeNames) throws Exception {
if (volumeNames.length < 1)
throw new IllegalArgumentException("Number of volumes < 1");
else
volumeManager.openVolumes(volumeNames);
}
/**
* Create and open default volumes for the benchmarks. <br/>
* The volumes will be created with the options given by {@link Config}.
*
* @param numberOfVolumes the number of volumes to be created
* @throws Exception
*/
public void setupDefaultVolumes(int numberOfVolumes) throws Exception {
if (numberOfVolumes < 1)
throw new IllegalArgumentException("Number of volumes < 1");
else
volumeManager.createDefaultVolumes(numberOfVolumes);
}
/**
* Starts sequential write benchmarks with the parameters specified in the {@link Config}. <br/>
*
* @return the results of the benchmark (see {@link BenchmarkResult})
* @throws Exception
*/
public ConcurrentLinkedQueue<BenchmarkResult> startSequentialWriteBenchmark(long size, int numberOfThreads) throws Exception {
verifySizesAndThreads(size, numberOfThreads, BenchmarkType.SEQ_WRITE);
return startBenchmark(size, numberOfThreads, BenchmarkType.SEQ_WRITE);
}
/**
* Starts sequential read benchmarks with the parameters specified in the {@link Config}. <br/>
*
* @return the results of the benchmark (see {@link BenchmarkResult})
* @throws Exception
*/
public ConcurrentLinkedQueue<BenchmarkResult> startSequentialReadBenchmark(long size, int numberOfThreads) throws Exception {
verifySizesAndThreads(size, numberOfThreads, BenchmarkType.SEQ_READ);
return startBenchmark(size, numberOfThreads, BenchmarkType.SEQ_READ);
}
/**
* Starts random write benchmarks with the parameters specified in the {@link Config}. <br/>
*
* @return the results of the benchmark (see {@link BenchmarkResult})
* @throws Exception
*/
public ConcurrentLinkedQueue<BenchmarkResult> startRandomWriteBenchmark(long size, int numberOfThreads) throws Exception {
verifySizesAndThreads(size, numberOfThreads, BenchmarkType.RAND_WRITE);
return startBenchmark(size, numberOfThreads, BenchmarkType.RAND_WRITE);
}
/**
* Starts random read benchmarks with the parameters specified in the {@link Config}. <br/>
*
* @return the results of the benchmark (see {@link BenchmarkResult})
* @throws Exception
*/
public ConcurrentLinkedQueue<BenchmarkResult> startRandomReadBenchmark(long size, int numberOfThreads) throws Exception {
verifySizesAndThreads(size, numberOfThreads, BenchmarkType.RAND_READ);
return startBenchmark(size, numberOfThreads, BenchmarkType.RAND_READ);
}
/**
* Starts filebased write benchmarks with the parameters specified in the {@link Config}. <br/>
*
* @return the results of the benchmark (see {@link BenchmarkResult})
* @throws Exception
*/
public ConcurrentLinkedQueue<BenchmarkResult> startFilebasedWriteBenchmark(long size, int numberOfThreads) throws Exception {
verifySizesAndThreads(size, numberOfThreads, BenchmarkType.FILES_WRITE);
return startBenchmark(size, numberOfThreads, BenchmarkType.FILES_WRITE);
}
/**
* Starts filebased read benchmarks with the parameters specified in the {@link Config}. <br/>
*
* @return the results of the benchmark (see {@link BenchmarkResult})
* @throws Exception
*/
public ConcurrentLinkedQueue<BenchmarkResult> startFilebasedReadBenchmark(long size, int numberOfThreads) throws Exception {
verifySizesAndThreads(size, numberOfThreads, BenchmarkType.FILES_READ);
return startBenchmark(size, numberOfThreads, BenchmarkType.FILES_READ);
}
public void tryConnection() throws Exception {
try {
clientManager.getNewClient().getServiceByType(DIR.ServiceType.SERVICE_TYPE_OSD);
} catch (Exception e) {
Logging.logMessage(Logging.LEVEL_ERROR, Logging.Category.tool, Controller.class,
"Failed to establish connection to DIR server.");
throw e;
}
}
/**
* Get the DIR address from default_dir
*
* @return the DIR address, or null if default_dir wasn't found or couldn't be accessed.
*/
public static String getDefaultDir() {
String[] dirAddresses;
DefaultDirConfig cfg = null;
try {
cfg = new DefaultDirConfig();
dirAddresses = cfg.getDirectoryServices();
return dirAddresses[0];
} catch (IOException e) {
logMessage(LEVEL_INFO, Logging.Category.tool, Controller.class,
"Could not access or find Default DIR Config in %s. Using default (localhost).",
DefaultDirConfig.DEFAULT_DIR_CONFIG);
return null;
}
}
/**
* Deletes all created volumes and files and shuts down all clients. This method should be called when all
* benchmarks are finished. The deletion of the volumes and files is regulated by the noCleanup options in
* {@link Config}.
*
* @throws Exception
*/
public void teardown() throws Exception {
deleteVolumesAndFiles();
if (config.isOsdCleanup())
volumeManager.cleanupOSD();
clientManager.shutdownClients();
}
private void verifySizesAndThreads(long size, int threads, BenchmarkType type) {
if ((type == BenchmarkType.SEQ_READ) || (type == BenchmarkType.SEQ_WRITE)) {
if (size % (config.getStripeSizeInBytes() * config.getStripeWidth()) != 0)
throw new IllegalArgumentException("size of " + type
+ " must satisfy: size mod (stripeSize * stripeWidth) == 0");
}
if ((type == BenchmarkType.RAND_READ) || (type == BenchmarkType.RAND_WRITE)) {
if (config.getBasefileSizeInBytes() < size)
throw new IllegalArgumentException("Basefile < size of " + type);
}
if ((type == BenchmarkType.FILES_WRITE) || (type == BenchmarkType.FILES_READ)) {
if (size % config.getFilesize() != 0)
throw new IllegalArgumentException("Size of " + type + " must satisfy: size mod filesize == 0");
}
if (volumeManager.getVolumes().size() < threads )
throw new IllegalArgumentException("Less volumes than parallel threads");
}
/*
* Starts benchmarks in parallel. Every benchmark is started within its own thread. The method waits for all threads
* to finish.
*/
private ConcurrentLinkedQueue<BenchmarkResult> startBenchmark(long size, int numberOfThreads, BenchmarkType benchmarkType)
throws Exception {
ConcurrentLinkedQueue<BenchmarkResult> results = new ConcurrentLinkedQueue<BenchmarkResult>();
ConcurrentLinkedQueue<Thread> threads = new ConcurrentLinkedQueue<Thread>();
for (int i = 0; i < numberOfThreads ; i++) {
AbstractBenchmark benchmark = BenchmarkFactory.createBenchmark(size, benchmarkType, config, clientManager.getNewClient(), volumeManager);
benchmark.startBenchmarkThread(results, threads);
}
/* wait for all threads to finish */
for (Thread thread : threads) {
thread.join();
}
/* reset VolumeManager to prepare for possible consecutive benchmarks */
volumeManager.reset();
/* Set BenchmarkResult Type */
for (BenchmarkResult res : results) {
res.setBenchmarkType(benchmarkType);
res.setNumberOfReadersOrWriters(numberOfThreads);
}
return results;
}
/* delete all created volumes and files depending on the noCleanup options */
private void deleteVolumesAndFiles() throws Exception {
if (!config.isNoCleanup() && !config.isNoCleanupOfVolumes()) {
volumeManager.deleteCreatedFiles(); // is needed in case no volume was created
volumeManager.deleteCreatedVolumes();
} else if (!config.isNoCleanup())
volumeManager.deleteCreatedFiles();
}
}
|
package org.xtreemfs.osd.rwre;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.atomic.AtomicInteger;
import org.xtreemfs.common.uuids.ServiceUUID;
import org.xtreemfs.common.uuids.UnknownUUIDException;
import org.xtreemfs.common.xloc.XLocations;
import org.xtreemfs.foundation.SSLOptions;
import org.xtreemfs.foundation.buffer.ASCIIString;
import org.xtreemfs.foundation.buffer.BufferPool;
import org.xtreemfs.foundation.buffer.ReusableBuffer;
import org.xtreemfs.foundation.flease.Flease;
import org.xtreemfs.foundation.flease.FleaseConfig;
import org.xtreemfs.foundation.flease.FleaseMessageSenderInterface;
import org.xtreemfs.foundation.flease.FleaseStage;
import org.xtreemfs.foundation.flease.FleaseStatusListener;
import org.xtreemfs.foundation.flease.FleaseViewChangeListenerInterface;
import org.xtreemfs.foundation.flease.comm.FleaseMessage;
import org.xtreemfs.foundation.flease.proposer.FleaseException;
import org.xtreemfs.foundation.logging.Logging;
import org.xtreemfs.foundation.logging.Logging.Category;
import org.xtreemfs.foundation.pbrpc.client.PBRPCException;
import org.xtreemfs.foundation.pbrpc.client.RPCAuthentication;
import org.xtreemfs.foundation.pbrpc.client.RPCNIOSocketClient;
import org.xtreemfs.foundation.pbrpc.client.RPCResponse;
import org.xtreemfs.foundation.pbrpc.client.RPCResponseAvailableListener;
import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC;
import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.ErrorType;
import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.POSIXErrno;
import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.RPCHeader.ErrorResponse;
import org.xtreemfs.foundation.pbrpc.utils.ErrorUtils;
import org.xtreemfs.osd.InternalObjectData;
import org.xtreemfs.osd.OSDRequest;
import org.xtreemfs.osd.OSDRequestDispatcher;
import org.xtreemfs.osd.operations.EventRWRStatus;
import org.xtreemfs.osd.operations.OSDOperation;
import org.xtreemfs.osd.rwre.ReplicatedFileState.ReplicaState;
import org.xtreemfs.osd.stages.Stage;
import org.xtreemfs.osd.stages.StorageStage.DeleteObjectsCallback;
import org.xtreemfs.osd.stages.StorageStage.InternalGetMaxObjectNoCallback;
import org.xtreemfs.osd.stages.StorageStage.WriteObjectCallback;
import org.xtreemfs.osd.storage.CowPolicy;
import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.FileCredentials;
import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.OSDWriteResponse;
import org.xtreemfs.pbrpc.generatedinterfaces.OSD.AuthoritativeReplicaState;
import org.xtreemfs.pbrpc.generatedinterfaces.OSD.ObjectData;
import org.xtreemfs.pbrpc.generatedinterfaces.OSD.ObjectVersion;
import org.xtreemfs.pbrpc.generatedinterfaces.OSD.ObjectVersionMapping;
import org.xtreemfs.pbrpc.generatedinterfaces.OSD.ReplicaStatus;
import org.xtreemfs.pbrpc.generatedinterfaces.OSDServiceClient;
/**
*
* @author bjko
*/
public class RWReplicationStage extends Stage implements FleaseMessageSenderInterface {
public static final int STAGEOP_REPLICATED_WRITE = 1;
public static final int STAGEOP_CLOSE = 2;
public static final int STAGEOP_PROCESS_FLEASE_MSG = 3;
public static final int STAGEOP_PREPAREOP = 5;
public static final int STAGEOP_TRUNCATE = 6;
public static final int STAGEOP_GETSTATUS = 7;
public static final int STAGEOP_INTERNAL_AUTHSTATE = 10;
public static final int STAGEOP_INTERNAL_OBJFETCHED = 11;
public static final int STAGEOP_LEASE_STATE_CHANGED = 13;
public static final int STAGEOP_INTERNAL_STATEAVAIL = 14;
public static final int STAGEOP_INTERNAL_DELETE_COMPLETE = 15;
public static final int STAGEOP_FORCE_RESET = 16;
public static final int STAGEOP_INTERNAL_MAXOBJ_AVAIL = 17;
public static final int STAGEOP_INTERNAL_BACKUP_AUTHSTATE = 18;
public static enum Operation {
READ,
WRITE,
TRUNCATE,
INTERNAL_UPDATE,
INTERNAL_TRUNCATE
};
private final RPCNIOSocketClient client;
private final OSDServiceClient osdClient;
private final Map<String,ReplicatedFileState> files;
private final Map<ASCIIString,String> cellToFileId;
private final OSDRequestDispatcher master;
private final FleaseStage fstage;
private final RPCNIOSocketClient fleaseClient;
private final OSDServiceClient fleaseOsdClient;
private final ASCIIString localID;
private int numObjsInFlight;
private static final int MAX_OBJS_IN_FLIGHT = 10;
private static final int MAX_PENDING_PER_FILE = 10;
private static final int MAX_EXTERNAL_REQUESTS_IN_Q = 250;
private final Queue<ReplicatedFileState> filesInReset;
private final FleaseMasterEpochThread masterEpochThread;
private final AtomicInteger externalRequestsInQueue;
public RWReplicationStage(OSDRequestDispatcher master, SSLOptions sslOpts, int maxRequestsQueueLength) throws IOException {
super("RWReplSt", maxRequestsQueueLength);
this.master = master;
client = new RPCNIOSocketClient(sslOpts, 15000, 60000*5, "RWReplicationStage");
fleaseClient = new RPCNIOSocketClient(sslOpts, 15000, 60000*5, "RWReplicationStage (flease)");
osdClient = new OSDServiceClient(client,null);
fleaseOsdClient = new OSDServiceClient(fleaseClient,null);
files = new HashMap<String, ReplicatedFileState>();
cellToFileId = new HashMap<ASCIIString,String>();
numObjsInFlight = 0;
filesInReset = new LinkedList();
externalRequestsInQueue = new AtomicInteger(0);
localID = new ASCIIString(master.getConfig().getUUID().toString());
masterEpochThread = new FleaseMasterEpochThread(master.getStorageStage().getStorageLayout(), maxRequestsQueueLength);
FleaseConfig fcfg = new FleaseConfig(master.getConfig().getFleaseLeaseToMS(),
master.getConfig().getFleaseDmaxMS(), master.getConfig().getFleaseMsgToMS(),
null, localID.toString(), master.getConfig().getFleaseRetries());
fstage = new FleaseStage(fcfg, master.getConfig().getObjDir()+"/",
this, false, new FleaseViewChangeListenerInterface() {
@Override
public void viewIdChangeEvent(ASCIIString cellId, int viewId) {
throw new UnsupportedOperationException("Not supported yet.");
}
}, new FleaseStatusListener() {
@Override
public void statusChanged(ASCIIString cellId, Flease lease) {
//FIXME: change state
eventLeaseStateChanged(cellId, lease, null);
}
@Override
public void leaseFailed(ASCIIString cellID, FleaseException error) {
//change state
//flush pending requests
eventLeaseStateChanged(cellID, null, error);
}
}, masterEpochThread);
fstage.setLifeCycleListener(master);
}
@Override
public void start() {
masterEpochThread.start();
client.start();
fleaseClient.start();
fstage.start();
super.start();
}
@Override
public void shutdown() {
client.shutdown();
fleaseClient.shutdown();
fstage.shutdown();
masterEpochThread.shutdown();
super.shutdown();
}
@Override
public void waitForStartup() throws Exception {
masterEpochThread.waitForStartup();
client.waitForStartup();
fleaseClient.waitForStartup();
fstage.waitForStartup();
super.waitForStartup();
}
@Override
public void waitForShutdown() throws Exception {
client.waitForShutdown();
fleaseClient.waitForShutdown();
fstage.waitForShutdown();
masterEpochThread.waitForShutdown();
super.waitForShutdown();
}
public void eventReplicaStateAvailable(String fileId, ReplicaStatus localState, ErrorResponse error) {
this.enqueueOperation(STAGEOP_INTERNAL_STATEAVAIL, new Object[]{fileId,localState,error}, null, null);
}
public void eventForceReset(FileCredentials credentials, XLocations xloc) {
this.enqueueOperation(STAGEOP_FORCE_RESET, new Object[]{credentials, xloc}, null, null);
}
public void eventDeleteObjectsComplete(String fileId, ErrorResponse error) {
this.enqueueOperation(STAGEOP_INTERNAL_DELETE_COMPLETE, new Object[]{fileId,error}, null, null);
}
void eventObjectFetched(String fileId, ObjectVersionMapping object, InternalObjectData data, ErrorResponse error) {
this.enqueueOperation(STAGEOP_INTERNAL_OBJFETCHED, new Object[]{fileId,object,data,error}, null, null);
}
void eventSetAuthState(String fileId, AuthoritativeReplicaState authState, ReplicaStatus localState, ErrorResponse error) {
this.enqueueOperation(STAGEOP_INTERNAL_AUTHSTATE, new Object[]{fileId,authState, localState, error}, null, null);
}
void eventLeaseStateChanged(ASCIIString cellId, Flease lease, FleaseException error) {
this.enqueueOperation(STAGEOP_LEASE_STATE_CHANGED, new Object[]{cellId,lease,error}, null, null);
}
void eventMaxObjAvail(String fileId, long maxObjVer, long fileSize, long truncateEpoch, ErrorResponse error) {
this.enqueueOperation(STAGEOP_INTERNAL_MAXOBJ_AVAIL, new Object[]{fileId,maxObjVer,error}, null, null);
}
public void eventBackupReplicaReset(String fileId, AuthoritativeReplicaState authState, ReplicaStatus localState,
FileCredentials credentials, XLocations xloc) {
this.enqueueOperation(STAGEOP_INTERNAL_BACKUP_AUTHSTATE, new Object[]{fileId,authState, localState, credentials, xloc}, null, null);
}
private void executeSetAuthState(final ReplicaStatus localState, final AuthoritativeReplicaState authState, ReplicatedFileState state, final String fileId) {
// Calculate what we need to do locally based on the local state.
boolean resetRequired = localState.getTruncateEpoch() < authState.getTruncateEpoch();
// Create a list of missing objects.
Map<Long, Long> objectsToBeDeleted = new HashMap();
for (ObjectVersion localObject : localState.getObjectVersionsList()) {
// Never delete any object which is newer than auth state!
if (localObject.getObjectVersion() <= authState.getMaxObjVersion()) {
objectsToBeDeleted.put(localObject.getObjectNumber(), localObject.getObjectVersion());
}
}
// Delete everything that is older or not part of the authoritative state.
for (ObjectVersionMapping authObject : authState.getObjectVersionsList()) {
Long version = objectsToBeDeleted.get(authObject.getObjectNumber());
if ((version != null) && (version == authObject.getObjectVersion())) {
objectsToBeDeleted.remove(authObject.getObjectNumber());
}
}
Map<Long, ObjectVersionMapping> missingObjects = new HashMap();
for (ObjectVersionMapping authObject : authState.getObjectVersionsList()) {
missingObjects.put(authObject.getObjectNumber(), authObject);
}
for (ObjectVersion localObject : localState.getObjectVersionsList()) {
ObjectVersionMapping object = missingObjects.get(localObject.getObjectNumber());
if ((object != null) && (localObject.getObjectVersion() >= object.getObjectVersion())) {
missingObjects.remove(localObject.getObjectNumber());
}
}
if (!missingObjects.isEmpty() || !objectsToBeDeleted.isEmpty() || (localState.getTruncateEpoch() < authState.getTruncateEpoch())) {
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this, "(R:%s) replica RESET required updates for: %s", localID, state.getFileId());
}
state.setObjectsToFetch(new LinkedList(missingObjects.values()));
filesInReset.add(state);
// Start by deleting the old objects.
master.getStorageStage().deleteObjects(fileId, state.getsPolicy(), authState.getTruncateEpoch(), objectsToBeDeleted, new DeleteObjectsCallback() {
@Override
public void deleteObjectsComplete(ErrorResponse error) {
eventDeleteObjectsComplete(fileId, error);
}
});
} else {
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this, "(R:%s) replica RESET finished (replica is up-to-date): %s", localID, state.getFileId());
}
doOpen(state);
}
}
private void processLeaseStateChanged(StageRequest method) {
try {
final ASCIIString cellId = (ASCIIString) method.getArgs()[0];
final Flease lease = (Flease) method.getArgs()[1];
final FleaseException error = (FleaseException) method.getArgs()[2];
if (error == null) {
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"(R:%s) lease change event: %s, %s",localID, cellId, lease);
}
} else {
// Logging.logMessage(Logging.LEVEL_WARN, Category.replication, this,"(R:%s) lease error in cell %s: %s cell debug: %s",localID, cellId, error, error.getFleaseCellDebugString());
Logging.logMessage(Logging.LEVEL_WARN, Category.replication, this,"(R:%s) lease error in cell %s: %s",localID, cellId, error);
}
final String fileId = cellToFileId.get(cellId);
if (fileId != null) {
ReplicatedFileState state = files.get(fileId);
assert(state != null);
boolean leaseOk = false;
if (error == null) {
boolean localIsPrimary = (lease.getLeaseHolder() != null) && (lease.getLeaseHolder().equals(localID));
ReplicaState oldState = state.getState();
state.setLocalIsPrimary(localIsPrimary);
state.setLease(lease);
// Error handling for timeouts on the primary.
if (oldState == ReplicaState.PRIMARY
&&lease.getLeaseHolder() == null
&& lease.getLeaseTimeout_ms() == 0) {
Logging.logMessage(Logging.LEVEL_ERROR, Category.replication, this,"(R:%s) was primary, lease error in cell %s, restarting replication: %s",localID, cellId,lease,error);
failed(state, ErrorUtils.getInternalServerError(new IOException(fileId +": lease timed out, renew failed")), "processLeaseStateChanged");
} else {
if ( (state.getState() == ReplicaState.BACKUP)
|| (state.getState() == ReplicaState.PRIMARY)
|| (state.getState() == ReplicaState.WAITING_FOR_LEASE) ) {
if (localIsPrimary) {
//notify onPrimary
if (oldState != ReplicaState.PRIMARY) {
state.setMasterEpoch(lease.getMasterEpochNumber());
doPrimary(state);
}
} else {
if (oldState != ReplicaState.BACKUP) {
state.setMasterEpoch(FleaseMessage.IGNORE_MASTER_EPOCH);
doBackup(state);
}
}
}
}
} else {
failed(state, ErrorUtils.getInternalServerError(error), "processLeaseStateChanged (error != null)");
}
}
} catch (Exception ex) {
Logging.logMessage(Logging.LEVEL_ERROR,
this,
"Exception was thrown and caught while processing the change of the lease state." +
" This is an error in the code. Please report it! Caught exception: ");
Logging.logError(Logging.LEVEL_ERROR, this,ex);
}
}
private void processBackupAuthoritativeState(StageRequest method) {
try {
final String fileId = (String) method.getArgs()[0];
final AuthoritativeReplicaState authState = (AuthoritativeReplicaState) method.getArgs()[1];
final ReplicaStatus localState = (ReplicaStatus) method.getArgs()[2];
final FileCredentials credentials = (FileCredentials) method.getArgs()[3];
final XLocations loc = (XLocations) method.getArgs()[4];
ReplicatedFileState state = getState(credentials, loc, true);
switch (state.getState()) {
case INITIALIZING:
case OPEN:
case WAITING_FOR_LEASE: {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"(R:%s) enqueued backup reset for file %s",localID, fileId);
state.addPendingRequest(method);
break;
}
case BACKUP: {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"(R:%s) backup reset triggered by AUTHSTATE request for file %s",localID, fileId);
state.setState(ReplicaState.RESET);
executeSetAuthState(localState, authState, state, fileId);
break;
}
case RESET:
default: {
// Ignore.
Logging.logMessage(Logging.LEVEL_WARN, Category.replication, this,"(R:%s) auth state ignored, already in reset for file %s",localID, fileId);
}
}
} catch (Exception ex) {
Logging.logError(Logging.LEVEL_ERROR, this,ex);
}
}
private void processSetAuthoritativeState(StageRequest method) {
try {
final String fileId = (String) method.getArgs()[0];
final AuthoritativeReplicaState authState = (AuthoritativeReplicaState) method.getArgs()[1];
final ReplicaStatus localState = (ReplicaStatus) method.getArgs()[2];
final ErrorResponse error = (ErrorResponse) method.getArgs()[3];
ReplicatedFileState state = files.get(fileId);
if (state == null) {
Logging.logMessage(Logging.LEVEL_WARN, Category.replication, this,"(R:%s) set AUTH for unknown file: %s",localID, fileId);
return;
}
if (error != null) {
failed(state, error, "processSetAuthoritativeState");
} else {
executeSetAuthState(localState, authState, state, fileId);
}
} catch (Exception ex) {
Logging.logError(Logging.LEVEL_ERROR, this,ex);
}
}
private void processDeleteObjectsComplete(StageRequest method) {
try {
final String fileId = (String) method.getArgs()[0];
final ErrorResponse error = (ErrorResponse) method.getArgs()[1];
ReplicatedFileState state = files.get(fileId);
if (state != null) {
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"(R:%s) deleted all objects requested by RESET for %s with %s",localID,state.getFileId(),
ErrorUtils.formatError(error));
}
if (error != null) {
failed(state, error, "processDeleteObjectsComplete");
} else {
fetchObjects();
}
}
} catch (Exception ex) {
Logging.logError(Logging.LEVEL_ERROR, this,ex);
}
}
private void fetchObjects() {
while (numObjsInFlight < MAX_OBJS_IN_FLIGHT) {
ReplicatedFileState file = filesInReset.poll();
if (file == null)
break;
if (!file.getObjectsToFetch().isEmpty()) {
ObjectVersionMapping o = file.getObjectsToFetch().remove(0);
file.setNumObjectsPending(file.getNumObjectsPending()+1);
numObjsInFlight++;
fetchObject(file.getFileId(), o);
}
if (!file.getObjectsToFetch().isEmpty()) {
filesInReset.add(file);
}
}
}
private void fetchObject(final String fileId, final ObjectVersionMapping record) {
ReplicatedFileState state = files.get(fileId);
if (state == null) {
return;
}
try {
final ServiceUUID osd = new ServiceUUID(record.getOsdUuidsList().get(0));
//fetch that object
if (Logging.isDebug())
Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"(R:%s) file %s, fetch object %d (version %d) from %s",
localID, fileId,record.getObjectNumber(),record.getObjectVersion(),osd);
RPCResponse r = osdClient.xtreemfs_rwr_fetch(osd.getAddress(), RPCAuthentication.authNone, RPCAuthentication.userService,
state.getCredentials(), fileId, record.getObjectNumber(), record.getObjectVersion());
r.registerListener(new RPCResponseAvailableListener() {
@Override
public void responseAvailable(RPCResponse r) {
try {
ObjectData metadata = (ObjectData) r.get();
InternalObjectData data = new InternalObjectData(metadata, r.getData());
eventObjectFetched(fileId, record, data, null);
} catch (PBRPCException ex) {
// Transform exception into correct ErrorResponse.
// TODO(mberlin): Generalize this functionality by returning "Throwable" instead of
// "ErrorResponse" to the event* functions.
// The "ErrorResponse" shall be created in the last 'step' at the
// invocation of failed().
eventObjectFetched(fileId,
record,
null,
ErrorUtils.getErrorResponse(ex.getErrorType(), ex.getPOSIXErrno(), ex.toString(), ex));
} catch (Exception ex) {
eventObjectFetched(fileId,
record,
null,
ErrorUtils.getErrorResponse(ErrorType.IO_ERROR, POSIXErrno.POSIX_ERROR_NONE, ex.toString(), ex));
} finally {
r.freeBuffers();
}
}
});
} catch (IOException ex) {
eventObjectFetched(fileId, record, null, ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EIO, ex.toString(), ex));
}
}
private void processObjectFetched(StageRequest method) {
try {
final String fileId = (String) method.getArgs()[0];
final ObjectVersionMapping record = (ObjectVersionMapping) method.getArgs()[1];
final InternalObjectData data = (InternalObjectData) method.getArgs()[2];
final ErrorResponse error = (ErrorResponse) method.getArgs()[3];
ReplicatedFileState state = files.get(fileId);
if (state != null) {
if (error != null) {
numObjsInFlight
fetchObjects();
failed(state, error, "processObjectFetched");
} else if (data.getData() == null) {
// data is null if object was deleted meanwhile.
numObjsInFlight
fetchObjects();
ErrorResponse generatedError = ErrorResponse.newBuilder().setErrorType(RPC.ErrorType.INTERNAL_SERVER_ERROR).setErrorMessage("Fetching a missing object failed because no data was returned. The object was probably deleted meanwhile.").build();
failed(state, generatedError, "processObjectFetched");
} else {
final int bytes = data.getData().remaining();
master.getStorageStage().writeObjectWithoutGMax(fileId, record.getObjectNumber(),
state.getsPolicy(), 0, data.getData(), CowPolicy.PolicyNoCow, null, false,
record.getObjectVersion(), null, new WriteObjectCallback() {
@Override
public void writeComplete(OSDWriteResponse result, ErrorResponse error) {
if (error != null) {
Logging.logMessage(Logging.LEVEL_ERROR, Category.replication, this,"cannot write object locally: %s",ErrorUtils.formatError(error));
}
}
});
master.getPreprocStage().pingFile(fileId);
master.objectReplicated();
master.replicatedDataReceived(bytes);
numObjsInFlight
final int numPendingFile = state.getNumObjectsPending()-1;
state.setNumObjectsPending(numPendingFile);
state.getPolicy().objectFetched(record.getObjectVersion());
if (Logging.isDebug())
Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"(R:%s) fetched object for replica, file %s, remaining %d",localID, fileId,numPendingFile);
fetchObjects();
if (numPendingFile == 0) {
//reset complete!
Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"(R:%s) RESET complete for file %s",localID, fileId);
doOpen(state);
}
}
}
} catch (Exception ex) {
Logging.logError(Logging.LEVEL_ERROR, this,ex);
}
}
private void doReset(final ReplicatedFileState file, long updateObjVer) {
if (file.getState() == ReplicaState.RESET) {
if (Logging.isDebug())
Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"file %s is already in RESET",file.getFileId());
return;
}
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"(R:%s) replica state changed for %s from %s to %s",localID, file.getFileId(),file.getState(),ReplicaState.RESET);
}
file.setState(ReplicaState.RESET);
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"(R:%s) replica RESET started: %s (update objVer=%d)",localID, file.getFileId(),updateObjVer);
}
OSDOperation op = master.getInternalEvent(EventRWRStatus.class);
op.startInternalEvent(new Object[]{file.getFileId(),file.getsPolicy()});
}
private void processReplicaStateAvailExecReset(StageRequest method) {
try {
final String fileId = (String) method.getArgs()[0];
final ReplicaStatus localReplicaState = (ReplicaStatus) method.getArgs()[1];
final ErrorResponse error = (ErrorResponse) method.getArgs()[2];
final ReplicatedFileState state = files.get(fileId);
if (state != null) {
if (error != null) {
Logging.logMessage(Logging.LEVEL_ERROR, Category.replication, this,"local state for %s failed: %s",
state.getFileId(), error);
failed(state, error, "processReplicaStateAvailExecReset");
} else {
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"(R:%s) local state for %s available.",
localID, state.getFileId());
}
state.getPolicy().executeReset(state.getCredentials(), localReplicaState, new ReplicaUpdatePolicy.ExecuteResetCallback() {
@Override
public void finished(AuthoritativeReplicaState authState) {
eventSetAuthState(state.getFileId(), authState, localReplicaState, null);
}
@Override
public void failed(ErrorResponse error) {
eventSetAuthState(state.getFileId(), null, null, error);
}
});
}
}
} catch (Exception ex) {
Logging.logError(Logging.LEVEL_ERROR, this,ex);
}
}
private void processForceReset(StageRequest method) {
try {
final FileCredentials credentials = (FileCredentials) method.getArgs()[0];
final XLocations loc = (XLocations) method.getArgs()[1];
ReplicatedFileState state = getState(credentials, loc, true);
if (!state.isForceReset()) {
state.setForceReset(true);
}
} catch (Exception ex) {
Logging.logError(Logging.LEVEL_ERROR, this,ex);
}
}
private void doWaitingForLease(final ReplicatedFileState file) {
if (file.getPolicy().requiresLease()) {
if (file.isCellOpen()) {
if (file.isLocalIsPrimary()) {
doPrimary(file);
} else {
doBackup(file);
}
} else {
file.setCellOpen(true);
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"(R:%s) replica state changed for %s from %s to %s",
localID,file.getFileId(),file.getState(),ReplicaState.WAITING_FOR_LEASE);
}
try {
file.setState(ReplicaState.WAITING_FOR_LEASE);
List<InetSocketAddress> osdAddresses = new ArrayList();
for (ServiceUUID osd : file.getPolicy().getRemoteOSDUUIDs()) {
osdAddresses.add(osd.getAddress());
}
fstage.openCell(file.getPolicy().getCellId(), osdAddresses, true);
//wait for lease...
} catch (UnknownUUIDException ex) {
failed(file, ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EIO, ex.toString(), ex), "doWaitingForLease");
}
}
} else {
//become primary immediately
doPrimary(file);
}
}
private void doOpen(final ReplicatedFileState file) {
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, this,"(R:%s) replica state changed for %s from %s to %s",localID, file.getFileId(),file.getState(),ReplicaState.OPEN);
}
file.setState(ReplicaState.OPEN);
if (file.getPendingRequests().size() > 0) {
doWaitingForLease(file);
}
}
private void doPrimary(final ReplicatedFileState file) {
assert(file.isLocalIsPrimary());
try {
if (file.getPolicy().onPrimary((int)file.getMasterEpoch()) && !file.isPrimaryReset()) {
file.setPrimaryReset(true);
doReset(file,ReplicaUpdatePolicy.UNLIMITED_RESET);
} else {
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"(R:%s) replica state changed for %s from %s to %s",
localID, file.getFileId(),file.getState(),ReplicaState.PRIMARY);
}
file.setPrimaryReset(false);
file.setState(ReplicaState.PRIMARY);
while (!file.getPendingRequests().isEmpty()) {
StageRequest m = file.getPendingRequests().remove(0);
enqueuePrioritized(m);
}
}
} catch (IOException ex) {
failed(file, ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EIO, ex.toString(), ex), "doPrimary");
}
}
private void doBackup(final ReplicatedFileState file) {
assert(!file.isLocalIsPrimary());
//try {
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"(R:%s) replica state changed for %s from %s to %s",
localID, file.getFileId(),file.getState(),ReplicaState.BACKUP);
}
file.setPrimaryReset(false);
file.setState(ReplicaState.BACKUP);
while (!file.getPendingRequests().isEmpty()) {
StageRequest m = file.getPendingRequests().remove(0);
enqueuePrioritized(m);
}
/*} catch (IOException ex) {
failed(file, ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EIO, ex.toString(), ex));
}*/
}
private void failed(ReplicatedFileState file, ErrorResponse ex, String methodName) {
Logging.logMessage(Logging.LEVEL_WARN, Category.replication, this,"(R:%s) replica for file %s failed (in method: %s): %s", localID, file.getFileId(), methodName, ErrorUtils.formatError(ex));
file.setPrimaryReset(false);
file.setState(ReplicaState.OPEN);
file.setCellOpen(false);
fstage.closeCell(file.getPolicy().getCellId(), false);
for (StageRequest rq : file.getPendingRequests()) {
RWReplicationCallback callback = (RWReplicationCallback) rq.getCallback();
if (callback != null) {
callback.failed(ex);
}
}
file.getPendingRequests().clear();
}
private void enqueuePrioritized(StageRequest rq) {
while (!q.offer(rq)) {
StageRequest otherRq = q.poll();
otherRq.sendInternalServerError(new IllegalStateException("internal queue overflow, cannot enqueue operation for processing."));
Logging.logMessage(Logging.LEVEL_DEBUG, this, "Dropping request from rwre queue due to overload");
}
}
public static interface RWReplicationCallback {
public void success(long newObjectVersion);
public void redirect(String redirectTo);
public void failed(ErrorResponse ex);
}
/*public void openFile(FileCredentials credentials, XLocations locations, boolean forceReset,
RWReplicationCallback callback, OSDRequest request) {
this.enqueueOperation(STAGEOP_OPEN, new Object[]{credentials,locations,forceReset}, request, callback);
}*/
protected void enqueueExternalOperation(int stageOp, Object[] arguments, OSDRequest request, ReusableBuffer createdViewBuffer, Object callback) {
if (externalRequestsInQueue.get() >= MAX_EXTERNAL_REQUESTS_IN_Q) {
Logging.logMessage(Logging.LEVEL_WARN, this, "RW replication stage is overloaded, request %d for %s dropped", request.getRequestId(), request.getFileId());
request.sendInternalServerError(new IllegalStateException("RW replication stage is overloaded, request dropped"));
// Make sure that the data buffer is returned to the pool if
// necessary, as some operations create view buffers on the
// data. Otherwise, a 'finalized but not freed before' warning
// may occur.
if (createdViewBuffer != null) {
assert (createdViewBuffer.getRefCount() >= 2);
BufferPool.free(createdViewBuffer);
}
} else {
externalRequestsInQueue.incrementAndGet();
this.enqueueOperation(stageOp, arguments, request, createdViewBuffer, callback);
}
}
public void prepareOperation(FileCredentials credentials, XLocations xloc, long objNo, long objVersion, Operation op, RWReplicationCallback callback,
OSDRequest request) {
this.enqueueExternalOperation(STAGEOP_PREPAREOP, new Object[]{credentials,xloc,objNo,objVersion,op}, request, null, callback);
}
public void replicatedWrite(FileCredentials credentials, XLocations xloc, long objNo, long objVersion, InternalObjectData data, ReusableBuffer createdViewBuffer,
RWReplicationCallback callback, OSDRequest request) {
this.enqueueExternalOperation(STAGEOP_REPLICATED_WRITE, new Object[]{credentials,xloc,objNo,objVersion,data}, request, createdViewBuffer, callback);
}
public void replicateTruncate(FileCredentials credentials, XLocations xloc, long newFileSize, long newObjectVersion,
RWReplicationCallback callback, OSDRequest request) {
this.enqueueExternalOperation(STAGEOP_TRUNCATE, new Object[]{credentials,xloc,newFileSize,newObjectVersion}, request, null, callback);
}
public void fileClosed(String fileId) {
this.enqueueOperation(STAGEOP_CLOSE, new Object[]{fileId}, null, null);
}
public void receiveFleaseMessage(ReusableBuffer message, InetSocketAddress sender) {
//this.enqueueOperation(STAGEOP_PROCESS_FLEASE_MSG, new Object[]{message,sender}, null, null);
try {
FleaseMessage msg = new FleaseMessage(message);
BufferPool.free(message);
msg.setSender(sender);
fstage.receiveMessage(msg);
} catch (Exception ex) {
Logging.logError(Logging.LEVEL_ERROR, this,ex);
}
}
public void getStatus(StatusCallback callback) {
this.enqueueOperation(STAGEOP_GETSTATUS, new Object[]{}, null, callback);
}
public static interface StatusCallback {
public void statusComplete(Map<String,Map<String,String>> status);
}
@Override
public void sendMessage(FleaseMessage message, InetSocketAddress recipient) {
ReusableBuffer data = BufferPool.allocate(message.getSize());
message.serialize(data);
data.flip();
try {
RPCResponse r = fleaseOsdClient.xtreemfs_rwr_flease_msg(recipient, RPCAuthentication.authNone, RPCAuthentication.userService, master.getHostName(),master.getConfig().getPort(),data);
r.registerListener(new RPCResponseAvailableListener() {
@Override
public void responseAvailable(RPCResponse r) {
r.freeBuffers();
}
});
} catch (IOException ex) {
Logging.logError(Logging.LEVEL_ERROR, this, ex);
}
}
@Override
protected void processMethod(StageRequest method) {
switch (method.getStageMethod()) {
case STAGEOP_REPLICATED_WRITE : {
externalRequestsInQueue.decrementAndGet();
processReplicatedWrite(method);
break;
}
case STAGEOP_TRUNCATE : {
externalRequestsInQueue.decrementAndGet();
processReplicatedTruncate(method);
break;
}
case STAGEOP_CLOSE : processFileClosed(method); break;
case STAGEOP_PROCESS_FLEASE_MSG : processFleaseMessage(method); break;
case STAGEOP_PREPAREOP : {
externalRequestsInQueue.decrementAndGet();
processPrepareOp(method);
break;
}
case STAGEOP_INTERNAL_AUTHSTATE : processSetAuthoritativeState(method); break;
case STAGEOP_LEASE_STATE_CHANGED : processLeaseStateChanged(method); break;
case STAGEOP_INTERNAL_OBJFETCHED : processObjectFetched(method); break;
case STAGEOP_INTERNAL_STATEAVAIL : processReplicaStateAvailExecReset(method); break;
case STAGEOP_INTERNAL_DELETE_COMPLETE : processDeleteObjectsComplete(method); break;
case STAGEOP_INTERNAL_MAXOBJ_AVAIL : processMaxObjAvail(method); break;
case STAGEOP_INTERNAL_BACKUP_AUTHSTATE: processBackupAuthoritativeState(method); break;
case STAGEOP_FORCE_RESET : processForceReset(method); break;
case STAGEOP_GETSTATUS : processGetStatus(method); break;
default : throw new IllegalArgumentException("no such stageop");
}
}
private void processFleaseMessage(StageRequest method) {
try {
final ReusableBuffer data = (ReusableBuffer) method.getArgs()[0];
final InetSocketAddress sender = (InetSocketAddress) method.getArgs()[1];
FleaseMessage msg = new FleaseMessage(data);
BufferPool.free(data);
msg.setSender(sender);
fstage.receiveMessage(msg);
} catch (Exception ex) {
Logging.logError(Logging.LEVEL_ERROR, this,ex);
}
}
private void processFileClosed(StageRequest method) {
try {
final String fileId = (String) method.getArgs()[0];
ReplicatedFileState state = files.remove(fileId);
if (state != null) {
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"closing file %s",fileId);
}
state.getPolicy().closeFile();
if (state.getPolicy().requiresLease())
fstage.closeCell(state.getPolicy().getCellId(), false);
cellToFileId.remove(state.getPolicy().getCellId());
}
} catch (Exception ex) {
Logging.logError(Logging.LEVEL_ERROR, this,ex);
}
}
private ReplicatedFileState getState(FileCredentials credentials, XLocations loc, boolean forceReset) throws IOException {
final String fileId = credentials.getXcap().getFileId();
ReplicatedFileState state = files.get(fileId);
if (state == null) {
if (Logging.isDebug())
Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"open file: "+fileId);
//"open" file
state = new ReplicatedFileState(fileId,loc, master.getConfig().getUUID(), fstage, osdClient);
files.put(fileId,state);
state.setCredentials(credentials);
state.setForceReset(forceReset);
cellToFileId.put(state.getPolicy().getCellId(),fileId);
assert(state.getState() == ReplicaState.INITIALIZING);
master.getStorageStage().internalGetMaxObjectNo(fileId, loc.getLocalReplica().getStripingPolicy(), new InternalGetMaxObjectNoCallback() {
@Override
public void maxObjectNoCompleted(long maxObjNo, long fileSize, long truncateEpoch, ErrorResponse error) {
eventMaxObjAvail(fileId, maxObjNo, fileSize, truncateEpoch, error);
}
});
}
return state;
}
private void processMaxObjAvail(StageRequest method) {
try {
final String fileId = (String) method.getArgs()[0];
final Long maxObjVersion = (Long) method.getArgs()[1];
final ErrorResponse error = (ErrorResponse) method.getArgs()[2];
if (Logging.isDebug())
Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"(R:%s) max obj avail for file: "+fileId+" max="+maxObjVersion, localID);
ReplicatedFileState state = files.get(fileId);
if (state == null) {
Logging.logMessage(Logging.LEVEL_ERROR, Category.replication, this,"received maxObjAvail event for unknow file: %s",fileId);
return;
}
assert(state.getState() == ReplicaState.INITIALIZING);
state.getPolicy().setLocalObjectVersion(maxObjVersion);
doOpen(state);
} catch (Exception ex) {
Logging.logError(Logging.LEVEL_ERROR, this, ex);
}
}
private void processReplicatedWrite(StageRequest method) {
final RWReplicationCallback callback = (RWReplicationCallback) method.getCallback();
try {
final FileCredentials credentials = (FileCredentials) method.getArgs()[0];
final XLocations loc = (XLocations) method.getArgs()[1];
final Long objNo = (Long) method.getArgs()[2];
final Long objVersion = (Long) method.getArgs()[3];
final InternalObjectData objData = (InternalObjectData) method.getArgs()[4];
final String fileId = credentials.getXcap().getFileId();
ReplicatedFileState state = files.get(fileId);
if (state == null) {
BufferPool.free(objData.getData());
callback.failed(ErrorUtils.getErrorResponse(ErrorType.INTERNAL_SERVER_ERROR, POSIXErrno.POSIX_ERROR_EIO, "file is not open!"));
return;
}
state.setCredentials(credentials);
state.getPolicy().executeWrite(credentials, objNo, objVersion, objData, new ReplicaUpdatePolicy.ClientOperationCallback() {
@Override
public void finsihed() {
callback.success(objVersion);
}
@Override
public void failed(ErrorResponse error) {
callback.failed(error);
}
});
} catch (Exception ex) {
ex.printStackTrace();
callback.failed(ErrorUtils.getInternalServerError(ex));
}
}
private void processReplicatedTruncate(StageRequest method) {
final RWReplicationCallback callback = (RWReplicationCallback) method.getCallback();
try {
final FileCredentials credentials = (FileCredentials) method.getArgs()[0];
final XLocations loc = (XLocations) method.getArgs()[1];
final Long newFileSize = (Long) method.getArgs()[2];
final Long newObjVersion = (Long) method.getArgs()[3];
final String fileId = credentials.getXcap().getFileId();
ReplicatedFileState state = files.get(fileId);
if (state == null) {
callback.failed(ErrorUtils.getErrorResponse(ErrorType.INTERNAL_SERVER_ERROR, POSIXErrno.POSIX_ERROR_EIO, "file is not open!"));
return;
}
state.setCredentials(credentials);
state.getPolicy().executeTruncate(credentials, newFileSize, newObjVersion, new ReplicaUpdatePolicy.ClientOperationCallback() {
@Override
public void finsihed() {
callback.success(newObjVersion);
}
@Override
public void failed(ErrorResponse error) {
callback.failed(error);
}
});
} catch (Exception ex) {
ex.printStackTrace();
callback.failed(ErrorUtils.getInternalServerError(ex));
}
}
private void processPrepareOp(StageRequest method) {
final RWReplicationCallback callback = (RWReplicationCallback)method.getCallback();
try {
final FileCredentials credentials = (FileCredentials) method.getArgs()[0];
final XLocations loc = (XLocations) method.getArgs()[1];
final Long objVersion = (Long) method.getArgs()[3];
final Operation op = (Operation) method.getArgs()[4];
final String fileId = credentials.getXcap().getFileId();
ReplicatedFileState state = getState(credentials, loc, false);
if ((op == Operation.INTERNAL_UPDATE) || (op == Operation.INTERNAL_TRUNCATE)) {
switch (state.getState()) {
case WAITING_FOR_LEASE:
case INITIALIZING:
case RESET:
case OPEN: {
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"enqeue update for %s (state is %s)",fileId,state.getState());
}
if (state.getPendingRequests().size() > MAX_PENDING_PER_FILE) {
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, this,
"rejecting request: too many requests (is: %d, max %d) in queue for file %s",
state.getPendingRequests().size(), MAX_PENDING_PER_FILE, fileId);
}
callback.failed(ErrorUtils.getErrorResponse(ErrorType.INTERNAL_SERVER_ERROR, POSIXErrno.POSIX_ERROR_NONE, "too many requests in queue for file"));
return;
} else {
state.getPendingRequests().add(method);
}
if (state.getState() == ReplicaState.OPEN) {
//immediately change to backup mode...no need to check the lease
doWaitingForLease(state);
}
return;
}
}
if (!state.getPolicy().acceptRemoteUpdate(objVersion)) {
Logging.logMessage(
Logging.LEVEL_WARN,
Category.replication,
this,
"received outdated object version %d for file %s",
objVersion,
fileId);
callback.failed(ErrorUtils.getErrorResponse(
ErrorType.IO_ERROR,
POSIXErrno.POSIX_ERROR_EIO,
"outdated object version for update rejected"));
return;
}
boolean needsReset = state.getPolicy().onRemoteUpdate(objVersion, state.getState());
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.replication, this,"%s needs reset: %s",fileId,needsReset);
}
if (needsReset) {
state.getPendingRequests().add(method);
doReset(state,objVersion);
} else {
callback.success(0);
}
} else {
state.setCredentials(credentials);
switch (state.getState()) {
case WAITING_FOR_LEASE:
case INITIALIZING:
case RESET : {
if (state.getPendingRequests().size() > MAX_PENDING_PER_FILE) {
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, this,
"rejecting request: too many requests (is: %d, max %d) in queue for file %s",
state.getPendingRequests().size(), MAX_PENDING_PER_FILE, fileId);
}
callback.failed(ErrorUtils.getErrorResponse(ErrorType.INTERNAL_SERVER_ERROR, POSIXErrno.POSIX_ERROR_NONE, "too many requests in queue for file"));
} else {
state.getPendingRequests().add(method);
}
return;
}
case OPEN : {
if (state.getPendingRequests().size() > MAX_PENDING_PER_FILE) {
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, this,
"rejecting request: too many requests (is: %d, max %d) in queue for file %s",
state.getPendingRequests().size(), MAX_PENDING_PER_FILE, fileId);
}
callback.failed(ErrorUtils.getErrorResponse(ErrorType.INTERNAL_SERVER_ERROR, POSIXErrno.POSIX_ERROR_NONE, "too many requests in queue for file"));
return;
} else {
state.getPendingRequests().add(method);
}
doWaitingForLease(state);
return;
}
}
try {
long newVersion = state.getPolicy().onClientOperation(op,objVersion,state.getState(),state.getLease());
callback.success(newVersion);
} catch (RedirectToMasterException ex) {
callback.redirect(ex.getMasterUUID());
} catch (RetryException ex) {
final ErrorResponse err = ErrorUtils.getInternalServerError(ex);
failed(state, err, "processPrepareOp");
if (state.getState() == ReplicaState.BACKUP
|| state.getState() == ReplicaState.PRIMARY) {
// Request is not in queue, we must notify
// callback.
callback.failed(err);
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
callback.failed(ErrorUtils.getInternalServerError(ex));
}
}
private void processGetStatus(StageRequest method) {
final StatusCallback callback = (StatusCallback)method.getCallback();
try {
Map<String,Map<String,String>> status = new HashMap();
Map<ASCIIString,FleaseMessage> fleaseState = fstage.getLocalState();
for (String fileId : this.files.keySet()) {
Map<String,String> fStatus = new HashMap();
final ReplicatedFileState fState = files.get(fileId);
final ASCIIString cellId = fState.getPolicy().getCellId();
fStatus.put("policy",fState.getPolicy().getClass().getSimpleName());
fStatus.put("peers (OSDs)",fState.getPolicy().getRemoteOSDUUIDs().toString());
fStatus.put("pending requests", fState.getPendingRequests() == null ? "0" : ""+fState.getPendingRequests().size());
fStatus.put("cellId", cellId.toString());
String primary = "unknown";
if ((fState.getLease() != null) && (!fState.getLease().isEmptyLease())) {
if (fState.getLease().isValid()) {
if (fState.isLocalIsPrimary()) {
primary = "primary";
} else {
primary = "backup ( primary is "+fState.getLease().getLeaseHolder()+")";
}
} else {
primary = "outdated lease: "+fState.getLease().getLeaseHolder();
}
}
fStatus.put("role", primary);
status.put(fileId,fStatus);
}
callback.statusComplete(status);
} catch (Exception ex) {
ex.printStackTrace();
callback.statusComplete(null);
}
}
}
|
package edu.gatech.oad.antlab.person;
/**
* A simple class for person 4
* returns their name and a
* modified string
*
* @author Bob
* @version 1.1
*/
public class Person4 {
/** Holds the persons real name */
private String name = "Jin W. Chung";
/**
* The constructor, takes in the persons
* name
* @param pname the person's real name
*/
public Person4(String pname) {
name = pname;
}
/**
* This method should return a string
* where each character is 1 greater
* than its previous value. So
* given "abc123" it should return
* "bcd234".
* @NullExceptionError throw this when string is null.
* @param input the string to be modified
* @return the modified string
*/
private String calc(String input) {
if(input == null) {
throw NullExceptionError ("the string is void.");
}
char[] divided = input.toCharArray();
int[] before = (int[]) divided;
String after = "";
for(i = 0; i < before.length; i++) {
after += (char) (before[i] + 1);
}
return after;
}
/**
* Return a string rep of this object
* that varies with an input string
*
* @param input the varying string
* @return the string representing the
* object
*/
public String toString(String input) {
return name + calc(input);
}
}
|
package fredboat.audio;
import com.sedmelluq.discord.lavaplayer.player.AudioConfiguration;
import com.sedmelluq.discord.lavaplayer.player.AudioPlayer;
import com.sedmelluq.discord.lavaplayer.player.AudioPlayerManager;
import com.sedmelluq.discord.lavaplayer.player.DefaultAudioPlayerManager;
import com.sedmelluq.discord.lavaplayer.player.event.AudioEventAdapter;
import com.sedmelluq.discord.lavaplayer.source.bandcamp.BandcampAudioSourceManager;
import com.sedmelluq.discord.lavaplayer.source.beam.BeamAudioSourceManager;
import com.sedmelluq.discord.lavaplayer.source.http.HttpAudioSourceManager;
import com.sedmelluq.discord.lavaplayer.source.soundcloud.SoundCloudAudioSourceManager;
import com.sedmelluq.discord.lavaplayer.source.twitch.TwitchStreamAudioSourceManager;
import com.sedmelluq.discord.lavaplayer.source.vimeo.VimeoAudioSourceManager;
import com.sedmelluq.discord.lavaplayer.source.youtube.YoutubeAudioSourceManager;
import com.sedmelluq.discord.lavaplayer.track.AudioTrack;
import com.sedmelluq.discord.lavaplayer.track.AudioTrackEndReason;
import com.sedmelluq.discord.lavaplayer.track.TrackMarker;
import com.sedmelluq.discord.lavaplayer.track.playback.AudioFrame;
import fredboat.Config;
import fredboat.audio.queue.AudioTrackContext;
import fredboat.audio.queue.ITrackProvider;
import fredboat.audio.queue.SplitAudioTrackContext;
import fredboat.audio.queue.TrackEndMarkerHandler;
import fredboat.audio.source.PlaylistImportSourceManager;
import fredboat.util.DistributionEnum;
import net.dv8tion.jda.core.audio.AudioSendHandler;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
public abstract class AbstractPlayer extends AudioEventAdapter implements AudioSendHandler {
private static final org.slf4j.Logger log = LoggerFactory.getLogger(AbstractPlayer.class);
private static AudioPlayerManager playerManager;
AudioPlayer player;
ITrackProvider audioTrackProvider;
private AudioFrame lastFrame = null;
private AudioTrackContext context;
@SuppressWarnings("LeakingThisInConstructor")
AbstractPlayer() {
initAudioPlayerManager();
player = playerManager.createPlayer();
player.addListener(this);
}
private static void initAudioPlayerManager() {
if (playerManager == null) {
playerManager = new DefaultAudioPlayerManager();
registerSourceManagers(playerManager);
//Patrons get higher quality
AudioConfiguration.ResamplingQuality quality = Config.CONFIG.getDistribution() == DistributionEnum.PATRON ? AudioConfiguration.ResamplingQuality.HIGH : AudioConfiguration.ResamplingQuality.LOW;
playerManager.getConfiguration().setResamplingQuality(quality);
playerManager.enableGcMonitoring();
if (Config.CONFIG.getDistribution() != DistributionEnum.PATRON && Config.CONFIG.getDistribution() != DistributionEnum.DEVELOPMENT && Config.CONFIG.isLavaplayerNodesEnabled()) {
playerManager.useRemoteNodes(Config.CONFIG.getLavaplayerNodes());
}
}
}
public static AudioPlayerManager registerSourceManagers(AudioPlayerManager mng) {
mng.registerSourceManager(new YoutubeAudioSourceManager());
mng.registerSourceManager(new SoundCloudAudioSourceManager());
mng.registerSourceManager(new BandcampAudioSourceManager());
mng.registerSourceManager(new PlaylistImportSourceManager());
mng.registerSourceManager(new TwitchStreamAudioSourceManager());
mng.registerSourceManager(new VimeoAudioSourceManager());
mng.registerSourceManager(new BeamAudioSourceManager());
mng.registerSourceManager(new HttpAudioSourceManager());
return mng;
}
public void play() {
if (player.isPaused()) {
player.setPaused(false);
}
if (player.getPlayingTrack() == null) {
play0(false);
}
}
public void setPause(boolean pause) {
if (pause) {
player.setPaused(true);
} else {
player.setPaused(false);
play();
}
}
public void pause() {
player.setPaused(true);
}
public void stop() {
player.stopTrack();
}
public void skip() {
player.stopTrack();
}
public boolean isQueueEmpty() {
return getPlayingTrack() == null && audioTrackProvider.isEmpty();
}
public AudioTrackContext getPlayingTrack() {
if (player.getPlayingTrack() == null) {
play0(true);//Ensure we have something to return, unless the queue is really empty
}
if (player.getPlayingTrack() == null) {
context = null;
}
return context;
}
public List<AudioTrackContext> getQueuedTracks() {
return audioTrackProvider.getAsList();
}
public List<AudioTrackContext> getRemainingTracks() {
//Includes currently playing track, which comes first
if (getPlayingTrack() != null) {
ArrayList<AudioTrackContext> list = new ArrayList<>();
list.add(getPlayingTrack());
list.addAll(getQueuedTracks());
return list;
} else {
return getQueuedTracks();
}
}
public List<AudioTrackContext> getRemainingTracksOrdered() {
List<AudioTrackContext> list = new ArrayList<>();
if (getPlayingTrack() != null) {
list.add(getPlayingTrack());
}
list.addAll(getAudioTrackProvider().getAsListOrdered());
return list;
}
public void setVolume(float vol) {
player.setVolume((int) (vol * 100));
}
public float getVolume() {
return ((float) player.getVolume()) / 100;
}
public void setAudioTrackProvider(ITrackProvider audioTrackProvider) {
this.audioTrackProvider = audioTrackProvider;
}
public ITrackProvider getAudioTrackProvider() {
return audioTrackProvider;
}
public static AudioPlayerManager getPlayerManager() {
initAudioPlayerManager();
return playerManager;
}
@Override
public void onTrackEnd(AudioPlayer player, AudioTrack track, AudioTrackEndReason endReason) {
if (endReason == AudioTrackEndReason.FINISHED) {
play0(false);
} else if(endReason == AudioTrackEndReason.STOPPED) {
play0(true);
}
}
private void play0(boolean skipped) {
if (audioTrackProvider != null) {
context = audioTrackProvider.provideAudioTrack(skipped);
if(context != null) {
player.playTrack(context.getTrack());
context.getTrack().setPosition(context.getStartPosition());
if(context instanceof SplitAudioTrackContext){
//Ensure we don't step over our bounds
log.info("Start: " + context.getStartPosition() + "End: " + (context.getStartPosition() + context.getEffectiveDuration()));
context.getTrack().setMarker(
new TrackMarker(context.getStartPosition() + context.getEffectiveDuration(),
new TrackEndMarkerHandler(this, context)));
}
}
} else {
log.warn("TrackProvider doesn't exist");
}
}
public void destroy() {
player.destroy();
}
@Override
public byte[] provide20MsAudio() {
return lastFrame.data;
}
@Override
public boolean canProvide() {
lastFrame = player.provide();
return lastFrame != null;
}
@Override
public boolean isOpus() {
return true;
}
public boolean isPlaying() {
return player.getPlayingTrack() != null && !player.isPaused();
}
public boolean isPaused() {
return player.isPaused();
}
}
|
package com.polarbirds.gifcreator;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import com.polarbirds.gifcreator.ThreadActionEvent.Action;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.concurrent.Task;
import javafx.concurrent.Worker.State;
import javafx.concurrent.WorkerStateEvent;
import javafx.event.EventHandler;
/**
*
* @author Kristian
* WIP.
*/
public class FileManager {
private File path;
private final List<BufferedImage> images;
private ObservableList<File> allFiles;
private ObservableList<File> selectedFiles;
private final List<ThreadActionCompleteListener> listeners;
private List<Task<Void>> loaders;
public FileManager() {
listeners = new ArrayList<ThreadActionCompleteListener>();
images = new ArrayList<BufferedImage>();
loaders = new ArrayList<Task<Void>>();
allFiles = FXCollections.observableArrayList();
selectedFiles = FXCollections.observableArrayList();
}
public void setPath(File path) {
this.path = path;
}
public File getPath() {
return path;
}
public ObservableList<File> getAllFilesList() {
return allFiles;
}
public ObservableList<File> getSelectedFilesList() {
return selectedFiles;
}
public void selectFile(int index) {
if (-1 < index && index < allFiles.size()) {
File selectedFile = allFiles.get(index);
if (selectedFile != null) {
selectedFiles.add(selectedFile);
}
}
}
public void removeSelection(int index) {
if (-1 < index && index < selectedFiles.size()) {
selectedFiles.remove(index);
}
}
/**
* @param index of the file to move.
* @return true if the file was moved, false otherwise.
*/
public boolean moveSelectionUp(int index) {
//Valid range is [1, last file]
if (0 < index && index < selectedFiles.size()) {
File above = selectedFiles.get(index-1);
selectedFiles.set(index-1, selectedFiles.get(index));
selectedFiles.set(index, above);
return true;
}
return false;
}
/**
* @param index of the file to move.
* @return true if the file was moved, false otherwise.
*/
public boolean moveSelectionDown(int index) {
//Valid range is [0, last file - 1]
if (0 <= index && index < selectedFiles.size()-1) {
File below = selectedFiles.get(index+1);
selectedFiles.set(index+1, selectedFiles.get(index));
selectedFiles.set(index, below);
return true;
}
return false;
}
public void loadPath() {
File[] files = getPath().listFiles(
new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
String[] extensions = ImageIO.getReaderFileSuffixes(); //Get an array containing "jpg", "bmp", "gif" etc.
for (String ext :extensions) {
if (name.endsWith(ext)) {
//Add image extensions as accepted file types.
return true;
}
}
return false;
}
});
if (allFiles != null) {
allFiles.clear();
for (File image : files) {
allFiles.add(image);
}
}
}
public void loadImages() {
//Make sure the loader does not rely on a mutable array.
final File[] files = new File[selectedFiles.size()];
for (int i = 0; i < selectedFiles.size(); i++) {
files[i] = new File(selectedFiles.get(i).getPath());
}
final BufferedImage[] temp = new BufferedImage[files.length];
//Create task
Task<Void> loadTask = new Task<Void>() {
@Override
protected Void call() throws Exception {
int i = 0;
for (File image : files) {
try {
// Possible optimization: load images into a map using path as key. avoids duplicates. Assign key to various indexes
// in a string array. When adding images from the map to the ArrayList later, use the same BufferedImage references where
// duplicates occur.
if (isCancelled()) {
return null;
}
temp[i] = ImageIO.read(image);
} catch (Exception e) {}
finally {
i++;
}
}
return null;
}
};
//Set action to perform on success
//inb4 "use lamba u filthy skrub"
loadTask.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
@Override
public void handle(WorkerStateEvent event) {
images.clear();
for (BufferedImage image : temp) {
images.add(image);
}
for (ThreadActionCompleteListener listener : listeners) {
listener.actionComplete(new ThreadActionEvent(Action.FILES_LOADED));
}
}
});
loaders.add(loadTask);
//Run task
Thread loadThread = new Thread(null, loadTask, "ImageLoader");
loadThread.setDaemon(true); //Not sure what happens on false.
loadThread.start();
}
/**
* Cancels the loading thread.
*/
public void cancelLoading() {
Iterator<Task<Void>> iter = loaders.iterator();
while (iter.hasNext()) {
Task<Void> loader = iter.next();
if (loader == null || loader.getState() == State.CANCELLED ||
loader.getState() == State.FAILED || loader.getState() == State.SUCCEEDED){
iter.remove();
} else {
loader.cancel();
}
}
}
/**
* Returns the loaded images.
*/
public BufferedImage[] getImages() {
BufferedImage[] out = new BufferedImage[images.size()];
int i = 0;
for (BufferedImage image : images) {
out[i] = image;
i++;
}
return out;
}
public void addListener(ThreadActionCompleteListener listener) {
listeners.add(listener);
}
public void removeListener(ThreadActionCompleteListener listener) {
listeners.remove(listener);
}
public void saveGif(byte[] imageByteArray, File file) {
ImageOutputStream a;
try {
System.out.println("Writing gif...");
a = ImageIO.createImageOutputStream(new FileOutputStream(file));
a.write(imageByteArray);
System.out.println("Done writing gif. Stream pos: "+a.getStreamPosition());
a.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
package com.gokuai.base;
import com.gokuai.base.utils.Util;
import java.util.*;
public class SignAbility {
static List<String> IGNORE_KEYS = Arrays.asList("filehash", "filesize", "sign");
protected final String mClientId;
protected final String mSecret;
public SignAbility(String clientId, String secret) {
this.mClientId = clientId;
this.mSecret = secret;
}
public String getClientId() {
return this.mClientId;
}
public String getSecret() {
return this.mSecret;
}
protected String generateSign(HashMap<String, String> params, String secret) {
// null
Iterator it = params.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
if (pair.getValue() == null) {
it.remove();
}
}
List<String> keys = new ArrayList<String>(params.keySet());
Collections.sort(keys);
String strToSign = "";
if (!params.isEmpty()) {
for (String key:keys) {
if (IGNORE_KEYS.contains(key)) {
continue;
}
String value = params.get(key);
strToSign += "\n" + value;
}
strToSign = strToSign.substring(1);
}
return Util.getHmacSha1(strToSign, secret);
}
protected String generateSign(HashMap<String, String> params) {
return this.generateSign(params, this.mSecret);
}
}
|
package org.bridj;
import org.bridj.ann.Convention.Style;
import java.lang.reflect.*;
import java.lang.annotation.*;
import java.util.Arrays;
import org.bridj.Pointer;
import org.bridj.ann.CLong;
import org.bridj.ann.Constructor;
import org.bridj.ann.Ptr;
import org.bridj.util.DefaultParameterizedType;
import org.bridj.cpp.GCC4Demangler;
import org.bridj.cpp.VC9Demangler;
/*
mvn exec:java -Dexec.mainClass=org.bridj.Demangler "-Dexec.args=?method_name@class_name@@QAEPAPADPAD0@Z"
*/
public abstract class Demangler {
public static void main(String[] args) {
for (String arg : args) {
try {
System.out.println("VC9: " + new VC9Demangler(null, arg).parseSymbol());
} catch (Exception ex) {
ex.printStackTrace();
}
try {
System.out.println("GCC4: " + new GCC4Demangler(null, arg).parseSymbol());
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
interface Annotations {
<A extends Annotation> A getAnnotation(Class<A> c);
}
static Annotations annotations(final Annotation[] aa) {
return new Annotations() {
@Override
public <A extends Annotation> A getAnnotation(Class<A> c) {
for (Annotation a : aa)
if (c.isInstance(a))
return (A)a;
return null;
}
};
}
static Annotations annotations(final AnnotatedElement e) {
return new Annotations() {
@Override
public <A extends Annotation> A getAnnotation(Class<A> c) {
return e.getAnnotation(c);
}
};
}
public static class DemanglingException extends Exception {
public DemanglingException(String mess) {
super(mess);
}
}
public abstract MemberRef parseSymbol() throws DemanglingException;
protected final String str;
protected final int length;
protected int position = 0;
protected final NativeLibrary library;
public Demangler(NativeLibrary library, String str) {
this.str = str;
this.length = str.length();
this.library = library;
}
public String getString() {
return str;
}
protected void expectChars(char... cs) throws DemanglingException {
for (char c : cs) {
char cc = consumeChar();
if (cc != c)
throw error("Expected char '" + c + "', found '" + cc + "'");
}
}
protected void expectAnyChar(char... cs) throws DemanglingException {
char cc = consumeChar();
for (char c : cs) {
if (cc == c)
return;
}
throw error("Expected any of " + Arrays.toString(cs) + ", found '" + cc + "'");
}
public static StringBuilder implode(StringBuilder b, Object[] items, String sep) {
return implode(b, Arrays.asList(items), sep);
}
public static StringBuilder implode(StringBuilder b, Iterable<?> items, String sep) {
boolean first = true;
for (Object item : items) {
if (first)
first = false;
else
b.append(sep);
b.append(item);
}
return b;
}
protected char peekChar() {
return position >= length ? 0 : str.charAt(position);
}
protected char lastChar() {
return position == 0 ? 0 : str.charAt(position - 1);
}
protected char consumeChar() {
char c = peekChar();
if (c != 0)
position++;
return c;
}
protected boolean consumeCharsIf(char... nextChars) {
int initialPosition = position;
for (char c : nextChars) {
char cc = consumeChar();
if (cc != c) {
position = initialPosition;
return false;
}
}
return true;
}
protected boolean consumeCharIf(char... allowedChars) {
char c = peekChar();
for (char allowedChar : allowedChars)
if (allowedChar == c) {
position++;
return true;
}
return false;
}
protected DemanglingException error(int deltaPosition) {
return error(null, deltaPosition);
}
protected DemanglingException error(String mess) {
return error(mess, -1);
}
protected DemanglingException error(String mess, int deltaPosition) {
StringBuilder err = new StringBuilder(position + 1);
int position = this.position + deltaPosition;
for (int i = 0; i < position; i++)
err.append(' ');
err.append('^');
return new DemanglingException("Parsing error at position " + position + (mess == null ? "" : ": " + mess) + " \n\t" + str + "\n\t" + err);
}
public interface TemplateArg {
}
public static class Symbol {
final String symbol;
long address;
MemberRef ref;
boolean refParsed;
final NativeLibrary library;
public Symbol(String symbol, NativeLibrary library) {
this.symbol = symbol;
this.library = library;
}
@Override
public String toString() {
return symbol + (ref == null ? "" : " (" + ref + ")");
}
public long getAddress() {
if (address == 0)
address = library.getSymbolAddress(symbol);
return address;
}
public boolean matches(Method method) {
if (!symbol.contains(method.getName()))
return false;
//if (!Modifier.isStatic(method.getModifiers()) && !symbol.contains(method.getDeclaringClass().getSimpleName()))
// return false;
parse();
try {
if (ref != null) {
boolean res = ref.matches(method);
if (!res) {
System.err.println("Symbol " + symbol + " was a good candidate but expected demangled signature " + ref + " did not match the method " + method);
}
return res;
}
} catch (Exception ex) {
ex.printStackTrace();
}
return false;
}
public MemberRef getParsedRef() {
parse();
return ref;
}
void parse() {
if (!refParsed) {
try {
ref = library.parseSymbol(symbol);
} catch (DemanglingException ex) {
System.err.println(ex);
//ex.printStackTrace();
}
refParsed = true;
}
}
public String getName() {
return symbol;
}
public boolean matchesVirtualTable(Class<?> type) {
if (!symbol.contains(type.getSimpleName()))
return false;
parse();
try {
if (ref != null) {
return ref.matchesVirtualTable(type);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return false;
}
public boolean matchesConstructor(Class<?> type) {
if (!symbol.contains(type.getSimpleName()))
return false;
parse();
try {
if (ref != null) {
return ref.matchesConstructor(type);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return false;
}
public boolean matchesDestructor(Class<?> type) {
if (!symbol.contains(type.getSimpleName()))
return false;
parse();
try {
if (ref != null) {
return ref.matchesDestructor(type);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return false;
}
public boolean isVirtualTable() {
// TODO Auto-generated method stub
return false;
}
}
public static abstract class TypeRef implements TemplateArg {
public abstract StringBuilder getQualifiedName(StringBuilder b, boolean generic);
public boolean matches(Type type, Annotations annotations) {
return getQualifiedName(new StringBuilder(), false).toString().equals(getTypeClass(type).getName());
}
}
public static class Constant implements TemplateArg {
Object value;
public Constant(Object value) {
this.value = value;
}
@Override
public String toString() {
return value.toString();
}
}
public static class NamespaceRef extends TypeRef {
Object[] namespace;
public NamespaceRef(Object[] namespace) {
this.namespace = namespace;
}
public StringBuilder getQualifiedName(StringBuilder b, boolean generic) {
return implode(b, namespace, ".");
}
@Override
public String toString() {
return getQualifiedName(new StringBuilder(), true).toString();
}
}
public static class PointerTypeRef extends TypeRef {
public TypeRef pointedType;
public PointerTypeRef(TypeRef pointedType) {
this.pointedType = pointedType;
}
@Override
public StringBuilder getQualifiedName(StringBuilder b, boolean generic) {
return b.append("org.bridj.Pointer");
}
}
protected static TypeRef pointerType(TypeRef tr) {
return new PointerTypeRef(tr);
}
protected static TypeRef classType(final Class<?> c, Class<? extends Annotation>... annotations) {
return classType(c, null, annotations);
}
protected static TypeRef classType(final Class<?> c, final java.lang.reflect.Type[] genericTypes, Class<? extends Annotation>... annotations) {
JavaTypeRef tr = new JavaTypeRef();
if (genericTypes == null)
tr.type = c;
else
tr.type = new DefaultParameterizedType(c, genericTypes);
tr.annotations = annotations;
return tr;
}
protected static TypeRef simpleType(String name) {
return new ClassRef(name);
}
static Class<?> getTypeClass(Type type) {
if (type instanceof Class<?>)
return (Class<?>)type;
if (type instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType)type;
Class<?> c = (Class<?>)pt.getRawType();
if (ValuedEnum.class.isAssignableFrom(c)) {
Type[] types = pt.getActualTypeArguments();
if (types == null || types.length != 1)
c = int.class;
else
c = getTypeClass(pt.getActualTypeArguments()[0]);
}
return c;
}
throw new UnsupportedOperationException("Unknown type type : " + type.getClass().getName());
}
public static class JavaTypeRef extends TypeRef {
java.lang.reflect.Type type;
Class<? extends Annotation>[] annotations;
@Override
public StringBuilder getQualifiedName(StringBuilder b, boolean generic) {
return b.append(getTypeClass(this.type).getName());
}
@Override
public boolean matches(Type type, Annotations annotations) {
Class<?> tc = getTypeClass(this.type);
Class<?> typec = Demangler.getTypeClass(type);
if (tc == typec)
return true;
if ((type == Long.TYPE && Pointer.class.isAssignableFrom(tc)) ||
(Pointer.class.isAssignableFrom(typec) && tc == Long.TYPE))
return true;
if (type == Long.TYPE && annotations != null) {
boolean
isPtr = annotations.getAnnotation(Ptr.class) != null,
isCLong = annotations.getAnnotation(CLong.class) != null;
if (isPtr || isCLong)
return true;
}
if (tc == CLong.class) {
if ((typec == int.class || typec == Integer.class) && (JNI.CLONG_SIZE == 4) || typec == long.class || typec == Long.class)
return true;
} else if (tc == SizeT.class) {
if ((typec == int.class || typec == Integer.class) && (JNI.SIZE_T_SIZE == 4) || typec == long.class || typec == Long.class)
return true;
}
if ((tc == Character.TYPE || tc == Character.class || tc == short.class || tc == Short.class) && (typec == Short.class || typec == short.class || typec == char.class || typec == Character.class))
return true;
if ((tc == Integer.class || tc == int.class) && ValuedEnum.class.isAssignableFrom(typec))
return true;
return typec.equals(tc); // TODO isAssignableFrom or the opposite, depending on context
}
@Override
public String toString() {
StringBuilder b = new StringBuilder();
for (Class<?> ann : annotations)
b.append(ann.getSimpleName()).append(' ');
b.append((type instanceof Class<?>) ? ((Class<?>)type).getSimpleName() : type.toString());
return b.toString();
}
}
public static class ClassRef extends TypeRef {
private TypeRef enclosingType;
private Object simpleName;
TemplateArg[] templateArguments;
public ClassRef() {
}
public ClassRef(String simpleName) {
this.simpleName = simpleName;
}
public StringBuilder getQualifiedName(StringBuilder b, boolean generic) {
if (getEnclosingType() instanceof ClassRef) {
getEnclosingType().getQualifiedName(b, generic).append('$');
} else if (getEnclosingType() instanceof NamespaceRef) {
getEnclosingType().getQualifiedName(b, generic).append('.');
}
b.append(getSimpleName());
if (generic && templateArguments != null) {
int args = 0;
for (int i = 0, n = templateArguments.length; i < n; i++) {
TemplateArg arg = templateArguments[i];
if (!(arg instanceof TypeRef))
continue;
if (args == 0)
b.append('<');
else
b.append(", ");
((TypeRef)arg).getQualifiedName(b, generic);
args++;
}
if (args > 0)
b.append('>');
}
return b;
}
public void setSimpleName(Object simpleName) {
this.simpleName = simpleName;
}
public Object getSimpleName() {
return simpleName;
}
public void setEnclosingType(TypeRef enclosingType) {
this.enclosingType = enclosingType;
}
public TypeRef getEnclosingType() {
return enclosingType;
}
public void setTemplateArguments(TemplateArg[] templateArguments) {
this.templateArguments = templateArguments;
}
public TemplateArg[] getTemplateArguments() {
return templateArguments;
}
@Override
public boolean matches(Type type, Annotations annotations) {
if (!getTypeClass(type).getSimpleName().equals(simpleName))
return false;
return true;
}
@Override
public String toString() {
StringBuilder b = new StringBuilder();
if (enclosingType != null)
b.append(enclosingType).append('.');
b.append(simpleName);
appendTemplateArgs(b, templateArguments);
return b.toString();
}
}
static void appendTemplateArgs(StringBuilder b, Object[] params) {
if (params == null || params.length == 0)
return;
appendArgs(b, '<', '>', params);
}
static void appendArgs(StringBuilder b, char pre, char post, Object[] params) {
b.append(pre);
if (params != null)
for (int i = 0; i < params.length; i++) {
if (i != 0)
b.append(", ");
b.append(params[i]);
}
b.append(post);
}
public static class FunctionTypeRef extends TypeRef {
MemberRef function;
public FunctionTypeRef(MemberRef function) {
this.function = function;
}
@Override
public StringBuilder getQualifiedName(StringBuilder b, boolean generic) {
// TODO Auto-generated method stub
return null;
}
@Override
public String toString() {
return function.toString();
}
}
public enum SpecialName {
Constructor("", true, true),
SpecialConstructor("", true, true),
Destructor("", true, true),
SelfishDestructor("", true, true),
DeletingDestructor("", true, true),
New("new", true, true),
Delete("delete", true, true),
VFTable("vftable", false, true),
VBTable("vbtable", false, true),
VCall("vcall", false, false), // What is that ???
TypeOf("typeof", false, false),
ScalarDeletingDestructor("'scalar deleting destructor'", true, true),
VectorDeletingDestructor("'vector deleting destructor'", true, true),
OperatorAssign("operator=", true, true),
OperatorRShift("operator>>", true, true),
OperatorDivideAssign("operator/=", true, true),
OperatorModuloAssign("operator%=", true, true),
OperatorRShiftAssign("operator>>=", true, true),
OperatorLShiftAssign("operator<<=", true, true),
OperatorBitAndAssign("operator&=", true, true),
OperatorBitOrAssign("operator|=", true, true),
OperatorXORAssign("operator^=", true, true),
OperatorLShift("operator<<", true, true),
OperatorLogicNot("operator!", true, true),
OperatorEquals("operator==", true, true),
OperatorDifferent("operator!=", true, true),
OperatorSquareBrackets("operator[]", true, true),
OperatorCast("'some cast operator'", true, true),
OperatorArrow("operator->", true, true),
OperatorMultiply("operator*", true, true),
OperatorIncrement("operator++", true, true),
OperatorDecrement("operator--", true, true),
OperatorSubstract("operator-", true, true),
OperatorAdd("operator+", true, true),
OperatorBitAnd("operator&=", true, true),
/// Member pointer selector
OperatorArrowStar("operator->*", true, true),
OperatorDivide("operator/", true, true),
OperatorModulo("operator%", true, true),
OperatorLower("operator<", true, true),
OperatorLowerEquals("operator<=", true, true),
OperatorGreater("operator>", true, true),
OperatorGreaterEquals("operator>=", true, true),
OperatorComma("operator,", true, true),
OperatorParenthesis("operator()", true, true),
OperatorBitNot("operator~", true, true),
OperatorXOR("operator^", true, true),
OperatorBitOr("operator|", true, true),
OperatorLogicAnd("operator&&", true, true),
OperatorLogicOr("operator||", true, true),
OperatorMultiplyAssign("operator*=", true, true),
OperatorAddAssign("operator+=", true, true),
OperatorSubstractAssign("operator-=", true, true);
private SpecialName(String name, boolean isFunction, boolean isMember) {
this.name = name;
this.isFunction = isFunction;
this.isMember = isMember;
}
final String name;
final boolean isFunction;
final boolean isMember;
@Override
public String toString() {
return name;
}
public boolean isFunction() {
return isFunction;
}
public boolean isMember() {
return isMember;
}
}
public static class MemberRef {
private Integer argumentsStackSize;
private TypeRef enclosingType;
private TypeRef valueType;
private Object memberName;
Boolean isStatic, isProtected, isPrivate;
public int modifiers;
public TypeRef[] paramTypes, throwTypes;
TemplateArg[] templateArguments;
public Style callingConvention;
public Integer getArgumentsStackSize() {
return argumentsStackSize;
}
public void setArgumentsStackSize(Integer argumentsStackSize) {
this.argumentsStackSize = argumentsStackSize;
}
public boolean matchesSingleThisPointerVoidMethod(Class<?> type) {
if (getEnclosingType() != null && !getEnclosingType().matches(type, annotations(type)))
return false;
if (getValueType() != null && !getValueType().matches(Void.TYPE, null))
return false;
Type[] methodArgTypes = new Type[] { Long.TYPE };
if (!matchesArgs(methodArgTypes, null, true))
return false;
return true;
}
protected boolean matchesVirtualTable(Class<?> type) {
return memberName == SpecialName.VFTable && getEnclosingType() != null && getEnclosingType().matches(type, annotations(type));
}
protected boolean matchesConstructor(Class<?> type) {
return memberName == SpecialName.Constructor && matchesSingleThisPointerVoidMethod(type);
}
protected boolean matchesDestructor(Class<?> type) {
return memberName == SpecialName.Destructor && matchesSingleThisPointerVoidMethod(type);
}
static boolean hasInstance(Object[] array, Class<?>... cs) {
for (Object o : array)
for (Class<?> c : cs)
if (c.isInstance(o))
return true;
return false;
}
static int getArgumentsStackSize(Method method) {
int total = 0;
Type[] paramTypes = method.getGenericParameterTypes();
Annotation[][] anns = method.getParameterAnnotations();
for (int iArg = 0, nArgs = paramTypes.length; iArg < nArgs; iArg++) {
Class<?> paramType = getTypeClass(paramTypes[iArg]);
if (paramType == int.class)
total += 4;
else if (paramType == long.class) {
if (hasInstance(anns[iArg], Ptr.class, CLong.class))
total += Pointer.SIZE;
else
total += 8;
} else if (paramType == float.class)
total += 4;
else if (paramType == double.class)
total += 8;
else if (paramType == byte.class)
total += 1;
else if (paramType == char.class)
total += JNI.WCHAR_T_SIZE;
else if (paramType == short.class)
total += 2;
else if (paramType == boolean.class)
total += 1;
else if (Pointer.class.isAssignableFrom(paramType))
total += Pointer.SIZE;
else if (NativeObject.class.isAssignableFrom(paramType))
total += ((CRuntime)BridJ.getRuntime(paramType)).sizeOf(paramTypes[iArg], null);
else if (FlagSet.class.isAssignableFrom(paramType))
total += 4; // TODO
else
throw new RuntimeException("Type not handled : " + paramType.getName());
}
return total;
}
protected boolean matches(Method method) {
if (memberName instanceof SpecialName)
return false; // use matchesConstructor...
if (getArgumentsStackSize() != null && getArgumentsStackSize().intValue() != getArgumentsStackSize(method))
return false;
if (getEnclosingType() != null && !getEnclosingType().matches(method.getDeclaringClass(), annotations(method)))
return false;
if (getMemberName() != null && !getMemberName().equals(method.getName()))
return false;
if (getValueType() != null && !getValueType().matches(method.getReturnType(), annotations(method)))
return false;
Annotation[][] anns = method.getParameterAnnotations();
// Class<?>[] methodArgTypes = method.getParameterTypes();
Type[] parameterTypes = method.getGenericParameterTypes();
boolean hasThisAsFirstArgument = BridJ.hasThisAsFirstArgument(method);//methodArgTypes, anns, true);
if (!matchesArgs(parameterTypes, anns, hasThisAsFirstArgument))
return false;
//int thisDirac = hasThisAsFirstArgument ? 1 : 0;
/*
switch (type) {
case Constructor:
case Destructor:
Annotation ann = method.getAnnotation(type == SpecialName.Constructor ? Constructor.class : Destructor.class);
if (ann == null)
return false;
if (!hasThisAsFirstArgument)
return false;
if (methodArgTypes.length - thisDirac != 0 )
return false;
break;
case InstanceMethod:
if (!hasThisAsFirstArgument)
return false;
break;
case StaticMethod:
if (hasThisAsFirstArgument)
return false;
break;
}*/
return true;
}
private boolean matchesArgs(Type[] parameterTypes, Annotation[][] anns, boolean hasThisAsFirstArgument) {
int totalArgs = 0;
for (int i = 0, n = templateArguments == null ? 0 : templateArguments.length; i < n; i++) {
if (totalArgs >= parameterTypes.length)
return false;
Type paramType = parameterTypes[i];
TemplateArg arg = templateArguments[i];
if (arg instanceof TypeRef) {
if (!paramType.equals(Class.class))
return false;
} else if (arg instanceof Constant) {
try {
getTypeClass(paramType).cast(((Constant)arg).value);
} catch (ClassCastException ex) {
return false;
}
}
totalArgs++;
}
if (hasThisAsFirstArgument)
totalArgs++;
for (int i = 0, n = paramTypes == null ? 0 : paramTypes.length; i < n; i++) {
if (totalArgs >= parameterTypes.length)
return false;
if (!paramTypes[i].matches(parameterTypes[totalArgs], annotations(anns[i])))
return false;
totalArgs++;
}
if (totalArgs != parameterTypes.length)
return false;
return true;
}
@Override
public String toString() {
StringBuilder b = new StringBuilder();
b.append(valueType).append(' ');
boolean nameWritten = false;
if (enclosingType != null) {
b.append(enclosingType);
b.append('.');
if (memberName instanceof SpecialName) {
switch ((SpecialName)memberName) {
case Destructor:
b.append('~');
case Constructor:
b.append(((ClassRef)enclosingType).simpleName);
nameWritten = true;
break;
}
}
}
if (!nameWritten)
b.append(memberName);
appendTemplateArgs(b, templateArguments);
appendArgs(b, '(', ')', paramTypes);
return b.toString();
}
public void setMemberName(Object memberName) {
this.memberName = memberName;
}
public Object getMemberName() {
return memberName;
}
public void setValueType(TypeRef valueType) {
this.valueType = valueType;
}
public TypeRef getValueType() {
return valueType;
}
public void setEnclosingType(TypeRef enclosingType) {
this.enclosingType = enclosingType;
}
public TypeRef getEnclosingType() {
return enclosingType;
}
}
}
|
package com.facebook.litho;
import static com.facebook.litho.ComponentLifecycle.StateUpdate;
import static com.facebook.litho.FrameworkLogEvents.EVENT_LAYOUT_CALCULATE;
import static com.facebook.litho.FrameworkLogEvents.EVENT_PRE_ALLOCATE_MOUNT_CONTENT;
import static com.facebook.litho.FrameworkLogEvents.PARAM_IS_BACKGROUND_LAYOUT;
import static com.facebook.litho.FrameworkLogEvents.PARAM_LOG_TAG;
import static com.facebook.litho.FrameworkLogEvents.PARAM_TREE_DIFF_ENABLED;
import static com.facebook.litho.LayoutState.CalculateLayoutSource;
import static com.facebook.litho.ThreadUtils.assertHoldsLock;
import static com.facebook.litho.ThreadUtils.assertMainThread;
import static com.facebook.litho.ThreadUtils.isMainThread;
import android.content.Context;
import android.graphics.Rect;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.IntDef;
import android.support.annotation.Keep;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.VisibleForTesting;
import android.util.Log;
import android.view.View;
import android.view.ViewParent;
import com.facebook.infer.annotation.ReturnsOwnership;
import com.facebook.infer.annotation.ThreadConfined;
import com.facebook.infer.annotation.ThreadSafe;
import com.facebook.litho.annotations.MountSpec;
import com.facebook.litho.config.ComponentsConfiguration;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.CheckReturnValue;
import javax.annotation.concurrent.GuardedBy;
/**
* Represents a tree of components and controls their life cycle. ComponentTree takes in a single
* root component and recursively invokes its OnCreateLayout to create a tree of components.
* ComponentTree is responsible for refreshing the mounted state of a component with new props.
*
* The usual use case for {@link ComponentTree} is:
* <code>
* ComponentTree component = ComponentTree.create(context, MyComponent.create());
* myHostView.setRoot(component);
* <code/>
*/
@ThreadSafe
public class ComponentTree {
public static final int INVALID_ID = -1;
private static final String TAG = ComponentTree.class.getSimpleName();
private static final int SIZE_UNINITIALIZED = -1;
// MainThread Looper messages:
private static final int MESSAGE_WHAT_BACKGROUND_LAYOUT_STATE_UPDATED = 1;
private static final String DEFAULT_LAYOUT_THREAD_NAME = "ComponentLayoutThread";
private static final String DEFAULT_PMC_THREAD_NAME = "PreallocateMountContentThread";
private static final int DEFAULT_LAYOUT_THREAD_PRIORITY =
ComponentsConfiguration.defaultBackgroundThreadPriority;
private static final int SCHEDULE_NONE = 0;
private static final int SCHEDULE_LAYOUT_ASYNC = 1;
private static final int SCHEDULE_LAYOUT_SYNC = 2;
private final MeasureListener mMeasureListener;
private boolean mReleased;
private String mReleasedComponent;
@IntDef({SCHEDULE_NONE, SCHEDULE_LAYOUT_ASYNC, SCHEDULE_LAYOUT_SYNC})
@Retention(RetentionPolicy.SOURCE)
private @interface PendingLayoutCalculation {}
public interface MeasureListener {
void onSetRootAndSizeSpec(int width, int height);
}
private static final AtomicInteger sIdGenerator = new AtomicInteger(0);
private static final Handler sMainThreadHandler = new ComponentMainThreadHandler();
// Do not access sDefaultLayoutThreadLooper directly, use getDefaultLayoutThreadLooper().
@GuardedBy("ComponentTree.class")
private static volatile Looper sDefaultLayoutThreadLooper;
@GuardedBy("ComponentTree.class")
private static volatile Looper sDefaultPreallocateMountContentThreadLooper;
private static final ThreadLocal<WeakReference<Handler>> sSyncStateUpdatesHandler =
new ThreadLocal<>();
// Helpers to track view visibility when we are incrementally
// mounting and partially invalidating
private static final int[] sCurrentLocation = new int[2];
private static final int[] sParentLocation = new int[2];
private static final Rect sParentBounds = new Rect();
@Nullable private final IncrementalMountHelper mIncrementalMountHelper;
private final boolean mShouldPreallocatePerMountSpec;
private final Runnable mPreAllocateMountContentRunnable =
new Runnable() {
@Override
public void run() {
preAllocateMountContent(mShouldPreallocatePerMountSpec);
}
};
private final Runnable mUpdateStateSyncRunnable = new Runnable() {
@Override
public void run() {
updateStateInternal(false);
}
};
private final ComponentContext mContext;
private final boolean mCanPrefetchDisplayLists;
private final boolean mCanCacheDrawingDisplayLists;
private final boolean mShouldClipChildren;
@Nullable private LayoutHandler mPreAllocateMountContentHandler;
// These variables are only accessed from the main thread.
@ThreadConfined(ThreadConfined.UI)
private boolean mIsMounting;
@ThreadConfined(ThreadConfined.UI)
private final boolean mIncrementalMountEnabled;
@ThreadConfined(ThreadConfined.UI)
private final boolean mIsLayoutDiffingEnabled;
@ThreadConfined(ThreadConfined.UI)
private boolean mIsAttached;
@ThreadConfined(ThreadConfined.UI)
private final boolean mIsAsyncUpdateStateEnabled;
@ThreadConfined(ThreadConfined.UI)
private LithoView mLithoView;
@ThreadConfined(ThreadConfined.UI)
private LayoutHandler mLayoutThreadHandler;
@GuardedBy("this")
private boolean mHasViewMeasureSpec;
private final Object mCurrentCalculateLayoutRunnableLock = new Object();
@GuardedBy("mCurrentCalculateLayoutRunnableLock")
private @Nullable CalculateLayoutRunnable mCurrentCalculateLayoutRunnable;
private boolean mHasMounted = false;
// TODO(6606683): Enable recycling of mComponent.
// We will need to ensure there are no background threads referencing mComponent. We'll need
// to keep a reference count or something. :-/
@Nullable
@GuardedBy("this")
private Component mRoot;
@GuardedBy("this")
private int mWidthSpec = SIZE_UNINITIALIZED;
@GuardedBy("this")
private int mHeightSpec = SIZE_UNINITIALIZED;
// This is written to only by the main thread with the lock held, read from the main thread with
// no lock held, or read from any other thread with the lock held.
@Nullable
private LayoutState mMainThreadLayoutState;
// The semantics here are tricky. Whenever you transfer mBackgroundLayoutState to a local that
// will be accessed outside of the lock, you must set mBackgroundLayoutState to null to ensure
// that the current thread alone has access to the LayoutState, which is single-threaded.
@GuardedBy("this")
@Nullable
private LayoutState mBackgroundLayoutState;
@GuardedBy("this")
private StateHandler mStateHandler;
@ThreadConfined(ThreadConfined.UI)
private RenderState mPreviousRenderState;
@ThreadConfined(ThreadConfined.UI)
private boolean mPreviousRenderStateSetFromBuilder = false;
private final Object mLayoutLock;
protected final int mId;
@GuardedBy("this")
private boolean mIsMeasuring;
@PendingLayoutCalculation
@GuardedBy("this")
private int mScheduleLayoutAfterMeasure;
@GuardedBy("mEventHandlers")
public final Map<String, EventHandlersWrapper> mEventHandlers = new LinkedHashMap<>();
@GuardedBy("mEventTriggersContainer")
private final EventTriggersContainer mEventTriggersContainer = new EventTriggersContainer();
public static Builder create(ComponentContext context, Component.Builder<?> root) {
return create(context, root.build());
}
public static Builder create(ComponentContext context, @NonNull Component root) {
if (root == null) {
throw new NullPointerException("Creating a ComponentTree with a null root is not allowed!");
}
return ComponentsPools.acquireComponentTreeBuilder(context, root);
}
protected ComponentTree(Builder builder) {
mContext = ComponentContext.withComponentTree(builder.context, this);
mRoot = builder.root;
mIncrementalMountEnabled = builder.incrementalMountEnabled;
mIsLayoutDiffingEnabled = builder.isLayoutDiffingEnabled;
mLayoutThreadHandler = builder.layoutThreadHandler;
mShouldPreallocatePerMountSpec = builder.shouldPreallocatePerMountSpec;
mPreAllocateMountContentHandler = builder.preAllocateMountContentHandler;
mLayoutLock = builder.layoutLock;
mIsAsyncUpdateStateEnabled = builder.asyncStateUpdates;
mCanPrefetchDisplayLists = builder.canPrefetchDisplayLists;
mCanCacheDrawingDisplayLists = builder.canCacheDrawingDisplayLists;
mShouldClipChildren = builder.shouldClipChildren;
mHasMounted = builder.hasMounted;
mMeasureListener = builder.mMeasureListener;
if (mLayoutThreadHandler == null) {
mLayoutThreadHandler = new DefaultLayoutHandler(getDefaultLayoutThreadLooper());
}
if (mPreAllocateMountContentHandler == null && builder.canPreallocateOnDefaultHandler) {
mPreAllocateMountContentHandler =
new DefaultPreallocateMountContentHandler(
getDefaultPreallocateMountContentThreadLooper());
}
final StateHandler builderStateHandler = builder.stateHandler;
mStateHandler = builderStateHandler == null
? StateHandler.acquireNewInstance(null)
: builderStateHandler;
if (builder.previousRenderState != null) {
mPreviousRenderState = builder.previousRenderState;
mPreviousRenderStateSetFromBuilder = true;
}
if (builder.overrideComponentTreeId != -1) {
mId = builder.overrideComponentTreeId;
} else {
mId = generateComponentTreeId();
}
mIncrementalMountHelper =
ComponentsConfiguration.USE_INCREMENTAL_MOUNT_HELPER
? new IncrementalMountHelper(this)
: null;
}
@Nullable
@ThreadConfined(ThreadConfined.UI)
LayoutState getMainThreadLayoutState() {
return mMainThreadLayoutState;
}
@Nullable
@VisibleForTesting
@GuardedBy("this")
protected LayoutState getBackgroundLayoutState() {
return mBackgroundLayoutState;
}
/**
* Picks the best LayoutState and sets it in mMainThreadLayoutState. The return value is a
* LayoutState that must be released (after the lock is released). This awkward contract is
* necessary to ensure thread-safety.
*/
@CheckReturnValue
@ReturnsOwnership
@ThreadConfined(ThreadConfined.UI)
@GuardedBy("this")
private LayoutState setBestMainThreadLayoutAndReturnOldLayout() {
assertHoldsLock(this);
// If everything matches perfectly then we prefer mMainThreadLayoutState
// because that means we don't need to remount.
final boolean isMainThreadLayoutBest;
if (isCompatibleComponentAndSpec(mMainThreadLayoutState)) {
isMainThreadLayoutBest = true;
} else if (isCompatibleSpec(mBackgroundLayoutState, mWidthSpec, mHeightSpec)
|| !isCompatibleSpec(mMainThreadLayoutState, mWidthSpec, mHeightSpec)) {
// If mMainThreadLayoutState isn't a perfect match, we'll prefer
// mBackgroundLayoutState since it will have the more recent create.
isMainThreadLayoutBest = false;
} else {
// If the main thread layout is still compatible size-wise, and the
// background one is not, then we'll do nothing. We want to keep the same
// main thread layout so that we don't force main thread re-layout.
isMainThreadLayoutBest = true;
}
if (isMainThreadLayoutBest) {
// We don't want to hold onto mBackgroundLayoutState since it's unlikely
// to ever be used again. We return mBackgroundLayoutState to indicate it
// should be released after exiting the lock.
final LayoutState toRelease = mBackgroundLayoutState;
mBackgroundLayoutState = null;
return toRelease;
} else {
// Since we are changing layout states we'll need to remount.
if (mLithoView != null) {
mLithoView.setMountStateDirty();
}
final LayoutState toRelease = mMainThreadLayoutState;
mMainThreadLayoutState = mBackgroundLayoutState;
mBackgroundLayoutState = null;
return toRelease;
}
}
private void backgroundLayoutStateUpdated() {
assertMainThread();
// If we aren't attached, then we have nothing to do. We'll handle
// everything in onAttach.
if (!mIsAttached) {
return;
}
LayoutState toRelease;
final boolean layoutStateUpdated;
final int componentRootId;
synchronized (this) {
if (mRoot == null) {
// We have been released. Abort.
return;
}
final LayoutState oldMainThreadLayoutState = mMainThreadLayoutState;
toRelease = setBestMainThreadLayoutAndReturnOldLayout();
layoutStateUpdated = (mMainThreadLayoutState != oldMainThreadLayoutState);
componentRootId = mRoot.getId();
}
if (toRelease != null) {
toRelease.releaseRef();
toRelease = null;
}
if (!layoutStateUpdated) {
return;
}
// We defer until measure if we don't yet have a width/height
final int viewWidth = mLithoView.getMeasuredWidth();
final int viewHeight = mLithoView.getMeasuredHeight();
if (viewWidth == 0 && viewHeight == 0) {
// The host view has not been measured yet.
return;
}
final boolean needsAndroidLayout =
!isCompatibleComponentAndSize(
mMainThreadLayoutState,
componentRootId,
viewWidth,
viewHeight);
if (needsAndroidLayout) {
mLithoView.requestLayout();
} else {
mountComponentIfDirty();
}
}
void attach() {
assertMainThread();
if (mLithoView == null) {
throw new IllegalStateException("Trying to attach a ComponentTree without a set View");
}
if (mIncrementalMountHelper != null) {
mIncrementalMountHelper.onAttach(mLithoView);
}
LayoutState toRelease;
final int componentRootId;
synchronized (this) {
// We need to track that we are attached regardless...
mIsAttached = true;
// ... and then we do state transfer
toRelease = setBestMainThreadLayoutAndReturnOldLayout();
if (mRoot == null) {
throw new IllegalStateException(
"Trying to attach a ComponentTree with a null root. Is released: "
+ mReleased
+ ", Released Component name is: "
+ mReleasedComponent);
}
componentRootId = mRoot.getId();
}
if (toRelease != null) {
toRelease.releaseRef();
toRelease = null;
}
// We defer until measure if we don't yet have a width/height
final int viewWidth = mLithoView.getMeasuredWidth();
final int viewHeight = mLithoView.getMeasuredHeight();
if (viewWidth == 0 && viewHeight == 0) {
// The host view has not been measured yet.
return;
}
final boolean needsAndroidLayout =
!isCompatibleComponentAndSize(
mMainThreadLayoutState,
componentRootId,
viewWidth,
viewHeight);
if (needsAndroidLayout || mLithoView.isMountStateDirty()) {
mLithoView.requestLayout();
} else {
mLithoView.rebind();
}
}
private static boolean hasSameRootContext(Context context1, Context context2) {
return ContextUtils.getRootContext(context1) == ContextUtils.getRootContext(context2);
}
@ThreadConfined(ThreadConfined.UI)
boolean isMounting() {
return mIsMounting;
}
private boolean mountComponentIfDirty() {
if (mLithoView.isMountStateDirty()) {
if (mIncrementalMountEnabled) {
incrementalMountComponent();
} else {
mountComponent(null, true);
}
return true;
}
return false;
}
void incrementalMountComponent() {
assertMainThread();
if (!mIncrementalMountEnabled) {
throw new IllegalStateException("Calling incrementalMountComponent() but incremental mount" +
" is not enabled");
}
if (mLithoView == null || mLithoView.doesOwnIncrementalMount()) {
return;
}
// Per ComponentTree visible area. Because LithoViews can be nested and mounted
// not in "depth order", this variable cannot be static.
final Rect currentVisibleArea = ComponentsPools.acquireRect();
if (getVisibleRect(currentVisibleArea)
|| animatingLithoViewBoundsOnFirstMount(currentVisibleArea)) {
mountComponent(currentVisibleArea, true);
}
// if false: no-op, doesn't have visible area, is not ready or not attached
ComponentsPools.release(currentVisibleArea);
}
private boolean getVisibleRect(Rect visibleBounds) {
assertMainThread();
if (ComponentsConfiguration.incrementalMountUsesLocalVisibleBounds) {
return mLithoView.getLocalVisibleRect(visibleBounds);
}
getLocationAndBoundsOnScreen(mLithoView, sCurrentLocation, visibleBounds);
final ViewParent viewParent = mLithoView.getParent();
if (viewParent instanceof View) {
final View parent = (View) viewParent;
getLocationAndBoundsOnScreen(parent, sParentLocation, sParentBounds);
if (!visibleBounds.setIntersect(visibleBounds, sParentBounds)) {
return false;
}
}
visibleBounds.offset(-sCurrentLocation[0], -sCurrentLocation[1]);
return true;
}
private boolean animatingLithoViewBoundsOnFirstMount(Rect visibleBounds) {
// We might be animating bounds of LithoView from 0 width/height on first mount, so we need to
// make sure to initiate mounting so that the animation properties are applied.
return !mHasMounted
&& ((hasLithoViewHeightAnimation() && visibleBounds.height() == 0)
|| (hasLithoViewWidthAnimation() && visibleBounds.width() == 0));
}
private static void getLocationAndBoundsOnScreen(View view, int[] location, Rect bounds) {
assertMainThread();
view.getLocationOnScreen(location);
bounds.set(
location[0], location[1], location[0] + view.getWidth(), location[1] + view.getHeight());
}
/** @see LayoutState#hasLithoViewWidthAnimation() */
@ThreadConfined(ThreadConfined.UI)
boolean hasLithoViewWidthAnimation() {
assertMainThread();
return mMainThreadLayoutState != null && mMainThreadLayoutState.hasLithoViewWidthAnimation();
}
/** @see LayoutState#hasLithoViewHeightAnimation() */
@ThreadConfined(ThreadConfined.UI)
boolean hasLithoViewHeightAnimation() {
assertMainThread();
return mMainThreadLayoutState != null && mMainThreadLayoutState.hasLithoViewHeightAnimation();
}
void mountComponent(Rect currentVisibleArea, boolean processVisibilityOutputs) {
assertMainThread();
if (mMainThreadLayoutState == null) {
Log.w(TAG, "Main Thread Layout state is not found");
return;
}
final boolean isDirtyMount = mLithoView.isMountStateDirty();
mIsMounting = true;
if (isDirtyMount) {
applyPreviousRenderData(mMainThreadLayoutState);
}
if (!mHasMounted) {
mLithoView.getMountState().setIsFirstMountOfComponentTree();
mHasMounted = true;
}
// currentVisibleArea null or empty => mount all
mLithoView.mount(mMainThreadLayoutState, currentVisibleArea, processVisibilityOutputs);
if (isDirtyMount) {
recordRenderData(mMainThreadLayoutState);
}
mIsMounting = false;
if (isDirtyMount) {
mLithoView.onDirtyMountComplete();
}
}
private void applyPreviousRenderData(LayoutState layoutState) {
final List<Component> components = layoutState.getComponentsNeedingPreviousRenderData();
if (components == null || components.isEmpty()) {
return;
}
if (mPreviousRenderState == null) {
return;
}
mPreviousRenderState.applyPreviousRenderData(components);
}
private void recordRenderData(LayoutState layoutState) {
final List<Component> components = layoutState.getComponentsNeedingPreviousRenderData();
if (components == null || components.isEmpty()) {
return;
}
if (mPreviousRenderState == null) {
mPreviousRenderState = ComponentsPools.acquireRenderState();
}
mPreviousRenderState.recordRenderData(components);
}
void detach() {
assertMainThread();
if (mIncrementalMountHelper != null) {
mIncrementalMountHelper.onDetach(mLithoView);
}
synchronized (this) {
mIsAttached = false;
mHasViewMeasureSpec = false;
}
}
/**
* Set a new LithoView to this ComponentTree checking that they have the same context and
* clear the ComponentTree reference from the previous LithoView if any.
* Be sure this ComponentTree is detach first.
*/
void setLithoView(@NonNull LithoView view) {
assertMainThread();
// It's possible that the view associated with this ComponentTree was recycled but was
// never detached. In all cases we have to make sure that the old references between
// lithoView and componentTree are reset.
if (mIsAttached) {
if (mLithoView != null) {
mLithoView.setComponentTree(null);
} else {
detach();
}
} else if (mLithoView != null) {
// Remove the ComponentTree reference from a previous view if any.
mLithoView.clearComponentTree();
}
if (!hasSameRootContext(view.getContext(), mContext)) {
// This would indicate bad things happening, like leaking a context.
throw new IllegalArgumentException(
"Base view context differs, view context is: " + view.getContext() +
", ComponentTree context is: " + mContext);
}
mLithoView = view;
}
void clearLithoView() {
assertMainThread();
// Crash if the ComponentTree is mounted to a view.
if (mIsAttached) {
throw new IllegalStateException(
"Clearing the LithoView while the ComponentTree is attached");
}
mLithoView = null;
}
void measure(int widthSpec, int heightSpec, int[] measureOutput, boolean forceLayout) {
assertMainThread();
Component component = null;
LayoutState toRelease;
synchronized (this) {
mIsMeasuring = true;
// This widthSpec/heightSpec is fixed until the view gets detached.
mWidthSpec = widthSpec;
mHeightSpec = heightSpec;
mHasViewMeasureSpec = true;
toRelease = setBestMainThreadLayoutAndReturnOldLayout();
if (forceLayout || !isCompatibleComponentAndSpec(mMainThreadLayoutState)) {
// Neither layout was compatible and we have to perform a layout.
// Since outputs get set on the same object during the lifecycle calls,
// we need to copy it in order to use it concurrently.
component = mRoot.makeShallowCopy();
}
}
if (toRelease != null) {
toRelease.releaseRef();
toRelease = null;
}
if (component != null) {
// TODO: We should re-use the existing CSSNodeDEPRECATED tree instead of re-creating it.
if (mMainThreadLayoutState != null) {
// It's beneficial to delete the old layout state before we start creating a new one since
// we'll be able to re-use some of the layout nodes.
final LayoutState localLayoutState;
synchronized (this) {
localLayoutState = mMainThreadLayoutState;
mMainThreadLayoutState = null;
}
localLayoutState.releaseRef();
}
// We have no layout that matches the given spec, so we need to compute it on the main thread.
LayoutState localLayoutState =
calculateLayoutState(
mLayoutLock,
mContext,
component,
widthSpec,
heightSpec,
mIsLayoutDiffingEnabled,
null,
CalculateLayoutSource.MEASURE);
final StateHandler layoutStateStateHandler =
localLayoutState.consumeStateHandler();
final List<Component> components = new ArrayList<>(localLayoutState.getComponents());
synchronized (this) {
if (layoutStateStateHandler != null) {
mStateHandler.commit(layoutStateStateHandler);
}
localLayoutState.clearComponents();
mMainThreadLayoutState = localLayoutState;
localLayoutState = null;
}
clearUnusedTriggerHandlers();
for (final Component layoutComponent : components) {
bindEventHandler(layoutComponent);
bindTriggerHandler(layoutComponent);
}
clearUnusedEventHandlers();
// We need to force remount on layout
mLithoView.setMountStateDirty();
}
measureOutput[0] = mMainThreadLayoutState.getWidth();
measureOutput[1] = mMainThreadLayoutState.getHeight();
int layoutScheduleType = SCHEDULE_NONE;
Component root = null;
synchronized (this) {
mIsMeasuring = false;
if (mScheduleLayoutAfterMeasure != SCHEDULE_NONE) {
layoutScheduleType = mScheduleLayoutAfterMeasure;
mScheduleLayoutAfterMeasure = SCHEDULE_NONE;
root = mRoot.makeShallowCopy();
}
}
if (layoutScheduleType != SCHEDULE_NONE) {
setRootAndSizeSpecInternal(
root,
SIZE_UNINITIALIZED,
SIZE_UNINITIALIZED,
layoutScheduleType == SCHEDULE_LAYOUT_ASYNC,
null /*output */,
CalculateLayoutSource.MEASURE);
}
}
/**
* Returns {@code true} if the layout call mounted the component.
*/
boolean layout() {
assertMainThread();
return mountComponentIfDirty();
}
/**
* Returns whether incremental mount is enabled or not in this component.
*/
public boolean isIncrementalMountEnabled() {
return mIncrementalMountEnabled;
}
synchronized Component getRoot() {
return mRoot;
}
/**
* Update the root component. This can happen in both attached and detached states. In each case
* we will run a layout and then proxy a message to the main thread to cause a
* relayout/invalidate.
*/
public void setRoot(Component rootComponent) {
if (rootComponent == null) {
throw new IllegalArgumentException("Root component can't be null");
}
setRootAndSizeSpecInternal(
rootComponent,
SIZE_UNINITIALIZED,
SIZE_UNINITIALIZED,
false /* isAsync */,
null /* output */,
CalculateLayoutSource.SET_ROOT);
}
/**
* Pre-allocate the mount content of all MountSpec in this tree. Must be called after layout is
* created.
*/
@ThreadSafe(enableChecks = false)
private void preAllocateMountContent(boolean shouldPreallocatePerMountSpec) {
final LayoutState toPrePopulate;
synchronized (this) {
if (mMainThreadLayoutState != null) {
toPrePopulate = mMainThreadLayoutState.acquireRef();
} else if (mBackgroundLayoutState != null) {
toPrePopulate = mBackgroundLayoutState.acquireRef();
} else {
return;
}
}
final ComponentsLogger logger = mContext.getLogger();
LogEvent event = null;
if (logger != null) {
event = logger.newPerformanceEvent(EVENT_PRE_ALLOCATE_MOUNT_CONTENT);
event.addParam(PARAM_LOG_TAG, mContext.getLogTag());
}
toPrePopulate.preAllocateMountContent(shouldPreallocatePerMountSpec);
if (logger != null) {
logger.log(event);
}
toPrePopulate.releaseRef();
}
public void setRootAsync(Component rootComponent) {
if (rootComponent == null) {
throw new IllegalArgumentException("Root component can't be null");
}
setRootAndSizeSpecInternal(
rootComponent,
SIZE_UNINITIALIZED,
SIZE_UNINITIALIZED,
true /* isAsync */,
null /* output */,
CalculateLayoutSource.SET_ROOT);
}
synchronized void updateStateLazy(String componentKey, StateUpdate stateUpdate) {
if (mRoot == null) {
return;
}
mStateHandler.queueStateUpdate(componentKey, stateUpdate);
}
void updateStateSync(String componentKey, StateUpdate stateUpdate) {
synchronized (this) {
if (mRoot == null) {
return;
}
mStateHandler.queueStateUpdate(componentKey, stateUpdate);
}
final Looper looper = Looper.myLooper();
if (looper == null) {
Log.w(
TAG,
"You cannot update state synchronously from a thread without a looper, " +
"using the default background layout thread instead");
mLayoutThreadHandler.removeCallbacks(mUpdateStateSyncRunnable);
mLayoutThreadHandler.post(mUpdateStateSyncRunnable);
return;
}
final Handler handler;
synchronized (sSyncStateUpdatesHandler) {
final WeakReference<Handler> handlerWr = sSyncStateUpdatesHandler.get();
if (handlerWr != null && handlerWr.get() != null) {
handler = handlerWr.get();
handler.removeCallbacks(mUpdateStateSyncRunnable);
} else {
handler = new Handler(looper);
sSyncStateUpdatesHandler.set(new WeakReference<>(handler));
}
}
handler.post(mUpdateStateSyncRunnable);
}
void updateStateAsync(String componentKey, StateUpdate stateUpdate) {
if (!mIsAsyncUpdateStateEnabled) {
throw new RuntimeException("Triggering async state updates on this component tree is " +
"disabled, use sync state updates.");
}
synchronized (this) {
if (mRoot == null) {
return;
}
mStateHandler.queueStateUpdate(componentKey, stateUpdate);
}
updateStateInternal(true);
}
void updateStateInternal(boolean isAsync) {
final Component root;
synchronized (this) {
if (mRoot == null) {
return;
}
if (mIsMeasuring) {
// If the layout calculation was already scheduled to happen synchronously let's just go
// with a sync layout calculation.
if (mScheduleLayoutAfterMeasure == SCHEDULE_LAYOUT_SYNC) {
return;
}
mScheduleLayoutAfterMeasure = isAsync ? SCHEDULE_LAYOUT_ASYNC : SCHEDULE_LAYOUT_SYNC;
return;
}
root = mRoot.makeShallowCopy();
}
setRootAndSizeSpecInternal(
root,
SIZE_UNINITIALIZED,
SIZE_UNINITIALIZED,
isAsync,
null /*output */,
CalculateLayoutSource.UPDATE_STATE);
}
private void bindEventHandler(Component component) {
final String key = component.getGlobalKey();
if (key == null) {
return;
}
synchronized (mEventHandlers) {
final EventHandlersWrapper eventHandlers = mEventHandlers.get(key);
if (eventHandlers == null) {
return;
}
// Mark that the list of event handlers for this component is still needed.
eventHandlers.boundInCurrentLayout = true;
eventHandlers.bindToDispatcherComponent(component);
}
}
private void clearUnusedEventHandlers() {
synchronized (mEventHandlers) {
final Iterator iterator = mEventHandlers.keySet().iterator();
while (iterator.hasNext()) {
if (!mEventHandlers.get(iterator.next()).boundInCurrentLayout) {
iterator.remove();
}
}
}
}
void recordEventHandler(Component component, EventHandler eventHandler) {
final String key = component.getGlobalKey();
if (key == null) {
return;
}
synchronized (mEventHandlers) {
EventHandlersWrapper eventHandlers = mEventHandlers.get(key);
if (eventHandlers == null) {
eventHandlers = new EventHandlersWrapper();
mEventHandlers.put(key, eventHandlers);
}
eventHandlers.addEventHandler(eventHandler);
}
}
private void bindTriggerHandler(Component component) {
synchronized (mEventTriggersContainer) {
component.recordEventTrigger(mEventTriggersContainer);
}
}
private void clearUnusedTriggerHandlers() {
synchronized (mEventTriggersContainer) {
mEventTriggersContainer.clear();
}
}
@Nullable
EventTrigger getEventTrigger(String triggerKey) {
synchronized (mEventTriggersContainer) {
return mEventTriggersContainer.getEventTrigger(triggerKey);
}
}
/**
* Update the width/height spec. This is useful if you are currently detached and are responding
* to a configuration change. If you are currently attached then the HostView is the source of
* truth for width/height, so this call will be ignored.
*/
public void setSizeSpec(int widthSpec, int heightSpec) {
setSizeSpec(widthSpec, heightSpec, null);
}
/**
* Same as {@link #setSizeSpec(int, int)} but fetches the resulting width/height
* in the given {@link Size}.
*/
public void setSizeSpec(int widthSpec, int heightSpec, Size output) {
setRootAndSizeSpecInternal(
null,
widthSpec,
heightSpec,
false /* isAsync */,
output /* output */,
CalculateLayoutSource.SET_SIZE_SPEC);
}
public void setSizeSpecAsync(int widthSpec, int heightSpec) {
setRootAndSizeSpecInternal(
null,
widthSpec,
heightSpec,
true /* isAsync */,
null /* output */,
CalculateLayoutSource.SET_SIZE_SPEC);
}
/**
* Compute asynchronously a new layout with the given component root and sizes
*/
public void setRootAndSizeSpecAsync(Component root, int widthSpec, int heightSpec) {
if (root == null) {
throw new IllegalArgumentException("Root component can't be null");
}
setRootAndSizeSpecInternal(
root,
widthSpec,
heightSpec,
true /* isAsync */,
null /* output */,
CalculateLayoutSource.SET_ROOT);
}
/**
* Compute a new layout with the given component root and sizes
*/
public void setRootAndSizeSpec(Component root, int widthSpec, int heightSpec) {
if (root == null) {
throw new IllegalArgumentException("Root component can't be null");
}
setRootAndSizeSpecInternal(
root,
widthSpec,
heightSpec,
false /* isAsync */,
null /* output */,
CalculateLayoutSource.SET_ROOT);
}
public void setRootAndSizeSpec(Component root, int widthSpec, int heightSpec, Size output) {
if (root == null) {
throw new IllegalArgumentException("Root component can't be null");
}
setRootAndSizeSpecInternal(
root, widthSpec, heightSpec, false /* isAsync */, output, CalculateLayoutSource.SET_ROOT);
}
/**
* @return the {@link LithoView} associated with this ComponentTree if any.
*/
@Keep
@Nullable
public LithoView getLithoView() {
assertMainThread();
return mLithoView;
}
/**
* Provides a new instance from the StateHandler pool that is initialized with the information
* from the StateHandler currently held by the ComponentTree. Once the state updates have been
* applied and we are back in the main thread the state handler gets released to the pool.
* @return a copy of the state handler instance held by ComponentTree.
*/
public synchronized StateHandler getStateHandler() {
return StateHandler.acquireNewInstance(mStateHandler);
}
/**
* Takes ownership of the {@link RenderState} object from this ComponentTree - this allows the
* RenderState to be persisted somewhere and then set back on another ComponentTree using the
* {@link Builder}. See {@link RenderState} for more information on the purpose of this object.
*/
@ThreadConfined(ThreadConfined.UI)
public RenderState consumePreviousRenderState() {
final RenderState previousRenderState = mPreviousRenderState;
mPreviousRenderState = null;
mPreviousRenderStateSetFromBuilder = false;
return previousRenderState;
}
/**
* @deprecated
* @see #showTooltip(LithoTooltip, String, int, int)
*/
@Deprecated
void showTooltip(
DeprecatedLithoTooltip tooltip,
String anchorGlobalKey,
TooltipPosition tooltipPosition,
int xOffset,
int yOffset) {
assertMainThread();
final Map<String, Rect> componentKeysToBounds;
synchronized (this) {
componentKeysToBounds =
mMainThreadLayoutState.getComponentKeyToBounds();
}
if (!componentKeysToBounds.containsKey(anchorGlobalKey)) {
throw new IllegalArgumentException(
"Cannot find a component with key " + anchorGlobalKey + " to use as anchor.");
}
final Rect anchorBounds = componentKeysToBounds.get(anchorGlobalKey);
LithoTooltipController.showOnAnchor(
tooltip,
anchorBounds,
mLithoView,
tooltipPosition,
xOffset,
yOffset);
}
void showTooltip(LithoTooltip lithoTooltip, String anchorGlobalKey, int xOffset, int yOffset) {
assertMainThread();
final Map<String, Rect> componentKeysToBounds;
synchronized (this) {
componentKeysToBounds = mMainThreadLayoutState.getComponentKeyToBounds();
}
if (!componentKeysToBounds.containsKey(anchorGlobalKey)) {
throw new IllegalArgumentException(
"Cannot find a component with key " + anchorGlobalKey + " to use as anchor.");
}
final Rect anchorBounds = componentKeysToBounds.get(anchorGlobalKey);
lithoTooltip.showLithoTooltip(mLithoView, anchorBounds, xOffset, yOffset);
}
private void setRootAndSizeSpecInternal(
Component root,
int widthSpec,
int heightSpec,
boolean isAsync,
Size output,
@CalculateLayoutSource int source) {
synchronized (this) {
final Map<String, List<StateUpdate>> pendingStateUpdates =
mStateHandler.getPendingStateUpdates();
if (pendingStateUpdates != null && pendingStateUpdates.size() > 0 && root != null) {
root = root.makeShallowCopyWithNewId();
}
final boolean rootInitialized = root != null;
final boolean widthSpecInitialized = widthSpec != SIZE_UNINITIALIZED;
final boolean heightSpecInitialized = heightSpec != SIZE_UNINITIALIZED;
if (mHasViewMeasureSpec && !rootInitialized) {
// It doesn't make sense to specify the width/height while the HostView is attached and it
// has been measured. We do not throw an Exception only because there can be race conditions
// that can cause this to happen. In such race conditions, ignoring the setSizeSpec call is
// the right thing to do.
return;
}
final boolean widthSpecDidntChange = !widthSpecInitialized || widthSpec == mWidthSpec;
final boolean heightSpecDidntChange = !heightSpecInitialized || heightSpec == mHeightSpec;
final boolean sizeSpecDidntChange = widthSpecDidntChange && heightSpecDidntChange;
final LayoutState mostRecentLayoutState =
mBackgroundLayoutState != null ? mBackgroundLayoutState : mMainThreadLayoutState;
final boolean allSpecsWereInitialized =
widthSpecInitialized &&
heightSpecInitialized &&
mWidthSpec != SIZE_UNINITIALIZED &&
mHeightSpec != SIZE_UNINITIALIZED;
final boolean sizeSpecsAreCompatible =
sizeSpecDidntChange ||
(allSpecsWereInitialized &&
mostRecentLayoutState != null &&
LayoutState.hasCompatibleSizeSpec(
mWidthSpec,
mHeightSpec,
widthSpec,
heightSpec,
mostRecentLayoutState.getWidth(),
mostRecentLayoutState.getHeight()));
final boolean rootDidntChange = !rootInitialized || root.getId() == mRoot.getId();
if (rootDidntChange && sizeSpecsAreCompatible) {
// The spec and the root haven't changed. Either we have a layout already, or we're
// currently computing one on another thread.
if (output == null) {
return;
}
// Set the output if we have a LayoutState, otherwise we need to compute one synchronously
// below to get the correct output.
if (mostRecentLayoutState != null) {
output.height = mostRecentLayoutState.getHeight();
output.width = mostRecentLayoutState.getWidth();
return;
}
}
if (widthSpecInitialized) {
mWidthSpec = widthSpec;
}
if (heightSpecInitialized) {
mHeightSpec = heightSpec;
}
if (rootInitialized) {
mRoot = root;
}
}
if (isAsync && output != null) {
throw new IllegalArgumentException("The layout can't be calculated asynchronously if" +
" we need the Size back");
} else if (isAsync) {
synchronized (mCurrentCalculateLayoutRunnableLock) {
if (mCurrentCalculateLayoutRunnable != null) {
mLayoutThreadHandler.removeCallbacks(mCurrentCalculateLayoutRunnable);
}
mCurrentCalculateLayoutRunnable = new CalculateLayoutRunnable(source);
mLayoutThreadHandler.post(mCurrentCalculateLayoutRunnable);
}
} else {
calculateLayout(output, source);
}
}
/**
* Calculates the layout.
*
* @param output a destination where the size information should be saved
*/
private void calculateLayout(Size output, @CalculateLayoutSource int source) {
final int widthSpec;
final int heightSpec;
final Component root;
LayoutState previousLayoutState = null;
// Cancel any scheduled layout requests we might have in the background queue
// since we are starting a new layout computation.
synchronized (mCurrentCalculateLayoutRunnableLock) {
if (mCurrentCalculateLayoutRunnable != null) {
mLayoutThreadHandler.removeCallbacks(mCurrentCalculateLayoutRunnable);
mCurrentCalculateLayoutRunnable = null;
}
}
synchronized (this) {
// Can't compute a layout if specs or root are missing
if (!hasSizeSpec() || mRoot == null) {
return;
}
// Check if we already have a compatible layout.
if (hasCompatibleComponentAndSpec()) {
if (output != null) {
final LayoutState mostRecentLayoutState =
mBackgroundLayoutState != null ? mBackgroundLayoutState : mMainThreadLayoutState;
output.width = mostRecentLayoutState.getWidth();
output.height = mostRecentLayoutState.getHeight();
}
return;
}
widthSpec = mWidthSpec;
heightSpec = mHeightSpec;
root = mRoot.makeShallowCopy();
if (mMainThreadLayoutState != null) {
previousLayoutState = mMainThreadLayoutState.acquireRef();
}
}
final ComponentsLogger logger = mContext.getLogger();
LogEvent layoutEvent = null;
if (logger != null) {
layoutEvent = logger.newPerformanceEvent(EVENT_LAYOUT_CALCULATE);
layoutEvent.addParam(PARAM_LOG_TAG, mContext.getLogTag());
layoutEvent.addParam(PARAM_TREE_DIFF_ENABLED, String.valueOf(mIsLayoutDiffingEnabled));
layoutEvent.addParam(PARAM_IS_BACKGROUND_LAYOUT, String.valueOf(!ThreadUtils.isMainThread()));
}
LayoutState localLayoutState =
calculateLayoutState(
mLayoutLock,
mContext,
root,
widthSpec,
heightSpec,
mIsLayoutDiffingEnabled,
previousLayoutState != null ? previousLayoutState.getDiffTree() : null,
source);
if (output != null) {
output.width = localLayoutState.getWidth();
output.height = localLayoutState.getHeight();
}
if (previousLayoutState != null) {
previousLayoutState.releaseRef();
previousLayoutState = null;
}
List<Component> components = null;
boolean layoutStateUpdated = false;
synchronized (this) {
// Make sure some other thread hasn't computed a compatible layout in the meantime.
if (!hasCompatibleComponentAndSpec()
&& isCompatibleSpec(localLayoutState, mWidthSpec, mHeightSpec)) {
if (localLayoutState != null) {
final StateHandler layoutStateStateHandler =
localLayoutState.consumeStateHandler();
if (layoutStateStateHandler != null) {
if (mStateHandler != null) { // we could have been released
mStateHandler.commit(layoutStateStateHandler);
}
}
if (mMeasureListener != null) {
mMeasureListener.onSetRootAndSizeSpec(
localLayoutState.getWidth(), localLayoutState.getHeight());
}
components = new ArrayList<>(localLayoutState.getComponents());
localLayoutState.clearComponents();
}
// Set the new layout state, and remember the old layout state so we
// can release it.
final LayoutState tmp = mBackgroundLayoutState;
mBackgroundLayoutState = localLayoutState;
localLayoutState = tmp;
layoutStateUpdated = true;
}
}
if (components != null) {
clearUnusedTriggerHandlers();
for (final Component component : components) {
bindEventHandler(component);
bindTriggerHandler(component);
}
clearUnusedEventHandlers();
}
if (localLayoutState != null) {
localLayoutState.releaseRef();
localLayoutState = null;
}
if (layoutStateUpdated) {
postBackgroundLayoutStateUpdated();
}
if (mPreAllocateMountContentHandler != null) {
mPreAllocateMountContentHandler.removeCallbacks(mPreAllocateMountContentRunnable);
mPreAllocateMountContentHandler.post(mPreAllocateMountContentRunnable);
}
if (logger != null) {
logger.log(layoutEvent);
}
}
/**
* Transfer mBackgroundLayoutState to mMainThreadLayoutState. This will proxy
* to the main thread if necessary. If the component/size-spec changes in the
* meantime, then the transfer will be aborted.
*/
private void postBackgroundLayoutStateUpdated() {
if (isMainThread()) {
// We need to possibly update mMainThreadLayoutState. This call will
// cause the host view to be invalidated and re-laid out, if necessary.
backgroundLayoutStateUpdated();
} else {
// If we aren't on the main thread, we send a message to the main thread
// to invoke backgroundLayoutStateUpdated.
sMainThreadHandler.obtainMessage(MESSAGE_WHAT_BACKGROUND_LAYOUT_STATE_UPDATED, this)
.sendToTarget();
}
}
/**
* The contract is that in order to release a ComponentTree, you must do so from the main
* thread, or guarantee that it will never be accessed from the main thread again. Usually
* HostView will handle releasing, but if you never attach to a host view, then you should call
* release yourself.
*/
public void release() {
if (mIsMounting) {
throw new IllegalStateException("Releasing a ComponentTree that is currently being mounted");
}
LayoutState mainThreadLayoutState;
LayoutState backgroundLayoutState;
synchronized (this) {
sMainThreadHandler.removeMessages(MESSAGE_WHAT_BACKGROUND_LAYOUT_STATE_UPDATED, this);
synchronized (mCurrentCalculateLayoutRunnableLock) {
if (mCurrentCalculateLayoutRunnable != null) {
mLayoutThreadHandler.removeCallbacks(mCurrentCalculateLayoutRunnable);
mCurrentCalculateLayoutRunnable = null;
}
}
mLayoutThreadHandler.removeCallbacks(mUpdateStateSyncRunnable);
if (mPreAllocateMountContentHandler != null) {
mPreAllocateMountContentHandler.removeCallbacks(mPreAllocateMountContentRunnable);
}
mReleased = true;
mReleasedComponent = mRoot.getSimpleName();
if (mLithoView != null) {
mLithoView.setComponentTree(null);
}
mRoot = null;
mainThreadLayoutState = mMainThreadLayoutState;
mMainThreadLayoutState = null;
backgroundLayoutState = mBackgroundLayoutState;
mBackgroundLayoutState = null;
// TODO t15532529
mStateHandler = null;
if (mPreviousRenderState != null && !mPreviousRenderStateSetFromBuilder) {
ComponentsPools.release(mPreviousRenderState);
}
mPreviousRenderState = null;
mPreviousRenderStateSetFromBuilder = false;
}
if (mainThreadLayoutState != null) {
mainThreadLayoutState.releaseRef();
mainThreadLayoutState = null;
}
if (backgroundLayoutState != null) {
backgroundLayoutState.releaseRef();
backgroundLayoutState = null;
}
synchronized (mEventTriggersContainer) {
clearUnusedTriggerHandlers();
}
}
@GuardedBy("this")
private boolean isCompatibleComponentAndSpec(LayoutState layoutState) {
assertHoldsLock(this);
return mRoot != null && isCompatibleComponentAndSpec(
layoutState, mRoot.getId(), mWidthSpec, mHeightSpec);
}
// Either the MainThreadLayout or the BackgroundThreadLayout is compatible with the current state.
@GuardedBy("this")
private boolean hasCompatibleComponentAndSpec() {
assertHoldsLock(this);
return isCompatibleComponentAndSpec(mMainThreadLayoutState)
|| isCompatibleComponentAndSpec(mBackgroundLayoutState);
}
@GuardedBy("this")
private boolean hasSizeSpec() {
assertHoldsLock(this);
return mWidthSpec != SIZE_UNINITIALIZED
&& mHeightSpec != SIZE_UNINITIALIZED;
}
private static synchronized Looper getDefaultLayoutThreadLooper() {
if (sDefaultLayoutThreadLooper == null) {
final HandlerThread defaultThread =
new HandlerThread(DEFAULT_LAYOUT_THREAD_NAME, DEFAULT_LAYOUT_THREAD_PRIORITY);
defaultThread.start();
sDefaultLayoutThreadLooper = defaultThread.getLooper();
}
return sDefaultLayoutThreadLooper;
}
private static synchronized Looper getDefaultPreallocateMountContentThreadLooper() {
if (sDefaultPreallocateMountContentThreadLooper == null) {
final HandlerThread defaultThread = new HandlerThread(DEFAULT_PMC_THREAD_NAME);
defaultThread.start();
sDefaultPreallocateMountContentThreadLooper = defaultThread.getLooper();
}
return sDefaultPreallocateMountContentThreadLooper;
}
private static boolean isCompatibleSpec(
LayoutState layoutState, int widthSpec, int heightSpec) {
return layoutState != null
&& layoutState.isCompatibleSpec(widthSpec, heightSpec)
&& layoutState.isCompatibleAccessibility();
}
private static boolean isCompatibleComponentAndSpec(
LayoutState layoutState, int componentId, int widthSpec, int heightSpec) {
return layoutState != null
&& layoutState.isCompatibleComponentAndSpec(componentId, widthSpec, heightSpec)
&& layoutState.isCompatibleAccessibility();
}
private static boolean isCompatibleComponentAndSize(
LayoutState layoutState, int componentId, int width, int height) {
return layoutState != null
&& layoutState.isComponentId(componentId)
&& layoutState.isCompatibleSize(width, height)
&& layoutState.isCompatibleAccessibility();
}
public synchronized boolean isReleased() {
return mReleased;
}
synchronized String getReleasedComponent() {
return mReleasedComponent;
}
public ComponentContext getContext() {
return mContext;
}
private static class ComponentMainThreadHandler extends Handler {
private ComponentMainThreadHandler() {
super(Looper.getMainLooper());
}
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_WHAT_BACKGROUND_LAYOUT_STATE_UPDATED:
final ComponentTree that = (ComponentTree) msg.obj;
that.backgroundLayoutStateUpdated();
break;
default:
throw new IllegalArgumentException();
}
}
}
protected LayoutState calculateLayoutState(
@Nullable Object lock,
ComponentContext context,
Component root,
int widthSpec,
int heightSpec,
boolean diffingEnabled,
@Nullable DiffNode diffNode,
@CalculateLayoutSource int source) {
final ComponentContext contextWithStateHandler;
int simulateDelayNano = 0;
synchronized (this) {
final KeyHandler keyHandler =
(ComponentsConfiguration.useGlobalKeys || ComponentsConfiguration.isDebugModeEnabled)
? new KeyHandler(mContext.getLogger())
: null;
contextWithStateHandler =
new ComponentContext(context, StateHandler.acquireNewInstance(mStateHandler), keyHandler);
if (mMainThreadLayoutState != null && source == CalculateLayoutSource.UPDATE_STATE) {
simulateDelayNano =
(int)
(mMainThreadLayoutState.mCalculateLayoutDuration
* ComponentsConfiguration.longerStateUpdatePercentage
/ 100);
}
}
if (lock != null) {
synchronized (lock) {
if (source == CalculateLayoutSource.UPDATE_STATE) {
maybeDelayStateUpdateLayout(simulateDelayNano);
}
return LayoutState.calculate(
contextWithStateHandler,
root,
mId,
widthSpec,
heightSpec,
diffingEnabled,
diffNode,
mCanPrefetchDisplayLists,
mCanCacheDrawingDisplayLists,
mShouldClipChildren,
source);
}
} else {
if (source == CalculateLayoutSource.UPDATE_STATE) {
maybeDelayStateUpdateLayout(simulateDelayNano);
}
return LayoutState.calculate(
contextWithStateHandler,
root,
mId,
widthSpec,
heightSpec,
diffingEnabled,
diffNode,
mCanPrefetchDisplayLists,
mCanCacheDrawingDisplayLists,
mShouldClipChildren,
source);
}
}
private static void maybeDelayStateUpdateLayout(int delayNano) {
if (delayNano == 0) {
return;
}
try {
Thread.sleep(delayNano / 1000000, delayNano % 1000000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
/**
* A default {@link LayoutHandler} that will use a {@link Handler} with a {@link Thread}'s
* {@link Looper}.
*/
private static class DefaultLayoutHandler extends Handler implements LayoutHandler {
private DefaultLayoutHandler(Looper threadLooper) {
super(threadLooper);
}
}
private static class DefaultPreallocateMountContentHandler extends Handler
implements LayoutHandler {
private DefaultPreallocateMountContentHandler(Looper threadLooper) {
super(threadLooper);
}
}
public static int generateComponentTreeId() {
return sIdGenerator.getAndIncrement();
}
private final class CalculateLayoutRunnable implements Runnable {
private final @CalculateLayoutSource int mSource;
public CalculateLayoutRunnable(@CalculateLayoutSource int source) {
mSource = source;
}
@Override
public void run() {
calculateLayout(null, mSource);
}
}
/**
* A builder class that can be used to create a {@link ComponentTree}.
*/
public static class Builder {
// required
private ComponentContext context;
private Component root;
// optional
private boolean incrementalMountEnabled = true;
private boolean isLayoutDiffingEnabled = true;
private LayoutHandler layoutThreadHandler;
private LayoutHandler preAllocateMountContentHandler;
private Object layoutLock;
private StateHandler stateHandler;
private RenderState previousRenderState;
private boolean asyncStateUpdates = true;
private int overrideComponentTreeId = -1;
private boolean canPrefetchDisplayLists = false;
private boolean canCacheDrawingDisplayLists = false;
private boolean shouldClipChildren = true;
private boolean hasMounted = false;
private MeasureListener mMeasureListener;
private boolean shouldPreallocatePerMountSpec;
private boolean canPreallocateOnDefaultHandler;
protected Builder() {
}
protected Builder(ComponentContext context, Component root) {
init(context, root);
}
protected void init(ComponentContext context, Component root) {
this.context = context;
this.root = root;
}
protected void release() {
context = null;
root = null;
incrementalMountEnabled = true;
isLayoutDiffingEnabled = true;
layoutThreadHandler = null;
layoutLock = null;
stateHandler = null;
previousRenderState = null;
asyncStateUpdates = true;
overrideComponentTreeId = -1;
canPrefetchDisplayLists = false;
canCacheDrawingDisplayLists = false;
shouldClipChildren = true;
hasMounted = false;
preAllocateMountContentHandler = null;
}
/**
* Whether or not to enable the incremental mount optimization. True by default.
* In order to use incremental mount you should disable mount diffing.
*
* @Deprecated We will remove this option soon, please consider turning it on (which is on by
* default)
*/
public Builder incrementalMount(boolean isEnabled) {
incrementalMountEnabled = isEnabled;
return this;
}
/**
* Whether or not to enable layout tree diffing. This will reduce the cost of
* updates at the expense of using extra memory. True by default.
*
* @Deprecated We will remove this option soon, please consider turning it on (which is on by
* default)
*/
public Builder layoutDiffing(boolean enabled) {
isLayoutDiffingEnabled = enabled;
return this;
}
/**
* Specify the looper to use for running layouts on. Note that in rare cases
* layout must run on the UI thread. For example, if you rotate the screen,
* we must measure on the UI thread. If you don't specify a Looper here, the
* Components default Looper will be used.
*/
public Builder layoutThreadLooper(Looper looper) {
if (looper != null) {
layoutThreadHandler = new DefaultLayoutHandler(looper);
}
return this;
}
/** Specify the handler for to preAllocateMountContent */
public Builder preAllocateMountContentHandler(LayoutHandler handler) {
preAllocateMountContentHandler = handler;
return this;
}
/**
* If true, this ComponentTree will only preallocate mount specs that are enabled for
* preallocation with {@link MountSpec#canPreallocate()}. If false, it preallocates all mount
* content.
*/
public Builder shouldPreallocateMountContentPerMountSpec(boolean preallocatePerMountSpec) {
shouldPreallocatePerMountSpec = preallocatePerMountSpec;
return this;
}
/**
* If true, mount content preallocation will use a default layout handler to preallocate mount
* content on a background thread if no other layout handler is provided through {@link
* ComponentTree.Builder#preAllocateMountContentHandler(LayoutHandler)}.
*/
public Builder preallocateOnDefaultHandler(boolean preallocateOnDefaultHandler) {
canPreallocateOnDefaultHandler = preallocateOnDefaultHandler;
return this;
}
/**
* Specify the looper to use for running layouts on. Note that in rare cases layout must run on
* the UI thread. For example, if you rotate the screen, we must measure on the UI thread. If
* you don't specify a Looper here, the Components default Looper will be used.
*/
public Builder layoutThreadHandler(LayoutHandler handler) {
layoutThreadHandler = handler;
return this;
}
/**
* Specify a lock to be acquired during layout. This is an advanced feature
* that can lead to deadlock if you don't know what you are doing.
*/
public Builder layoutLock(Object layoutLock) {
this.layoutLock = layoutLock;
return this;
}
/**
* Specify an initial state handler object that the ComponentTree can use to set the current
* values for states.
*/
public Builder stateHandler(StateHandler stateHandler) {
this.stateHandler = stateHandler;
return this;
}
/**
* Specify an existing previous render state that the ComponentTree can use to set the current
* values for providing previous versions of @Prop/@State variables.
*/
public Builder previousRenderState(RenderState previousRenderState) {
this.previousRenderState = previousRenderState;
return this;
}
/**
* Specify whether the ComponentTree allows async state updates. This is enabled by default.
*/
public Builder asyncStateUpdates(boolean enabled) {
this.asyncStateUpdates = enabled;
return this;
}
/**
* Gives the ability to override the auto-generated ComponentTree id: this is generally not
* useful in the majority of circumstances, so don't use it unless you really know what you're
* doing.
*/
public Builder overrideComponentTreeId(int overrideComponentTreeId) {
this.overrideComponentTreeId = overrideComponentTreeId;
return this;
}
/**
* Specify whether the ComponentTree allows to prefetch display lists of its components
* on idle time of UI thread.
*
* NOTE: To make display lists prefetching work, besides setting this flag
* {@link com.facebook.litho.utils.DisplayListUtils#prefetchDisplayLists(View)}
* should be called on scrollable surfaces like {@link android.support.v7.widget.RecyclerView}
* during scrolling.
*/
public Builder canPrefetchDisplayLists(boolean canPrefetch) {
this.canPrefetchDisplayLists = canPrefetch;
return this;
}
/**
* Specify whether the ComponentTree allows to cache display lists of the components after it
* was first drawng.
*
* NOTE: To make display lists caching work, {@link #canPrefetchDisplayLists(boolean)} should
* be set to true.
*/
public Builder canCacheDrawingDisplayLists(boolean canCacheDrawingDisplayLists) {
this.canCacheDrawingDisplayLists = canCacheDrawingDisplayLists;
return this;
}
public Builder shouldClipChildren(boolean shouldClipChildren) {
this.shouldClipChildren = shouldClipChildren;
return this;
}
/**
* Sets whether the 'hasMounted' flag should be set on this ComponentTree (for use with appear
* animations).
*/
public Builder hasMounted(boolean hasMounted) {
this.hasMounted = hasMounted;
return this;
}
public Builder measureListener(MeasureListener measureListener) {
this.mMeasureListener = measureListener;
return this;
}
/** Builds a {@link ComponentTree} using the parameters specified in this builder. */
public ComponentTree build() {
final ComponentTree componentTree = new ComponentTree(this);
ComponentsPools.release(this);
return componentTree;
}
}
}
|
package imagej.legacy;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import org.scijava.util.FileUtils;
/**
* Assorted legacy patches / extension points for use in the legacy mode.
*
* <p>
* The Fiji distribution of ImageJ accumulated patches and extensions to ImageJ
* 1.x over the years.
* </p>
*
* <p>
* However, there was a lot of overlap with the ImageJ2 project, so it was
* decided to focus Fiji more on the life-science specific part and move all the
* parts that are of more general use into ImageJ2. That way, it is pretty
* clear-cut what goes into Fiji and what goes into ImageJ2.
* </p>
*
* <p>
* This class contains the extension points (such as being able to override the
* macro editor) ported from Fiji as well as the code for runtime patching
* ImageJ 1.x needed both for the extension points and for more backwards
* compatibility than ImageJ 1.x wanted to provide (e.g. when public methods or
* classes that were used by Fiji plugins were removed all of a sudden, without
* being deprecated first).
* </p>
*
* <p>
* The code in this class is only used in the legacy mode.
* </p>
*
* @author Johannes Schindelin
*/
public class LegacyExtensions {
/*
* Extension points
*/
/**
* A minimal interface for the editor to use instead of ImageJ 1.x' limited AWT-based one.
*
* @author Johannes Schindelin
*/
public interface LegacyEditorPlugin {
public boolean open(final File path);
public boolean create(final String title, final String content);
}
private static LegacyEditorPlugin editor;
private static String appName = "ImageJ";
private static URL iconURL;
private static Runnable afterRefreshMenus;
/**
* Sets the application name for ImageJ 1.x.
*
* @param name the name to display instead of <i>ImageJ</i>.
*/
public static void setAppName(final String name) {
appName = name;
}
/**
* Returns the application name for use with ImageJ 1.x.
* @return the application name
*/
public static String getAppName() {
return appName;
}
/**
* Sets the icon for ImageJ 1.x.
*
* @param file
* the {@link File} of the icon to use in ImageJ 1.x
*/
public static void setIcon(final File file) {
if (file != null && file.exists()) try {
iconURL = file.toURI().toURL();
return;
} catch (MalformedURLException e) {
e.printStackTrace();
}
iconURL = null;
}
/**
* Returns the icon for use with ImageJ 1.x.
*
* @return the application name
*/
public static URL getIconURL() {
return iconURL;
}
/**
* Sets the legacy editor to use instead of ImageJ 1.x' built-in one.
*
* @param plugin the editor to set, or null if ImageJ 1.x' built-in editor should be used
*/
public static void setLegacyEditor(final LegacyEditorPlugin plugin) {
editor = plugin;
}
public static void runAfterRefreshMenus(final Runnable runnable) {
afterRefreshMenus = runnable;
}
public static void runAfterRefreshMenus() {
if (afterRefreshMenus != null) afterRefreshMenus.run();
}
/*
* Helper functions intended to be called by runtime-patched ImageJ 1.x
*/
public static boolean handleNoSuchMethodError(NoSuchMethodError error) {
String message = error.getMessage();
int paren = message.indexOf("(");
if (paren < 0) return false;
int dot = message.lastIndexOf(".", paren);
if (dot < 0) return false;
String path = message.substring(0, dot).replace('.', '/') + ".class";
Set<String> urls = new LinkedHashSet<String>();
try {
Enumeration<URL> e = IJ1Helper.getClassLoader().getResources(path);
while (e.hasMoreElements()) {
urls.add(e.nextElement().toString());
}
e = IJ1Helper.getClassLoader().getResources("/" + path);
while (e.hasMoreElements()) {
urls.add(e.nextElement().toString());
}
} catch (Throwable t) {
t.printStackTrace();
return false;
}
if (urls.size() == 0) return false;
StringBuilder buffer = new StringBuilder();
buffer.append("There was a problem with the class ");
buffer.append(message.substring(0, dot));
buffer.append(" which can be found here:\n");
for (String url : urls) {
if (url.startsWith("jar:")) url = url.substring(4);
if (url.startsWith("file:")) url = url.substring(5);
int bang = url.indexOf("!");
if (bang < 0) buffer.append(url);
else buffer.append(url.substring(0, bang));
buffer.append("\n");
}
if (urls.size() > 1) {
buffer.append("\nWARNING: multiple locations found!\n");
}
StringWriter writer = new StringWriter();
error.printStackTrace(new PrintWriter(writer));
buffer.append(writer.toString());
IJ1Helper.log(buffer.toString());
IJ1Helper.error("Could not find method " + message + "\n(See Log for details)\n");
return true;
}
public static List<File> handleExtraPluginJars() {
final List<File> result = new ArrayList<File>();
final String extraPluginDirs = System.getProperty("ij1.plugin.dirs");
if (extraPluginDirs != null) {
for (final String dir : extraPluginDirs.split(File.pathSeparator)) {
handleExtraPluginJars(new File(dir), result);
}
return result;
}
final String userHome = System.getProperty("user.home");
if (userHome != null) handleExtraPluginJars(new File(userHome, ".plugins"), result);
return result;
}
private static void handleExtraPluginJars(final File directory, final List<File> result) {
final File[] list = directory.listFiles();
if (list == null) return;
for (final File file : list) {
if (file.isDirectory()) handleExtraPluginJars(file, result);
else if (file.isFile() && file.getName().endsWith(".jar")) {
result.add(file);
}
}
}
/**
* Opens the given path in the registered legacy editor, if any.
*
* @param path the path of the file to open
* @return whether the file was opened successfully
*/
public static boolean openInLegacyEditor(final String path) {
if (editor == null) return false;
if (path.indexOf("://") > 0) return false;
if ("".equals(FileUtils.getExtension(path))) return false;
if (stackTraceContains(LegacyExtensions.class.getName() + ".openEditor(")) return false;
final File file = new File(path);
if (!file.exists()) return false;
if (isBinaryFile(file)) return false;
return editor.open(file);
}
/**
* Creates the given file in the registered legacy editor, if any.
*
* @param title the title of the file to create
* @param content the text of the file to be created
* @return whether the fule was opened successfully
*/
public static boolean createInLegacyEditor(final String title, final String content) {
if (editor == null) return false;
return editor.create(title, content);
}
/**
* Determines whether the current stack trace contains the specified string.
*
* @param needle the text to find
* @return whether the stack trace contains the text
*/
private static boolean stackTraceContains(String needle) {
final StringWriter writer = new StringWriter();
final PrintWriter out = new PrintWriter(writer);
new Exception().printStackTrace(out);
out.close();
return writer.toString().indexOf(needle) >= 0;
}
/**
* Determines whether a file is binary or text.
*
* This just checks for a NUL in the first 1024 bytes.
* Not the best test, but a pragmatic one.
*
* @param file the file to test
* @return whether it is binary
*/
private static boolean isBinaryFile(final File file) {
try {
InputStream in = new FileInputStream(file);
byte[] buffer = new byte[1024];
int offset = 0;
while (offset < buffer.length) {
int count = in.read(buffer, offset, buffer.length - offset);
if (count < 0)
break;
else
offset += count;
}
in.close();
while (offset > 0)
if (buffer[--offset] == 0)
return true;
} catch (IOException e) {
}
return false;
}
/*
* Runtime patches (using CodeHacker for patching)
*/
/**
* Applies runtime patches to ImageJ 1.x for backwards-compatibility and extension points.
*
* <p>
* These patches enable a patched ImageJ 1.x to call a different script editor or to override
* the application icon.
* </p>
*
* <p>
* This method is called by {@link LegacyInjector#injectHooks(ClassLoader)}.
* </p>
*
* @param hacker the {@link CodeHacker} instance
*/
public static void injectHooks(final CodeHacker hacker) {
// Below are patches to make ImageJ 1.x more backwards-compatible
// add back the (deprecated) killProcessor(), and overlay methods
final String[] imagePlusMethods = {
"public void killProcessor()",
"{}",
"public void setDisplayList(java.util.Vector list)",
"getCanvas().setDisplayList(list);",
"public java.util.Vector getDisplayList()",
"return getCanvas().getDisplayList();",
"public void setDisplayList(ij.gui.Roi roi, java.awt.Color strokeColor,"
+ " int strokeWidth, java.awt.Color fillColor)",
"setOverlay(roi, strokeColor, strokeWidth, fillColor);"
};
for (int i = 0; i < imagePlusMethods.length; i++) try {
hacker.insertNewMethod("ij.ImagePlus",
imagePlusMethods[i], imagePlusMethods[++i]);
} catch (Exception e) { /* ignore */ }
// make sure that ImageJ has been initialized in batch mode
hacker.insertAtTopOfMethod("ij.IJ",
"public static java.lang.String runMacro(java.lang.String macro, java.lang.String arg)",
"if (ij==null && ij.Menus.getCommands()==null) init();");
try {
hacker.insertNewMethod("ij.CompositeImage",
"public ij.ImagePlus[] splitChannels(boolean closeAfter)",
"ij.ImagePlus[] result = ij.plugin.ChannelSplitter.split(this);"
+ "if (closeAfter) close();"
+ "return result;");
hacker.insertNewMethod("ij.plugin.filter.RGBStackSplitter",
"public static ij.ImagePlus[] splitChannelsToArray(ij.ImagePlus imp, boolean closeAfter)",
"if (!imp.isComposite()) {"
+ " ij.IJ.error(\"splitChannelsToArray was called on a non-composite image\");"
+ " return null;"
+ "}"
+ "ij.ImagePlus[] result = ij.plugin.ChannelSplitter.split(imp);"
+ "if (closeAfter)"
+ " imp.close();"
+ "return result;");
} catch (IllegalArgumentException e) {
final Throwable cause = e.getCause();
if (cause != null && !cause.getClass().getName().endsWith("DuplicateMemberException")) {
throw e;
}
}
// handle mighty mouse (at least on old Linux, Java mistakes the horizontal wheel for a popup trigger)
for (String fullClass : new String[] {
"ij.gui.ImageCanvas",
"ij.plugin.frame.RoiManager",
"ij.text.TextPanel",
"ij.gui.Toolbar"
}) {
hacker.handleMightyMousePressed(fullClass);
}
// tell IJ#runUserPlugIn to catch NoSuchMethodErrors
final String runUserPlugInSig = "static java.lang.Object runUserPlugIn(java.lang.String commandName, java.lang.String className, java.lang.String arg, boolean createNewLoader)";
hacker.addCatch("ij.IJ", runUserPlugInSig, "java.lang.NoSuchMethodError",
"if (" + LegacyExtensions.class.getName() + ".handleNoSuchMethodError($e))"
+ " throw new RuntimeException(ij.Macro.MACRO_CANCELED);"
+ "throw $e;");
// tell IJ#runUserPlugIn to be more careful about catching NoClassDefFoundError
hacker.insertPrivateStaticField("ij.IJ", String.class, "originalClassName");
hacker.insertAtTopOfMethod("ij.IJ", runUserPlugInSig, "originalClassName = $2;");
hacker.insertAtTopOfExceptionHandlers("ij.IJ", runUserPlugInSig, "java.lang.NoClassDefFoundError",
"java.lang.String realClassName = $1.getMessage();"
+ "int spaceParen = realClassName.indexOf(\" (\");"
+ "if (spaceParen > 0) realClassName = realClassName.substring(0, spaceParen);"
+ "if (!originalClassName.replace('.', '/').equals(realClassName)) {"
+ " if (realClassName.startsWith(\"javax/vecmath/\") || realClassName.startsWith(\"com/sun/j3d/\") || realClassName.startsWith(\"javax/media/j3d/\"))"
+ " ij.IJ.error(\"The class \" + originalClassName + \" did not find Java3D (\" + realClassName + \")\\nPlease call Plugins>3D Viewer to install\");"
+ " else"
+ " ij.IJ.handleException($1);"
+ " return null;"
+ "}");
// let the plugin class loader find stuff in $HOME/.plugins, too
addExtraPlugins(hacker);
// make sure that the GenericDialog is disposed in macro mode
try {
hacker.insertAtTopOfMethod("ij.gui.GenericDialog", "public void showDialog()", "if (macro) dispose();");
} catch (IllegalArgumentException e) {
// ignore if the headless patcher renamed the method away
if (e.getCause() == null || !e.getCause().getClass().getName().endsWith("NotFoundException")) {
throw e;
}
}
// make sure NonBlockingGenericDialog does not wait in macro mode
hacker.replaceCallInMethod("ij.gui.NonBlockingGenericDialog", "public void showDialog()", "java.lang.Object", "wait", "if (isShowing()) wait();");
// tell the showStatus() method to show the version() instead of empty status
hacker.insertAtTopOfMethod("ij.ImageJ", "void showStatus(java.lang.String s)", "if ($1 == null || \"\".equals($1)) $1 = version();");
// handle custom icon (e.g. for Fiji)
addIconHooks(hacker);
// optionally disallow batch mode from calling System.exit()
hacker.insertPrivateStaticField("ij.ImageJ", Boolean.TYPE, "batchModeMayExit");
hacker.insertAtTopOfMethod("ij.ImageJ", "public static void main(java.lang.String[] args)",
"batchModeMayExit = true;"
+ "for (int i = 0; i < $1.length; i++) {"
+ " if (\"-batch-no-exit\".equals($1[i])) {"
+ " batchModeMayExit = false;"
+ " $1[i] = \"-batch\";"
+ " }"
+ "}");
hacker.replaceCallInMethod("ij.ImageJ", "public static void main(java.lang.String[] args)", "java.lang.System", "exit",
"if (batchModeMayExit) System.exit($1);"
+ "if ($1 == 0) return;"
+ "throw new RuntimeException(\"Exit code: \" + $1);");
// do not use the current directory as IJ home on Windows
String prefsDir = System.getenv("IJ_PREFS_DIR");
if (prefsDir == null && System.getProperty("os.name").startsWith("Windows")) {
prefsDir = System.getenv("user.home");
}
if (prefsDir != null) {
hacker.overrideFieldWrite("ij.Prefs", "public java.lang.String load(java.lang.Object ij, java.applet.Applet applet)",
"prefsDir", "$_ = \"" + prefsDir + "\";");
}
// tool names can be prefixes of other tools, watch out for that!
hacker.replaceCallInMethod("ij.gui.Toolbar", "public int getToolId(java.lang.String name)", "java.lang.String", "startsWith",
"$_ = $0.equals($1) || $0.startsWith($1 + \"-\") || $0.startsWith($1 + \" -\");");
// make sure Rhino gets the correct class loader
hacker.insertAtTopOfMethod("JavaScriptEvaluator", "public void run()",
"Thread.currentThread().setContextClassLoader(ij.IJ.getClassLoader());");
// make sure that the check for Bio-Formats is correct
hacker.addToClassInitializer("ij.io.Opener",
"try {"
+ " ij.IJ.getClassLoader().loadClass(\"loci.plugins.LociImporter\");"
+ " bioformats = true;"
+ "} catch (ClassNotFoundException e) {"
+ " bioformats = false;"
+ "}");
// make sure that symbolic links are *not* resolved (because then the parent info in the FileInfo would be wrong)
hacker.replaceCallInMethod("ij.plugin.DragAndDrop", "public void openFile(java.io.File f)", "java.io.File", "getCanonicalPath",
"$_ = $0.getAbsolutePath();");
// make sure no dialog is opened in headless mode
hacker.insertAtTopOfMethod("ij.macro.Interpreter", "void showError(java.lang.String title, java.lang.String msg, java.lang.String[] variables)",
"if (ij.IJ.getInstance() == null) {"
+ " java.lang.System.err.println($1 + \": \" + $2);"
+ " return;"
+ "}");
// let IJ.handleException override the macro interpreter's call()'s exception handling
hacker.insertAtTopOfExceptionHandlers("ij.macro.Functions", "java.lang.String call()", "java.lang.reflect.InvocationTargetException",
"ij.IJ.handleException($1);"
+ "return null;");
// Add back the "Convert to 8-bit Grayscale" checkbox to Import>Image Sequence
if (!hacker.hasField("ij.plugin.FolderOpener", "convertToGrayscale")) {
hacker.insertPrivateStaticField("ij.plugin.FolderOpener", Boolean.TYPE, "convertToGrayscale");
hacker.replaceCallInMethod("ij.plugin.FolderOpener", "public void run(java.lang.String arg)", "ij.io.Opener", "openImage",
"$_ = $0.openImage($1, $2);"
+ "if (convertToGrayscale)"
+ " ij.IJ.run($_, \"8-bit\", \"\");");
hacker.replaceCallInMethod("ij.plugin.FolderOpener", "boolean showDialog(ij.ImagePlus imp, java.lang.String[] list)",
"ij.gui.GenericDialog", "addCheckbox",
"i$0.addCheckbox(\"Convert to 8-bit Grayscale\", convertToGrayscale);"
+ "$0.addCheckbox($1, $2);", 1);
hacker.replaceCallInMethod("ij.plugin.FolderOpener", "boolean showDialog(ij.ImagePlus imp, java.lang.String[] list)",
"ij.gui.GenericDialog", "getNextBoolean",
"convertToGrayscale = $0.getNextBoolean();"
+ "$_ = $0.getNextBoolean();"
+ "if (convertToGrayscale && $_) {"
+ " ij.IJ.error(\"Cannot convert to grayscale and RGB at the same time.\");"
+ " return false;"
+ "}", 1);
}
// handle HTTPS in addition to HTTP
hacker.handleHTTPS("ij.macro.Functions", "java.lang.String exec()");
hacker.handleHTTPS("ij.plugin.DragAndDrop", "public void drop(java.awt.dnd.DropTargetDropEvent dtde)");
hacker.handleHTTPS(hacker.existsClass("ij.plugin.PluginInstaller") ? "ij.plugin.PluginInstaller" : "ij.io.PluginInstaller", "public boolean install(java.lang.String path)");
hacker.handleHTTPS("ij.plugin.ListVirtualStack", "public void run(java.lang.String arg)");
hacker.handleHTTPS("ij.plugin.ListVirtualStack", "java.lang.String[] open(java.lang.String path)");
addEditorExtensionPoints(hacker);
insertAppNameHooks(hacker);
insertRefreshMenusHook(hacker);
}
/**
* Install a hook to optionally run a Runnable at the end of Help>Refresh Menus.
*
* <p>
* See {@link LegacyExtensions#runAfterRefreshMenus(Runnable)}.
* </p>
*
* @param hacker the {@link CodeHacker} to use for patching
*/
private static void insertRefreshMenusHook(CodeHacker hacker) {
hacker.insertAtBottomOfMethod("ij.Menus", "public static void updateImageJMenus()",
LegacyExtensions.class.getName() + ".runAfterRefreshMenus();");
}
private static void addEditorExtensionPoints(final CodeHacker hacker) {
hacker.insertAtTopOfMethod("ij.io.Opener", "public void open(java.lang.String path)",
"if (isText($1) && " + LegacyExtensions.class.getName() + ".openInLegacyEditor($1)) return;");
hacker.dontReturnOnNull("ij.plugin.frame.Recorder", "void createMacro()");
hacker.replaceCallInMethod("ij.plugin.frame.Recorder", "void createMacro()",
"ij.plugin.frame.Editor", "runPlugIn",
"$_ = null;");
hacker.replaceCallInMethod("ij.plugin.frame.Recorder", "void createMacro()",
"ij.plugin.frame.Editor", "createMacro",
"if ($1.endsWith(\".txt\")) {"
+ " $1 = $1.substring($1.length() - 3) + \"ijm\";"
+ "}"
+ "if (!" + LegacyExtensions.class.getName() + ".createInLegacyEditor($1, $2)) {"
+ " ((ij.plugin.frame.Editor)ij.IJ.runPlugIn(\"ij.plugin.frame.Editor\", \"\")).createMacro($1, $2);"
+ "}");
hacker.insertPublicStaticField("ij.plugin.frame.Recorder", String.class, "nameForEditor", null);
hacker.insertAtTopOfMethod("ij.plugin.frame.Recorder", "void createPlugin(java.lang.String text, java.lang.String name)",
"this.nameForEditor = $2;");
hacker.replaceCallInMethod("ij.plugin.frame.Recorder", "void createPlugin(java.lang.String text, java.lang.String name)",
"ij.IJ", "runPlugIn",
"$_ = null;"
+ "new ij.plugin.NewPlugin().createPlugin(this.nameForEditor, ij.plugin.NewPlugin.PLUGIN, $2);"
+ "return;");
hacker.replaceCallInMethod("ij.plugin.NewPlugin", "public void createMacro(java.lang.String name)",
"ij.plugin.frame.Editor", "<init>",
"$_ = null;");
hacker.replaceCallInMethod("ij.plugin.NewPlugin", "public void createMacro(java.lang.String name)",
"ij.plugin.frame.Editor", "create",
"if ($1.endsWith(\".txt\")) {"
+ " $1 = $1.substring(0, $1.length() - 3) + \"ijm\";"
+ "}"
+ "if ($1.endsWith(\".ijm\") && " + LegacyExtensions.class.getName() + ".createInLegacyEditor($1, $2)) return;"
+ "int options = (monospaced ? ij.plugin.frame.Editor.MONOSPACED : 0)"
+ " | (menuBar ? ij.plugin.frame.Editor.MENU_BAR : 0);"
+ "new ij.plugin.frame.Editor(rows, columns, 0, options).create($1, $2);");
hacker.dontReturnOnNull("ij.plugin.NewPlugin", "public void createPlugin(java.lang.String name, int type, java.lang.String methods)");
hacker.replaceCallInMethod("ij.plugin.NewPlugin", "public void createPlugin(java.lang.String name, int type, java.lang.String methods)",
"ij.IJ", "runPlugIn",
"$_ = null;");
hacker.replaceCallInMethod("ij.plugin.NewPlugin", "public void createPlugin(java.lang.String name, int type, java.lang.String methods)",
"ij.plugin.frame.Editor", "create",
"if (!" + LegacyExtensions.class.getName() + ".createInLegacyEditor($1, $2)) {"
+ " ((ij.plugin.frame.Editor)ij.IJ.runPlugIn(\"ij.plugin.frame.Editor\", \"\")).create($1, $2);"
+ "}");
}
/**
* Inserts hooks to replace the application name.
*/
private static void insertAppNameHooks(final CodeHacker hacker) {
final String appName = LegacyExtensions.class.getName() + ".getAppName()";
hacker.insertAtTopOfMethod("ij.IJ", "public void error(java.lang.String title, java.lang.String msg)",
"if ($1 == null || $1.equals(\"ImageJ\")) $1 = " + appName + ";");
hacker.insertAtBottomOfMethod("ij.ImageJ", "public java.lang.String version()", "$_ = $_.replace(\"ImageJ\", " + appName + ");");
hacker.replaceParameterInCall("ij.ImageJ", "public <init>(java.applet.Applet applet, int mode)", "super", 1, appName);
hacker.replaceParameterInNew("ij.ImageJ", "public void run()", "ij.gui.GenericDialog", 1, appName);
hacker.replaceParameterInCall("ij.ImageJ", "public void run()", "addMessage", 1, appName);
hacker.replaceParameterInNew("ij.plugin.CommandFinder", "public void export()", "ij.text.TextWindow", 1, appName);
hacker.replaceParameterInCall("ij.plugin.Hotkeys", "public void removeHotkey()", "addMessage", 1, appName);
hacker.replaceParameterInCall("ij.plugin.Hotkeys", "public void removeHotkey()", "showStatus", 1, appName);
hacker.replaceParameterInCall("ij.plugin.Options", "public void appearance()", "showMessage", 2, appName);
hacker.replaceParameterInCall("ij.gui.YesNoCancelDialog", "public <init>(java.awt.Frame parent, java.lang.String title, java.lang.String msg)", "super", 2, appName);
hacker.replaceParameterInCall("ij.gui.Toolbar", "private void showMessage(int toolId)", "showStatus", 1, appName);
}
private static void addIconHooks(final CodeHacker hacker) {
final String icon = LegacyExtensions.class.getName() + ".getIconURL()";
hacker.replaceCallInMethod("ij.ImageJ", "void setIcon()", "java.lang.Class", "getResource",
"java.net.URL _iconURL = " + icon + ";\n" +
"if (_iconURL == null) $_ = $0.getResource($1);" +
"else $_ = _iconURL;");
hacker.insertAtTopOfMethod("ij.ImageJ", "public <init>(java.applet.Applet applet, int mode)",
"if ($2 != 2 /* ij.ImageJ.NO_SHOW */) setIcon();");
hacker.insertAtTopOfMethod("ij.WindowManager", "public void addWindow(java.awt.Frame window)",
"java.net.URL _iconURL = " + icon + ";\n"
+ "if (_iconURL != null && $1 != null) {"
+ " java.awt.Image img = $1.createImage((java.awt.image.ImageProducer)_iconURL.getContent());"
+ " if (img != null) {"
+ " $1.setIconImage(img);"
+ " }"
+ "}");
}
/**
* Makes sure that the legacy plugin class loader finds stuff in
* $HOME/.plugins/
*
* @param directory
* a directory where additional plugins can be found
*/
private static void addExtraPlugins(final CodeHacker hacker) {
hacker.insertAtTopOfMethod("ij.io.PluginClassLoader", "void init(java.lang.String path)",
extraPluginJarsHandler("addJAR(file);"));
hacker.insertAtBottomOfMethod("ij.Menus",
"public static synchronized java.lang.String[] getPlugins()",
extraPluginJarsHandler("if (jarFiles == null) jarFiles = new java.util.Vector();" +
"jarFiles.addElement(file.getAbsolutePath());"));
// force IJ.getClassLoader() to instantiate a PluginClassLoader
hacker.replaceCallInMethod(
"ij.IJ",
"public static ClassLoader getClassLoader()",
"java.lang.System",
"getProperty",
"$_ = System.getProperty($1);\n"
+ "if ($_ == null && $1.equals(\"plugins.dir\")) $_ = \"/non-existant/\";");
}
private static String extraPluginJarsHandler(final String code) {
return "for (java.util.Iterator iter = " + LegacyExtensions.class.getName() + ".handleExtraPluginJars().iterator();\n" +
"iter.hasNext(); ) {\n" +
"\tjava.io.File file = (java.io.File)iter.next();\n" +
code + "\n" +
"}\n";
}
}
|
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.util.*;
import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import oracle.sql.*;
import oracle.jdbc.*;
import java.awt.Image;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
public class UploadImageLogicSQL extends HttpServlet {
public String response_message;
private Integer record_id; //must grab this
private Integer image_id;
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
//Parse the HTTP request to get the image stream
DiskFileUpload fu = new DiskFileUpload();
record_id = request.getParameters("record_id")
List FileItems = fu.parseRequest(request.getParameters("filesToUpload[]"));
// Process the uploaded items
Iterator i = FileItems.iterator();
FileItem item = (FileItem) i.next();
while (i.hasNext() && item.isFormField()) {
item = (FileItem) i.next();
long size = item.getSize();
//Get the image stream
InputStream instream = item.getInputStream();
//converting to smaller and smaller thumbnails
BufferedImage full_size = ImageIO.read(instream);
BufferedImage reg_size = shrink(full_size, 5);
BufferedImage thumbnail = shrink(reg_size, 5);
// Connect to the database
Connection conn = mkconn();
//getting newID for picture for image_id
Statement stmt = null;
stmt = conn.createStatement();
ResultSet rset1 = stmt.executeQuery("SELECT pic_id_sequence.nextval from dual");
rset1.next();
int image_id = rset1.getInt(1);
//Insert an blob into table with new ID
PreparedStatement pstmt = null;
pstmt = conn.prepareStatement("INSERT INTO pacs_images (record_id,image_id,thumbnail,regular_size,full_size)"
+ "values(?,?,empty_blob(), empty_blob(),empty_blob())");
pstmt.setInt(1,record_id);
pstmt.setInt(2, image_id);
// Retrieving the BLOB_locator
pstmt = conn.prepareStatement("SELECT thumbnail,regular_size,full_size FROM pacs_images WHERE record_id = '?' AND image_id = '?' FOR UPDATE");
Resultset rset = pstmt.executeStatement();
BLOB thumbnail_blob = ((OracleResultSet)rset).getBLOB(3);
BLOB regular_blob = ((OracleResultSet)rset).getBLOB(3);
BLOB full_blob = ((OracleResultSet)rset).getBLOB(3);
//Write the image to the blob object
OutputStream thumbnail_out = thumbnail_blob.getBinaryOutputStream();
ImageIO.write(thumbnail, "jpg", thumbnail_out);
OutputStream regular_out = regular_blob.getBinaryOutputStream();
ImageIO.write(reg_size, "jpg", regular_out);
OutputStream full_out = full_bob.getBinaryOutputStream();
ImageIO.write(full_size, "jpg", full_out);
thumbnail_out.close();
regular_out.close();
full_out.close();
instream.close();
response_message = "The Images Have been Uploaded";
}
conn.close();
}
catch( Exception ex ) {
response_message = ex.getMessage();
}
//Output response to the client if image uploaded properly
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
"Transitional//EN\">\n" +
"<HTML>\n" +
"<HEAD><TITLE>Upload Message</TITLE></HEAD>\n" +
"<BODY>\n" +
"<H1>" +
response_message +
"</H1>\n" +
"</BODY></HTML>");
}
//This creates a connection to database for insertion of picture
public Connection mkconn(){
String USER = ""; //Change these parameters when testing to your oracle password :)
String PASSWORD = "";
Connection conn = null;
String driverName = "oracle.jdbc.driver.OracleDriver";
String dbstring = "jdbc:oracle:thin:@gwynne.cs.ualberta.ca:1521:CRS";
try{
Class drvClass = Class.forName(driverName);
DriverManager.registerDriver((Driver) drvClass.newInstance());
conn = DriverManager.getConnection(dbstring, USER, PASSWORD);
conn.setAutoCommit(false);
return conn;
}
catch(Exception ex){
return null;
}
}
//Shrinks image by a factor of n
public static BufferedImage shrink(BufferedImage image, int n) {
int w = image.getWidth() / n;
int h = image.getHeight() / n;
BufferedImage shrunkImage =
new BufferedImage(w, h, image.getType());
for (int y=0; y < h; ++y)
for (int x=0; x < w; ++x)
shrunkImage.setRGB(x, y, image.getRGB(x*n, y*n));
return shrunkImage;
}
}
|
package hudson.diagnosis;
import hudson.model.AdministrativeMonitor;
import jenkins.model.Jenkins;
import hudson.Extension;
import org.jenkinsci.Symbol;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import java.io.IOException;
/**
* If Hudson is run with a lot of jobs but no views, suggest the user that they can create views.
*
* <p>
* I noticed at an user visit that some users didn't notice the '+' icon in the tab bar.
*
* @author Kohsuke Kawaguchi
*/
@Extension @Symbol("tooManyJobsButNoView")
public class TooManyJobsButNoView extends AdministrativeMonitor {
public boolean isActivated() {
Jenkins h = Jenkins.getInstance();
return h.getViews().size()==1 && h.getItemMap().size()> THRESHOLD;
}
/**
* Depending on whether the user said "yes" or "no", send him to the right place.
*/
public void doAct(StaplerRequest req, StaplerResponse rsp) throws IOException {
if(req.hasParameter("no")) {
disable(true);
rsp.sendRedirect(req.getContextPath()+"/manage");
} else {
rsp.sendRedirect(req.getContextPath()+"/newView");
}
}
public static final int THRESHOLD = 16;
}
|
package net.novucs.ftop.listener;
import net.novucs.ftop.FactionsTopPlugin;
import net.novucs.ftop.PluginService;
import net.novucs.ftop.entity.FactionWorth;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
public class ChatListener implements Listener, PluginService {
private static final String RANK_PLACEHOLDER = "{rank}";
private final FactionsTopPlugin plugin;
public ChatListener(FactionsTopPlugin plugin) {
this.plugin = plugin;
}
@Override
public void initialize() {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
@Override
public void terminate() {
HandlerList.unregisterAll(this);
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOW)
public void replacePlaceholders(AsyncPlayerChatEvent event) {
// Do nothing if placeholder should not be applied.
if (!plugin.getSettings().isChatEnabled()) {
return;
}
String placeholder = plugin.getSettings().getChatRankPlaceholder();
if (!event.getFormat().contains(placeholder)) {
return;
}
String factionId = plugin.getFactionsHook().getFaction(event.getPlayer());
String format = event.getFormat();
// Set rank not found if player is in an ignored faction.
if (plugin.getSettings().getIgnoredFactionIds().contains(factionId)) {
format = format.replace(placeholder, plugin.getSettings().getChatRankNotFound());
event.setFormat(format);
return;
}
// Update chat format with rank found placeholder.
FactionWorth worth = plugin.getWorthManager().getWorth(factionId);
int rank = plugin.getWorthManager().getOrderedFactions().indexOf(worth) + 1;
String rankFound = plugin.getSettings().getChatRankFound().replace(RANK_PLACEHOLDER, String.valueOf(rank));
format = format.replace(placeholder, rankFound);
event.setFormat(format);
}
}
|
package org.mskcc.cbio.cgds.util;
import org.mskcc.cbio.cgds.dao.*;
import org.mskcc.cbio.cgds.model.CancerStudy;
import org.mskcc.cbio.cgds.model.CanonicalGene;
import org.mskcc.cbio.cgds.model.Gistic;
import org.mskcc.cbio.cgds.validate.ValidateGistic;
import org.mskcc.cbio.cgds.validate.validationException;
import org.springframework.ui.context.Theme;
import java.io.*;
import java.lang.System;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Properties;
/**
* Utility for importing Gistic data from a file
*/
public class GisticReader {
/**
* Extracts find the database's internal Id for the record
* associated with the Cancer Study string
* @param cancerStudy_str String (e.g. "tcga_gbm")
* @return CancerStudyId
* @throws DaoException
*/
public int getCancerStudyInternalId(String cancerStudy_str)
throws DaoException {
CancerStudy cancerStudy = DaoCancerStudy.getCancerStudyByStableId(cancerStudy_str);
if (cancerStudy == null) {
throw new DaoException(cancerStudy_str);
}
return cancerStudy.getInternalId();
}
public ArrayList<Gistic> parse(File gistic_f, int cancerStudyId) throws IOException, DaoException {
ArrayList<Gistic> gistics = new ArrayList<Gistic>();
FileReader reader = new FileReader(gistic_f);
BufferedReader buf = new BufferedReader(reader);
String line = buf.readLine();
// -- parse field names --
// todo: would it be better to use <enums>?
int chromosomeField = -1;
int peakStartField = -1;
int peakEndField = -1;
int genesField = -1;
int qvalField = -1;
int ampField = -1;
int cytobandField = -1;
String[] fields = line.split("\t");
int num_fields = fields.length;
for (int i = 0 ; i < num_fields; i+=1) {
if (fields[i].equals("chromosome")) {
chromosomeField = i;
}
else if (fields[i].equals("peak_start")) {
peakStartField = i;
}
else if (fields[i].equals("peak_end")) {
peakEndField = i;
}
else if (fields[i].equals("genes_in_region")) {
genesField = i;
}
else if (fields[i].equals("q_value")) {
qvalField = i;
}
else if (fields[i].equals("cytoband")) {
cytobandField = i;
}
else if (fields[i].equals("amp")) {
ampField = i;
}
}
if (chromosomeField == -1) {
System.out.println("The field: chromosome, is missing");
System.exit(1);
}
if (peakStartField == -1) {
System.out.println("The field: peak start, is missing");
System.exit(1);
}
if (peakEndField == -1) {
System.out.println("The field: peak end, is missing");
System.exit(1);
}
if (genesField == -1) {
System.out.println("The field: genes, is missing");
System.exit(1);
}
if (qvalField == -1) {
System.out.println("The field: q_value, is missing");
System.exit(1);
}
if (cytobandField == -1) {
System.out.println("The field: cytoband, is missing");
System.exit(1);
}
if (ampField == -1) {
System.out.println("The field: amp, is missing");
System.exit(1);
}
line = buf.readLine();
while (line != null) {
fields = line.split("\t");
Gistic gistic = new Gistic();
gistic.setCancerStudyId(cancerStudyId);
try {
gistic.setChromosome(Integer.parseInt(fields[chromosomeField]));
}
catch (NumberFormatException e) {
System.err.println("Ignoring row with chromosome number: " + fields[chromosomeField]);
line = buf.readLine();
continue;
}
gistic.setPeakStart(Integer.parseInt(fields[peakStartField]));
gistic.setPeakEnd(Integer.parseInt(fields[peakEndField]));
int amp = Integer.parseInt(fields[ampField]);
gistic.setAmp(amp == 1);
gistic.setCytoband(fields[cytobandField]);
gistic.setqValue((Float.parseFloat(fields[qvalField])));
// -- parse genes --
// parse out '[' and ']' chars and ** Do these brackets have meaning? **
String[] _genes = fields[genesField].replace("[","")
.replace("]", "")
.split(",");
// map _genes to list of CanonicalGenes
ArrayList<CanonicalGene> genes = new ArrayList<CanonicalGene>();
DaoGeneOptimized daoGene = DaoGeneOptimized.getInstance();
for (String gene : _genes) {
CanonicalGene canonicalGene = daoGene.getNonAmbiguousGene(gene);
if (canonicalGene == null) {
canonicalGene = new CanonicalGene(gene);
// System.out.println("gene not found, skipping: " + gene);
// throw new DaoException("gene not found: " + gene);
}
if (canonicalGene.isMicroRNA()) {
System.err.println("ignoring miRNA: " + canonicalGene.getHugoGeneSymbolAllCaps());
continue;
}
genes.add(canonicalGene);
}
// -- end parse genes --
gistic.setGenes_in_ROI(genes);
gistics.add(gistic);
line = buf.readLine();
}
buf.close();
reader.close();
return gistics;
}
}
|
package org.mskcc.cbio.portal.dao;
import org.mskcc.cbio.portal.model.*;
import org.mskcc.cbio.portal.model.ExtendedMutation.*;
import org.mskcc.cbio.portal.util.MutationKeywordUtils;
import org.apache.commons.lang.StringUtils;
import java.sql.*;
import java.util.*;
/**
* Data access object for Mutation table
*/
public final class DaoMutation {
public static final String NAN = "NaN";
public static int addMutation(ExtendedMutation mutation, boolean newMutationEvent) throws DaoException {
if (!MySQLbulkLoader.isBulkLoad()) {
throw new DaoException("You have to turn on MySQLbulkLoader in order to insert mutations");
}
else {
MySQLbulkLoader.getMySQLbulkLoader("mutation").insertRecord(
Long.toString(mutation.getMutationEventId()),
Integer.toString(mutation.getGeneticProfileId()),
Integer.toString(mutation.getSampleId()),
Long.toString(mutation.getGene().getEntrezGeneId()),
mutation.getSequencingCenter(),
mutation.getSequencer(),
mutation.getMutationStatus(),
mutation.getValidationStatus(),
mutation.getTumorSeqAllele1(),
mutation.getTumorSeqAllele2(),
mutation.getMatchedNormSampleBarcode(),
mutation.getMatchNormSeqAllele1(),
mutation.getMatchNormSeqAllele2(),
mutation.getTumorValidationAllele1(),
mutation.getTumorValidationAllele2(),
mutation.getMatchNormValidationAllele1(),
mutation.getMatchNormValidationAllele2(),
mutation.getVerificationStatus(),
mutation.getSequencingPhase(),
mutation.getSequenceSource(),
mutation.getValidationMethod(),
mutation.getScore(),
mutation.getBamFile(),
Integer.toString(mutation.getTumorAltCount()),
Integer.toString(mutation.getTumorRefCount()),
Integer.toString(mutation.getNormalAltCount()),
Integer.toString(mutation.getNormalRefCount()));
if (newMutationEvent) {
return addMutationEvent(mutation.getEvent())+1;
}
else {
return 1;
}
}
}
public static int addMutationEvent(ExtendedMutation.MutationEvent event) throws DaoException {
// use this code if bulk loading
// write to the temp file maintained by the MySQLbulkLoader
String keyword = MutationKeywordUtils.guessOncotatorMutationKeyword(event.getProteinChange(), event.getMutationType());
MySQLbulkLoader.getMySQLbulkLoader("mutation_event").insertRecord(
Long.toString(event.getMutationEventId()),
Long.toString(event.getGene().getEntrezGeneId()),
event.getChr(),
Long.toString(event.getStartPosition()),
Long.toString(event.getEndPosition()),
event.getReferenceAllele(),
event.getTumorSeqAllele(),
event.getProteinChange(),
event.getMutationType(),
event.getFunctionalImpactScore(),
Float.toString(event.getFisValue()),
event.getLinkXVar(),
event.getLinkPdb(),
event.getLinkMsa(),
event.getNcbiBuild(),
event.getStrand(),
event.getVariantType(),
event.getDbSnpRs(),
event.getDbSnpValStatus(),
event.getOncotatorDbSnpRs(),
event.getOncotatorRefseqMrnaId(),
event.getOncotatorCodonChange(),
event.getOncotatorUniprotName(),
event.getOncotatorUniprotAccession(),
Integer.toString(event.getOncotatorProteinPosStart()),
Integer.toString(event.getOncotatorProteinPosEnd()),
boolToStr(event.isCanonicalTranscript()),
keyword==null ? "\\N":(event.getGene().getHugoGeneSymbolAllCaps()+" "+keyword));
return 1;
}
public static int calculateMutationCount (int profileId) throws DaoException {
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = JdbcUtil.getDbConnection(DaoMutation.class);
pstmt = con.prepareStatement
("INSERT INTO mutation_count " +
"SELECT genetic_profile.`GENETIC_PROFILE_ID` , `SAMPLE_ID` , COUNT( * ) AS MUTATION_COUNT " +
"FROM `mutation` , `genetic_profile` " +
"WHERE mutation.`GENETIC_PROFILE_ID` = genetic_profile.`GENETIC_PROFILE_ID` " +
"AND genetic_profile.`GENETIC_PROFILE_ID`=? " +
"GROUP BY genetic_profile.`GENETIC_PROFILE_ID` , `SAMPLE_ID`;");
pstmt.setInt(1, profileId);
return pstmt.executeUpdate();
} catch (SQLException e) {
throw new DaoException(e);
} finally {
JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs);
}
}
public static ArrayList<ExtendedMutation> getMutations (int geneticProfileId, Collection<Integer> targetSampleList,
long entrezGeneId) throws DaoException {
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
ArrayList <ExtendedMutation> mutationList = new ArrayList <ExtendedMutation>();
try {
con = JdbcUtil.getDbConnection(DaoMutation.class);
pstmt = con.prepareStatement
("SELECT * FROM mutation "
+ "INNER JOIN mutation_event ON mutation.MUTATION_EVENT_ID=mutation_event.MUTATION_EVENT_ID "
+ "WHERE SAMPLE_ID IN ('"
+ org.apache.commons.lang.StringUtils.join(targetSampleList, "','") +
"') AND GENETIC_PROFILE_ID = ? AND mutation.ENTREZ_GENE_ID = ?");
pstmt.setInt(1, geneticProfileId);
pstmt.setLong(2, entrezGeneId);
rs = pstmt.executeQuery();
while (rs.next()) {
ExtendedMutation mutation = extractMutation(rs);
mutationList.add(mutation);
}
} catch (SQLException e) {
throw new DaoException(e);
} finally {
JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs);
}
return mutationList;
}
public static HashMap getSimplifiedMutations (int geneticProfileId, Collection<Integer> targetSampleList,
Collection<Long> entrezGeneIds) throws DaoException {
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
HashMap hm = new HashMap();
try {
con = JdbcUtil.getDbConnection(DaoMutation.class);
pstmt = con.prepareStatement
("SELECT SAMPLE_ID, ENTREZ_GENE_ID FROM mutation "
//+ "INNER JOIN mutation_event ON mutation.MUTATION_EVENT_ID=mutation_event.MUTATION_EVENT_ID "
+ "WHERE SAMPLE_ID IN ('"
+ org.apache.commons.lang.StringUtils.join(targetSampleList, "','")+
"') AND GENETIC_PROFILE_ID = ? AND mutation.ENTREZ_GENE_ID IN ('" +
org.apache.commons.lang.StringUtils.join(entrezGeneIds, "','") + "')");
pstmt.setInt(1, geneticProfileId);
rs = pstmt.executeQuery();
while (rs.next()) {
String tmpStr = new StringBuilder().append(Integer.toString(rs.getInt("SAMPLE_ID"))).append(Integer.toString(rs.getInt("ENTREZ_GENE_ID"))).toString();
hm.put(tmpStr, "");
}
} catch (SQLException e) {
throw new DaoException(e);
} finally {
JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs);
}
return hm;
}
public static ArrayList<ExtendedMutation> getMutations (int geneticProfileId, int sampleId,
long entrezGeneId) throws DaoException {
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
ArrayList <ExtendedMutation> mutationList = new ArrayList <ExtendedMutation>();
try {
con = JdbcUtil.getDbConnection(DaoMutation.class);
pstmt = con.prepareStatement
("SELECT * FROM mutation "
+ "INNER JOIN mutation_event ON mutation.MUTATION_EVENT_ID=mutation_event.MUTATION_EVENT_ID "
+ "WHERE SAMPLE_ID = ? AND GENETIC_PROFILE_ID = ? AND mutation.ENTREZ_GENE_ID = ?");
pstmt.setInt(1, sampleId);
pstmt.setInt(2, geneticProfileId);
pstmt.setLong(3, entrezGeneId);
rs = pstmt.executeQuery();
while (rs.next()) {
ExtendedMutation mutation = extractMutation(rs);
mutationList.add(mutation);
}
} catch (NullPointerException e) {
throw new DaoException(e);
} catch (SQLException e) {
throw new DaoException(e);
} finally {
JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs);
}
return mutationList;
}
/**
* Gets all Genes in a Specific Genetic Profile.
*
* @param geneticProfileId Genetic Profile ID.
* @return Set of Canonical Genes.
* @throws DaoException Database Error.
*/
public static Set<CanonicalGene> getGenesInProfile(int geneticProfileId) throws DaoException {
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
Set<CanonicalGene> geneSet = new HashSet<CanonicalGene>();
DaoGeneOptimized daoGene = DaoGeneOptimized.getInstance();
try {
con = JdbcUtil.getDbConnection(DaoMutation.class);
pstmt = con.prepareStatement
("SELECT DISTINCT ENTREZ_GENE_ID FROM mutation WHERE GENETIC_PROFILE_ID = ?");
pstmt.setInt(1, geneticProfileId);
rs = pstmt.executeQuery();
while (rs.next()) {
geneSet.add(daoGene.getGene(rs.getLong("ENTREZ_GENE_ID")));
}
} catch (SQLException e) {
throw new DaoException(e);
} finally {
JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs);
}
return geneSet;
}
public static ArrayList<ExtendedMutation> getMutations (long entrezGeneId) throws DaoException {
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
ArrayList <ExtendedMutation> mutationList = new ArrayList <ExtendedMutation>();
try {
con = JdbcUtil.getDbConnection(DaoMutation.class);
pstmt = con.prepareStatement
("SELECT * FROM mutation "
+ "INNER JOIN mutation_event ON mutation.MUTATION_EVENT_ID=mutation_event.MUTATION_EVENT_ID "
+ "WHERE mutation.ENTREZ_GENE_ID = ?");
pstmt.setLong(1, entrezGeneId);
rs = pstmt.executeQuery();
while (rs.next()) {
ExtendedMutation mutation = extractMutation(rs);
mutationList.add(mutation);
}
} catch (SQLException e) {
throw new DaoException(e);
} finally {
JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs);
}
return mutationList;
}
public static ArrayList<ExtendedMutation> getMutations (long entrezGeneId, String aminoAcidChange) throws DaoException {
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
ArrayList <ExtendedMutation> mutationList = new ArrayList <ExtendedMutation>();
try {
con = JdbcUtil.getDbConnection(DaoMutation.class);
pstmt = con.prepareStatement
("SELECT * FROM mutation_event"
+ " INNER JOIN mutation ON mutation.MUTATION_EVENT_ID=mutation_event.MUTATION_EVENT_ID "
+ " WHERE mutation.ENTREZ_GENE_ID = ? AND PROTEIN_CHANGE = ?");
pstmt.setLong(1, entrezGeneId);
pstmt.setString(2, aminoAcidChange);
rs = pstmt.executeQuery();
while (rs.next()) {
ExtendedMutation mutation = extractMutation(rs);
mutationList.add(mutation);
}
} catch (SQLException e) {
throw new DaoException(e);
} finally {
JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs);
}
return mutationList;
}
public static ArrayList<ExtendedMutation> getMutations (int geneticProfileId, int sampleId) throws DaoException {
return getMutations(geneticProfileId, Arrays.asList(new Integer(sampleId)));
}
public static ArrayList<ExtendedMutation> getMutations (int geneticProfileId, List<Integer> sampleIds) throws DaoException {
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
ArrayList <ExtendedMutation> mutationList = new ArrayList <ExtendedMutation>();
try {
con = JdbcUtil.getDbConnection(DaoMutation.class);
pstmt = con.prepareStatement
("SELECT * FROM mutation "
+ "INNER JOIN mutation_event ON mutation.MUTATION_EVENT_ID=mutation_event.MUTATION_EVENT_ID "
+ "WHERE GENETIC_PROFILE_ID = ? AND SAMPLE_ID in ('"+ StringUtils.join(sampleIds, "','")+"')");
pstmt.setInt(1, geneticProfileId);
rs = pstmt.executeQuery();
while (rs.next()) {
ExtendedMutation mutation = extractMutation(rs);
mutationList.add(mutation);
}
} catch (SQLException e) {
throw new DaoException(e);
} finally {
JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs);
}
return mutationList;
}
public static boolean hasAlleleFrequencyData (int geneticProfileId, int sampleId) throws DaoException {
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = JdbcUtil.getDbConnection(DaoMutation.class);
pstmt = con.prepareStatement
("SELECT EXISTS (SELECT 1 FROM mutation "
+ "WHERE GENETIC_PROFILE_ID = ? AND SAMPLE_ID = ? AND TUMOR_ALT_COUNT>=0 AND TUMOR_REF_COUNT>=0)");
pstmt.setInt(1, geneticProfileId);
pstmt.setInt(2, sampleId);
rs = pstmt.executeQuery();
return rs.next() && rs.getInt(1)==1;
} catch (NullPointerException e) {
throw new DaoException(e);
} catch (SQLException e) {
throw new DaoException(e);
} finally {
JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs);
}
}
public static ArrayList<ExtendedMutation> getMutations (long entrezGeneId, String aminoAcidChange, int excludeSampleId) throws DaoException {
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
ArrayList <ExtendedMutation> mutationList = new ArrayList <ExtendedMutation>();
try {
con = JdbcUtil.getDbConnection(DaoMutation.class);
pstmt = con.prepareStatement
("SELECT * FROM mutation, mutation_event "
+ "WHERE mutation.MUTATION_EVENT_ID=mutation_event.MUTATION_EVENT_ID "
+ "AND mutation.ENTREZ_GENE_ID = ? AND PROTEIN_CHANGE = ? AND SAMPLE_ID <> ?");
pstmt.setLong(1, entrezGeneId);
pstmt.setString(2, aminoAcidChange);
pstmt.setInt(3, excludeSampleId);
rs = pstmt.executeQuery();
while (rs.next()) {
ExtendedMutation mutation = extractMutation(rs);
mutationList.add(mutation);
}
} catch (NullPointerException e) {
throw new DaoException(e);
} catch (SQLException e) {
throw new DaoException(e);
} finally {
JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs);
}
return mutationList;
}
public static ArrayList<ExtendedMutation> getMutations (int geneticProfileId,
long entrezGeneId) throws DaoException {
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
ArrayList <ExtendedMutation> mutationList = new ArrayList <ExtendedMutation>();
try {
con = JdbcUtil.getDbConnection(DaoMutation.class);
pstmt = con.prepareStatement
("SELECT * FROM mutation "
+ "INNER JOIN mutation_event ON mutation.MUTATION_EVENT_ID=mutation_event.MUTATION_EVENT_ID "
+ "WHERE GENETIC_PROFILE_ID = ? AND mutation.ENTREZ_GENE_ID = ?");
pstmt.setInt(1, geneticProfileId);
pstmt.setLong(2, entrezGeneId);
rs = pstmt.executeQuery();
while (rs.next()) {
ExtendedMutation mutation = extractMutation(rs);
mutationList.add(mutation);
}
} catch (SQLException e) {
throw new DaoException(e);
} finally {
JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs);
}
return mutationList;
}
public static ArrayList<ExtendedMutation> getAllMutations () throws DaoException {
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
ArrayList <ExtendedMutation> mutationList = new ArrayList <ExtendedMutation>();
try {
con = JdbcUtil.getDbConnection(DaoMutation.class);
pstmt = con.prepareStatement
("SELECT * FROM mutation "
+ "INNER JOIN mutation_event ON mutation.MUTATION_EVENT_ID=mutation_event.MUTATION_EVENT_ID");
rs = pstmt.executeQuery();
while (rs.next()) {
ExtendedMutation mutation = extractMutation(rs);
mutationList.add(mutation);
}
} catch (SQLException e) {
throw new DaoException(e);
} finally {
JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs);
}
return mutationList;
}
/**
* Similar to getAllMutations(), but filtered by a passed geneticProfileId
* @param geneticProfileId
* @return
* @throws DaoException
*/
public static ArrayList<ExtendedMutation> getAllMutations (int geneticProfileId) throws DaoException {
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
ArrayList <ExtendedMutation> mutationList = new ArrayList <ExtendedMutation>();
try {
con = JdbcUtil.getDbConnection(DaoMutation.class);
pstmt = con.prepareStatement
("SELECT * FROM mutation "
+ "INNER JOIN mutation_event ON mutation.MUTATION_EVENT_ID=mutation_event.MUTATION_EVENT_ID "
+ "WHERE mutation.GENETIC_PROFILE_ID = ?");
pstmt.setInt(1, geneticProfileId);
rs = pstmt.executeQuery();
while (rs.next()) {
ExtendedMutation mutation = extractMutation(rs);
mutationList.add(mutation);
}
} catch (SQLException e) {
throw new DaoException(e);
} finally {
JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs);
}
return mutationList;
}
public static Set<ExtendedMutation.MutationEvent> getAllMutationEvents() throws DaoException {
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
Set<ExtendedMutation.MutationEvent> events = new HashSet<ExtendedMutation.MutationEvent>();
try {
con = JdbcUtil.getDbConnection(DaoMutation.class);
pstmt = con.prepareStatement
("SELECT * FROM mutation_event");
rs = pstmt.executeQuery();
while (rs.next()) {
ExtendedMutation.MutationEvent event = extractMutationEvent(rs);
events.add(event);
}
} catch (SQLException e) {
throw new DaoException(e);
} finally {
JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs);
}
return events;
}
public static long getLargestMutationEventId() throws DaoException {
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = JdbcUtil.getDbConnection(DaoMutation.class);
pstmt = con.prepareStatement
("SELECT MAX(`MUTATION_EVENT_ID`) FROM `mutation_event`");
rs = pstmt.executeQuery();
return rs.next() ? rs.getLong(1) : 0;
} catch (SQLException e) {
throw new DaoException(e);
} finally {
JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs);
}
}
private static ExtendedMutation extractMutation(ResultSet rs) throws SQLException, DaoException {
try {
ExtendedMutation mutation = new ExtendedMutation(extractMutationEvent(rs));
mutation.setGeneticProfileId(rs.getInt("GENETIC_PROFILE_ID"));
mutation.setSampleId(rs.getInt("SAMPLE_ID"));
mutation.setSequencingCenter(rs.getString("CENTER"));
mutation.setSequencer(rs.getString("SEQUENCER"));
mutation.setMutationStatus(rs.getString("MUTATION_STATUS"));
mutation.setValidationStatus(rs.getString("VALIDATION_STATUS"));
mutation.setTumorSeqAllele1(rs.getString("TUMOR_SEQ_ALLELE1"));
mutation.setTumorSeqAllele2(rs.getString("TUMOR_SEQ_ALLELE2"));
mutation.setMatchedNormSampleBarcode(rs.getString("MATCHED_NORM_SAMPLE_BARCODE"));
mutation.setMatchNormSeqAllele1(rs.getString("MATCH_NORM_SEQ_ALLELE1"));
mutation.setMatchNormSeqAllele2(rs.getString("MATCH_NORM_SEQ_ALLELE2"));
mutation.setTumorValidationAllele1(rs.getString("TUMOR_VALIDATION_ALLELE1"));
mutation.setTumorValidationAllele2(rs.getString("TUMOR_VALIDATION_ALLELE2"));
mutation.setMatchNormValidationAllele1(rs.getString("MATCH_NORM_VALIDATION_ALLELE1"));
mutation.setMatchNormValidationAllele2(rs.getString("MATCH_NORM_VALIDATION_ALLELE2"));
mutation.setVerificationStatus(rs.getString("VERIFICATION_STATUS"));
mutation.setSequencingPhase(rs.getString("SEQUENCING_PHASE"));
mutation.setSequenceSource(rs.getString("SEQUENCE_SOURCE"));
mutation.setValidationMethod(rs.getString("VALIDATION_METHOD"));
mutation.setScore(rs.getString("SCORE"));
mutation.setBamFile(rs.getString("BAM_FILE"));
mutation.setTumorAltCount(rs.getInt("TUMOR_ALT_COUNT"));
mutation.setTumorRefCount(rs.getInt("TUMOR_REF_COUNT"));
mutation.setNormalAltCount(rs.getInt("NORMAL_ALT_COUNT"));
mutation.setNormalRefCount(rs.getInt("NORMAL_REF_COUNT"));
return mutation;
}
catch(NullPointerException e) {
throw new DaoException(e);
}
}
private static ExtendedMutation.MutationEvent extractMutationEvent(ResultSet rs) throws SQLException, DaoException {
ExtendedMutation.MutationEvent event = new ExtendedMutation.MutationEvent();
event.setMutationEventId(rs.getLong("MUTATION_EVENT_ID"));
long entrezId = rs.getLong("mutation_event.ENTREZ_GENE_ID");
DaoGeneOptimized aDaoGene = DaoGeneOptimized.getInstance();
CanonicalGene gene = aDaoGene.getGene(entrezId);
event.setGene(gene);
event.setChr(rs.getString("CHR"));
event.setStartPosition(rs.getLong("START_POSITION"));
event.setEndPosition(rs.getLong("END_POSITION"));
event.setProteinChange(rs.getString("PROTEIN_CHANGE"));
event.setMutationType(rs.getString("MUTATION_TYPE"));
event.setFunctionalImpactScore(rs.getString("FUNCTIONAL_IMPACT_SCORE"));
event.setFisValue(rs.getFloat("FIS_VALUE"));
event.setLinkXVar(rs.getString("LINK_XVAR"));
event.setLinkPdb(rs.getString("LINK_PDB"));
event.setLinkMsa(rs.getString("LINK_MSA"));
event.setNcbiBuild(rs.getString("NCBI_BUILD"));
event.setStrand(rs.getString("STRAND"));
event.setVariantType(rs.getString("VARIANT_TYPE"));
event.setDbSnpRs(rs.getString("DB_SNP_RS"));
event.setDbSnpValStatus(rs.getString("DB_SNP_VAL_STATUS"));
event.setReferenceAllele(rs.getString("REFERENCE_ALLELE"));
event.setOncotatorDbSnpRs(rs.getString("ONCOTATOR_DBSNP_RS"));
event.setOncotatorRefseqMrnaId(rs.getString("ONCOTATOR_REFSEQ_MRNA_ID"));
event.setOncotatorCodonChange(rs.getString("ONCOTATOR_CODON_CHANGE"));
event.setOncotatorUniprotName(rs.getString("ONCOTATOR_UNIPROT_ENTRY_NAME"));
event.setOncotatorUniprotAccession(rs.getString("ONCOTATOR_UNIPROT_ACCESSION"));
event.setOncotatorProteinPosStart(rs.getInt("ONCOTATOR_PROTEIN_POS_START"));
event.setOncotatorProteinPosEnd(rs.getInt("ONCOTATOR_PROTEIN_POS_END"));
event.setCanonicalTranscript(rs.getBoolean("CANONICAL_TRANSCRIPT"));
event.setTumorSeqAllele(rs.getString("TUMOR_SEQ_ALLELE"));
event.setKeyword(rs.getString("KEYWORD"));
return event;
}
public static int getCount() throws DaoException {
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = JdbcUtil.getDbConnection(DaoMutation.class);
pstmt = con.prepareStatement
("SELECT COUNT(*) FROM mutation");
rs = pstmt.executeQuery();
if (rs.next()) {
return rs.getInt(1);
}
return 0;
} catch (SQLException e) {
throw new DaoException(e);
} finally {
JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs);
}
}
/**
* Get significantly mutated genes
* @param profileId
* @param entrezGeneIds
* @param thresholdRecurrence
* @param thresholdNumGenes
* @param selectedCaseIds
* @return
* @throws DaoException
*/
public static Map<Long, Map<String, String>> getSMGs(int profileId, Collection<Long> entrezGeneIds,
int thresholdRecurrence, int thresholdNumGenes,
Collection<Integer> selectedCaseIds) throws DaoException {
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = JdbcUtil.getDbConnection(DaoMutation.class);
pstmt = con.prepareStatement("SET SESSION group_concat_max_len = 1000000");
rs = pstmt.executeQuery();
String sql = "SELECT mutation.ENTREZ_GENE_ID, GROUP_CONCAT(mutation.SAMPLE_ID), COUNT(*), COUNT(*)/`LENGTH` AS count_per_nt"
+ " FROM mutation, gene"
+ " WHERE mutation.ENTREZ_GENE_ID=gene.ENTREZ_GENE_ID"
+ " AND GENETIC_PROFILE_ID=" + profileId
+ (entrezGeneIds==null?"":(" AND mutation.ENTREZ_GENE_ID IN("+StringUtils.join(entrezGeneIds,",")+")"))
+ (selectedCaseIds==null?"":(" AND mutation.SAMPLE_ID IN("+StringUtils.join(selectedCaseIds,",")+")"))
+ " GROUP BY mutation.ENTREZ_GENE_ID"
+ (thresholdRecurrence>0?(" HAVING COUNT(*)>="+thresholdRecurrence):"")
+ " ORDER BY count_per_nt DESC"
+ (thresholdNumGenes>0?(" LIMIT 0,"+thresholdNumGenes):"");
pstmt = con.prepareStatement(sql);
rs = pstmt.executeQuery();
Map<Long, Map<String, String>> map = new HashMap();
while (rs.next()) {
Map<String, String> value = new HashMap<>();
value.put("caseIds", rs.getString(2));
value.put("count", rs.getString(3));
map.put(rs.getLong(1), value);
}
return map;
} catch (SQLException e) {
throw new DaoException(e);
} finally {
JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs);
}
}
/**
* return the number of all mutations for a profile
* @param profileId
* @return Map < case id, mutation count >
* @throws DaoException
*/
public static int countMutationEvents(int profileId) throws DaoException {
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = JdbcUtil.getDbConnection(DaoMutation.class);
String sql = "SELECT count(DISTINCT `SAMPLE_ID`, `MUTATION_EVENT_ID`) FROM mutation"
+ " WHERE `GENETIC_PROFILE_ID`=" + profileId;
pstmt = con.prepareStatement(sql);
rs = pstmt.executeQuery();
if (rs.next()) {
return rs.getInt(1);
}
return 0;
} catch (SQLException e) {
throw new DaoException(e);
} finally {
JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs);
}
}
/**
* return the number of mutations for each sample
* @param sampleIds if null, return all case available
* @param profileId
* @return Map < sample id, mutation count >
* @throws DaoException
*/
public static Map<Integer, Integer> countMutationEvents(int profileId, Collection<Integer> sampleIds) throws DaoException {
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = JdbcUtil.getDbConnection(DaoMutation.class);
String sql;
if (sampleIds==null) {
sql = "SELECT `SAMPLE_ID`, `MUTATION_COUNT` FROM mutation_count"
+ " WHERE `GENETIC_PROFILE_ID`=" + profileId;
} else {
sql = "SELECT `SAMPLE_ID`, `MUTATION_COUNT` FROM mutation_count"
+ " WHERE `GENETIC_PROFILE_ID`=" + profileId
+ " AND `SAMPLE_ID` IN ('"
+ StringUtils.join(sampleIds,"','")
+ "')";
}
pstmt = con.prepareStatement(sql);
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
rs = pstmt.executeQuery();
while (rs.next()) {
map.put(rs.getInt(1), rs.getInt(2));
}
return map;
} catch (NullPointerException e) {
throw new DaoException(e);
} catch (SQLException e) {
throw new DaoException(e);
} finally {
JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs);
}
}
/**
* get events for each sample
* @return Map < sample id, list of event ids >
* @throws DaoException
*/
public static Map<Integer, Set<Long>> getSamplesWithMutations(Collection<Long> eventIds) throws DaoException {
return getSamplesWithMutations(StringUtils.join(eventIds, ","));
}
/**
* get events for each sample
* @param concatEventIds event ids concatenated by comma (,)
* @return Map < sample id, list of event ids >
* @throws DaoException
*/
public static Map<Integer, Set<Long>> getSamplesWithMutations(String concatEventIds) throws DaoException {
if (concatEventIds.isEmpty()) {
return Collections.emptyMap();
}
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = JdbcUtil.getDbConnection(DaoMutation.class);
String sql = "SELECT `SAMPLE_ID`, `MUTATION_EVENT_ID` FROM mutation"
+ " WHERE `MUTATION_EVENT_ID` IN ("
+ concatEventIds + ")";
pstmt = con.prepareStatement(sql);
Map<Integer, Set<Long>> map = new HashMap<Integer, Set<Long>> ();
rs = pstmt.executeQuery();
while (rs.next()) {
int sampleId = rs.getInt("SAMPLE_ID");
long eventId = rs.getLong("MUTATION_EVENT_ID");
Set<Long> events = map.get(sampleId);
if (events == null) {
events = new HashSet<Long>();
map.put(sampleId, events);
}
events.add(eventId);
}
return map;
} catch (NullPointerException e) {
throw new DaoException(e);
} catch (SQLException e) {
throw new DaoException(e);
} finally {
JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs);
}
}
/**
* @return Map < sample, list of event ids >
* @throws DaoException
*/
public static Map<Sample, Set<Long>> getSimilarSamplesWithMutationsByKeywords(
Collection<Long> eventIds) throws DaoException {
return getSimilarSamplesWithMutationsByKeywords(StringUtils.join(eventIds, ","));
}
/**
* @param concatEventIds event ids concatenated by comma (,)
* @return Map < sample, list of event ids >
* @throws DaoException
*/
public static Map<Sample, Set<Long>> getSimilarSamplesWithMutationsByKeywords(
String concatEventIds) throws DaoException {
if (concatEventIds.isEmpty()) {
return Collections.emptyMap();
}
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = JdbcUtil.getDbConnection(DaoMutation.class);
String sql = "SELECT `SAMPLE_ID`, `GENETIC_PROFILE_ID`, me1.`MUTATION_EVENT_ID`"
+ " FROM mutation cme, mutation_event me1, mutation_event me2"
+ " WHERE me1.`MUTATION_EVENT_ID` IN ("+ concatEventIds + ")"
+ " AND me1.`KEYWORD`=me2.`KEYWORD`"
+ " AND cme.`MUTATION_EVENT_ID`=me2.`MUTATION_EVENT_ID`";
pstmt = con.prepareStatement(sql);
Map<Sample, Set<Long>> map = new HashMap<Sample, Set<Long>> ();
rs = pstmt.executeQuery();
while (rs.next()) {
Sample sample = DaoSample.getSampleById(rs.getInt("SAMPLE_ID"));
long eventId = rs.getLong("MUTATION_EVENT_ID");
Set<Long> events = map.get(sample);
if (events == null) {
events = new HashSet<Long>();
map.put(sample, events);
}
events.add(eventId);
}
return map;
} catch (NullPointerException e) {
throw new DaoException(e);
} catch (SQLException e) {
throw new DaoException(e);
} finally {
JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs);
}
}
/**
* @param entrezGeneIds event ids concatenated by comma (,)
* @return Map < sample, list of event ids >
* @throws DaoException
*/
public static Map<Sample, Set<Long>> getSimilarSamplesWithMutatedGenes(
Collection<Long> entrezGeneIds) throws DaoException {
if (entrezGeneIds.isEmpty()) {
return Collections.emptyMap();
}
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = JdbcUtil.getDbConnection(DaoMutation.class);
String sql = "SELECT `SAMPLE_ID`, `GENETIC_PROFILE_ID`, `ENTREZ_GENE_ID`"
+ " FROM mutation"
+ " WHERE `ENTREZ_GENE_ID` IN ("+ StringUtils.join(entrezGeneIds,",") + ")";
pstmt = con.prepareStatement(sql);
Map<Sample, Set<Long>> map = new HashMap<Sample, Set<Long>> ();
rs = pstmt.executeQuery();
while (rs.next()) {
Sample sample = DaoSample.getSampleById(rs.getInt("SAMPLE_ID"));
long entrez = rs.getLong("ENTREZ_GENE_ID");
Set<Long> genes = map.get(sample);
if (genes == null) {
genes = new HashSet<Long>();
map.put(sample, genes);
}
genes.add(entrez);
}
return map;
} catch (NullPointerException e) {
throw new DaoException(e);
} catch (SQLException e) {
throw new DaoException(e);
} finally {
JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs);
}
}
public static Map<Long, Integer> countSamplesWithMutationEvents(Collection<Long> eventIds, int profileId) throws DaoException {
return countSamplesWithMutationEvents(StringUtils.join(eventIds, ","), profileId);
}
/**
* return the number of samples for each mutation event
* @param concatEventIds
* @param profileId
* @return Map < event id, sampleCount >
* @throws DaoException
*/
public static Map<Long, Integer> countSamplesWithMutationEvents(String concatEventIds, int profileId) throws DaoException {
if (concatEventIds.isEmpty()) {
return Collections.emptyMap();
}
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = JdbcUtil.getDbConnection(DaoMutation.class);
String sql = "SELECT `MUTATION_EVENT_ID`, count(DISTINCT `SAMPLE_ID`) FROM mutation"
+ " WHERE `GENETIC_PROFILE_ID`=" + profileId
+ " AND `MUTATION_EVENT_ID` IN ("
+ concatEventIds
+ ") GROUP BY `MUTATION_EVENT_ID`";
pstmt = con.prepareStatement(sql);
Map<Long, Integer> map = new HashMap<Long, Integer>();
rs = pstmt.executeQuery();
while (rs.next()) {
map.put(rs.getLong(1), rs.getInt(2));
}
return map;
} catch (SQLException e) {
throw new DaoException(e);
} finally {
JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs);
}
}
public static Map<Long, Integer> countSamplesWithMutatedGenes(Collection<Long> entrezGeneIds, int profileId) throws DaoException {
return countSamplesWithMutatedGenes(StringUtils.join(entrezGeneIds, ","), profileId);
}
/**
* return the number of samples for each mutated genes
* @param concatEntrezGeneIds
* @param profileId
* @return Map < entrez, sampleCount >
* @throws DaoException
*/
public static Map<Long, Integer> countSamplesWithMutatedGenes(String concatEntrezGeneIds, int profileId) throws DaoException {
if (concatEntrezGeneIds.isEmpty()) {
return Collections.emptyMap();
}
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = JdbcUtil.getDbConnection(DaoMutation.class);
String sql = "SELECT ENTREZ_GENE_ID, count(DISTINCT SAMPLE_ID)"
+ " FROM mutation"
+ " WHERE GENETIC_PROFILE_ID=" + profileId
+ " AND ENTREZ_GENE_ID IN ("
+ concatEntrezGeneIds
+ ") GROUP BY `ENTREZ_GENE_ID`";
pstmt = con.prepareStatement(sql);
Map<Long, Integer> map = new HashMap<Long, Integer>();
rs = pstmt.executeQuery();
while (rs.next()) {
map.put(rs.getLong(1), rs.getInt(2));
}
return map;
} catch (SQLException e) {
throw new DaoException(e);
} finally {
JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs);
}
}
public static Map<String, Integer> countSamplesWithKeywords(Collection<String> keywords, int profileId) throws DaoException {
if (keywords.isEmpty()) {
return Collections.emptyMap();
}
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = JdbcUtil.getDbConnection(DaoMutation.class);
String sql = "SELECT KEYWORD, count(DISTINCT SAMPLE_ID)"
+ " FROM mutation, mutation_event"
+ " WHERE GENETIC_PROFILE_ID=" + profileId
+ " AND mutation.MUTATION_EVENT_ID=mutation_event.MUTATION_EVENT_ID"
+ " AND KEYWORD IN ('"
+ StringUtils.join(keywords,"','")
+ "') GROUP BY `KEYWORD`";
pstmt = con.prepareStatement(sql);
Map<String, Integer> map = new HashMap<String, Integer>();
rs = pstmt.executeQuery();
while (rs.next()) {
map.put(rs.getString(1), rs.getInt(2));
}
return map;
} catch (SQLException e) {
throw new DaoException(e);
} finally {
JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs);
}
}
/**
*
* Counts all the samples in each cancer study in the collection of geneticProfileIds by mutation keyword
*
* @param keywords
* @param internalProfileIds
* @return Collection of Maps {"keyword" , "hugo" , "cancer_study" , "count"} where cancer_study == cancerStudy.getName();
* @throws DaoException
* @author Gideon Dresdner <dresdnerg@cbio.mskcc.org>
*/
public static Collection<Map<String, Object>> countSamplesWithKeywords(Collection<String> keywords, Collection<Integer> internalProfileIds) throws DaoException {
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = JdbcUtil.getDbConnection(DaoMutation.class);
String sql = "SELECT KEYWORD, GENETIC_PROFILE_ID, mutation.ENTREZ_GENE_ID, count(DISTINCT SAMPLE_ID) FROM mutation, mutation_event " +
"WHERE GENETIC_PROFILE_ID IN (" + StringUtils.join(internalProfileIds, ",") + ") " +
"AND mutation.MUTATION_EVENT_ID=mutation_event.MUTATION_EVENT_ID " +
"AND KEYWORD IN ('" + StringUtils.join(keywords, "','") + "') " +
"GROUP BY KEYWORD, GENETIC_PROFILE_ID";
pstmt = con.prepareStatement(sql);
rs = pstmt.executeQuery();
Collection<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
while (rs.next()) {
Map<String, Object> d = new HashMap<String, Object>();
String keyword = rs.getString(1);
Integer geneticProfileId = rs.getInt(2);
Long entrez = rs.getLong(3);
Integer count = rs.getInt(4);
// this is computing a join and in not optimal
GeneticProfile geneticProfile = DaoGeneticProfile.getGeneticProfileById(geneticProfileId);
Integer cancerStudyId = geneticProfile.getCancerStudyId();
CancerStudy cancerStudy = DaoCancerStudy.getCancerStudyByInternalId(cancerStudyId);
String name = cancerStudy.getName();
String cancerType = cancerStudy.getTypeOfCancerId();
CanonicalGene gene = DaoGeneOptimized.getInstance().getGene(entrez);
String hugo = gene.getHugoGeneSymbolAllCaps();
d.put("keyword", keyword);
d.put("hugo", hugo);
d.put("cancer_study", name);
d.put("cancer_type", cancerType);
d.put("count", count);
data.add(d);
}
return data;
} catch (SQLException e) {
throw new DaoException(e);
} finally {
JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs);
}
}
/**
*
* Counts up all the samples that have any mutation in a gene by genomic profile (ids)
*
* @param hugos
* @param internalProfileIds
* @return Collection of Maps {"hugo" , "cancer_study" , "count"} where cancer_study == cancerStudy.getName();
* and gene is the hugo gene symbol.
*
* @throws DaoException
* @author Gideon Dresdner <dresdnerg@cbio.mskcc.org>
*/
public static Collection<Map<String, Object>> countSamplesWithGenes(Collection<String> hugos, Collection<Integer> internalProfileIds) throws DaoException {
// convert hugos to entrezs
// and simultaneously construct a map to turn them back into hugo gene symbols later
List<Long> entrezs = new ArrayList<Long>();
Map<Long, CanonicalGene> entrez2CanonicalGene = new HashMap<Long, CanonicalGene>();
DaoGeneOptimized daoGeneOptimized = DaoGeneOptimized.getInstance();
for (String hugo : hugos) {
CanonicalGene canonicalGene = daoGeneOptimized.getGene(hugo);
Long entrez = canonicalGene.getEntrezGeneId();
entrezs.add(entrez);
entrez2CanonicalGene.put(entrez, canonicalGene);
}
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = JdbcUtil.getDbConnection(DaoMutation.class);
String sql = "select mutation.ENTREZ_GENE_ID, mutation.GENETIC_PROFILE_ID, count(distinct SAMPLE_ID) from mutation, mutation_event\n" +
"where GENETIC_PROFILE_ID in (" + StringUtils.join(internalProfileIds, ",") + ")\n" +
"and mutation.ENTREZ_GENE_ID in (" + StringUtils.join(entrezs, ",") + ")\n" +
"and mutation.MUTATION_EVENT_ID=mutation_event.MUTATION_EVENT_ID\n" +
"group by ENTREZ_GENE_ID, GENETIC_PROFILE_ID";
pstmt = con.prepareStatement(sql);
rs = pstmt.executeQuery();
Collection<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
while (rs.next()) {
Map<String, Object> d = new HashMap<String, Object>();
Long entrez = rs.getLong(1);
Integer geneticProfileId = rs.getInt(2);
Integer count = rs.getInt(3);
// can you do the boogie woogie to get a cancerStudy's name?
// this is computing a join and in not optimal
GeneticProfile geneticProfile = DaoGeneticProfile.getGeneticProfileById(geneticProfileId);
Integer cancerStudyId = geneticProfile.getCancerStudyId();
CancerStudy cancerStudy = DaoCancerStudy.getCancerStudyByInternalId(cancerStudyId);
String name = cancerStudy.getName();
String cancerType = cancerStudy.getTypeOfCancerId();
CanonicalGene canonicalGene = entrez2CanonicalGene.get(entrez);
String hugo = canonicalGene.getHugoGeneSymbolAllCaps();
d.put("hugo", hugo);
d.put("cancer_study", name);
d.put("cancer_type", cancerType);
d.put("count", count);
data.add(d);
}
return data;
} catch (SQLException e) {
throw new DaoException(e);
} finally {
JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs);
}
}
public static Collection<Map<String, Object>> countSamplesWithProteinChanges(
Collection<String> proteinChanges, Collection<Integer> internalProfileIds) throws DaoException
{
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = JdbcUtil.getDbConnection(DaoMutation.class);
String sql = "SELECT PROTEIN_CHANGE, GENETIC_PROFILE_ID, mutation.ENTREZ_GENE_ID, count(DISTINCT SAMPLE_ID) FROM mutation, mutation_event " +
"WHERE GENETIC_PROFILE_ID IN (" + StringUtils.join(internalProfileIds, ",") + ") " +
"AND mutation.MUTATION_EVENT_ID=mutation_event.MUTATION_EVENT_ID " +
"AND PROTEIN_CHANGE IN ('" + StringUtils.join(proteinChanges, "','") + "') " +
"GROUP BY PROTEIN_CHANGE, GENETIC_PROFILE_ID";
pstmt = con.prepareStatement(sql);
rs = pstmt.executeQuery();
Collection<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
while (rs.next()) {
Map<String, Object> d = new HashMap<String, Object>();
String proteinChange = rs.getString(1);
Integer geneticProfileId = rs.getInt(2);
Long entrez = rs.getLong(3);
Integer count = rs.getInt(4);
// can you do the boogie woogie to get a cancerStudy's name?
// this is computing a join and in not optimal
GeneticProfile geneticProfile = DaoGeneticProfile.getGeneticProfileById(geneticProfileId);
Integer cancerStudyId = geneticProfile.getCancerStudyId();
CancerStudy cancerStudy = DaoCancerStudy.getCancerStudyByInternalId(cancerStudyId);
String name = cancerStudy.getName();
String cancerType = cancerStudy.getTypeOfCancerId();
CanonicalGene gene = DaoGeneOptimized.getInstance().getGene(entrez);
String hugo = gene.getHugoGeneSymbolAllCaps();
d.put("protein_change", proteinChange);
d.put("hugo", hugo);
d.put("cancer_study", name);
d.put("cancer_type", cancerType);
d.put("count", count);
data.add(d);
}
return data;
} catch (SQLException e) {
throw new DaoException(e);
} finally {
JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs);
}
}
public static Collection<Map<String, Object>> countSamplesWithProteinPosStarts(
Collection<String> proteinPosStarts, Collection<Integer> internalProfileIds) throws DaoException
{
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = JdbcUtil.getDbConnection(DaoMutation.class);
//TODO: create where clause for mutation table to allow use of ENTREZ_GENE_ID index to filter results
String sql = "SELECT ONCOTATOR_PROTEIN_POS_START, GENETIC_PROFILE_ID, mutation.ENTREZ_GENE_ID, count(DISTINCT SAMPLE_ID) FROM mutation, mutation_event " +
"WHERE GENETIC_PROFILE_ID IN (" + StringUtils.join(internalProfileIds, ",") + ") " +
"AND mutation.MUTATION_EVENT_ID=mutation_event.MUTATION_EVENT_ID " +
//"AND concat(concat(mutation.ENTREZ_GENE_ID, '_'), ONCOTATOR_PROTEIN_POS_START)" +
//"IN ('" + StringUtils.join(proteinPosStarts, "','") + "') " +
"AND (mutation.ENTREZ_GENE_ID, ONCOTATOR_PROTEIN_POS_START)" +
"IN (" + StringUtils.join(proteinPosStarts, ",") + ") " +
"GROUP BY ONCOTATOR_PROTEIN_POS_START, GENETIC_PROFILE_ID";
pstmt = con.prepareStatement(sql);
rs = pstmt.executeQuery();
Collection<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
while (rs.next()) {
Map<String, Object> d = new HashMap<String, Object>();
String proteinPosStart = rs.getString(1);
Integer geneticProfileId = rs.getInt(2);
Long entrez = rs.getLong(3);
Integer count = rs.getInt(4);
// can you do the boogie woogie to get a cancerStudy's name?
// this is computing a join and in not optimal
GeneticProfile geneticProfile = DaoGeneticProfile.getGeneticProfileById(geneticProfileId);
Integer cancerStudyId = geneticProfile.getCancerStudyId();
CancerStudy cancerStudy = DaoCancerStudy.getCancerStudyByInternalId(cancerStudyId);
String name = cancerStudy.getName();
String cancerType = cancerStudy.getTypeOfCancerId();
CanonicalGene gene = DaoGeneOptimized.getInstance().getGene(entrez);
String hugo = gene.getHugoGeneSymbolAllCaps();
d.put("protein_pos_start", proteinPosStart);
d.put("protein_start_with_hugo", hugo+"_"+proteinPosStart);
d.put("hugo", hugo);
d.put("cancer_study", name);
d.put("cancer_type", cancerType);
d.put("count", count);
data.add(d);
}
return data;
} catch (SQLException e) {
throw new DaoException(e);
} finally {
JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs);
}
}
public static Set<Long> getGenesOfMutations(
Collection<Long> eventIds, int profileId) throws DaoException {
return getGenesOfMutations(StringUtils.join(eventIds, ","), profileId);
}
/**
* return entrez gene ids of the mutations specified by their mutaiton event ids.
* @param concatEventIds
* @param profileId
* @return
* @throws DaoException
*/
public static Set<Long> getGenesOfMutations(String concatEventIds, int profileId)
throws DaoException {
if (concatEventIds.isEmpty()) {
return Collections.emptySet();
}
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = JdbcUtil.getDbConnection(DaoMutation.class);
String sql = "SELECT DISTINCT ENTREZ_GENE_ID FROM mutation_event "
+ "WHERE MUTATION_EVENT_ID in ("
+ concatEventIds
+ ")";
pstmt = con.prepareStatement(sql);
Set<Long> set = new HashSet<Long>();
rs = pstmt.executeQuery();
while (rs.next()) {
set.add(rs.getLong(1));
}
return set;
} catch (SQLException e) {
throw new DaoException(e);
} finally {
JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs);
}
}
/**
* return keywords of the mutations specified by their mutaiton event ids.
* @param concatEventIds
* @param profileId
* @return
* @throws DaoException
*/
public static Set<String> getKeywordsOfMutations(String concatEventIds, int profileId)
throws DaoException {
if (concatEventIds.isEmpty()) {
return Collections.emptySet();
}
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = JdbcUtil.getDbConnection(DaoMutation.class);
String sql = "SELECT DISTINCT KEYWORD FROM mutation_event "
+ "WHERE MUTATION_EVENT_ID in ("
+ concatEventIds
+ ")";
pstmt = con.prepareStatement(sql);
Set<String> set = new HashSet<String>();
rs = pstmt.executeQuery();
while (rs.next()) {
set.add(rs.getString(1));
}
return set;
} catch (SQLException e) {
throw new DaoException(e);
} finally {
JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs);
}
}
protected static String boolToStr(boolean value)
{
return value ? "1" : "0";
}
public static void deleteAllRecordsInGeneticProfile(long geneticProfileId) throws DaoException {
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = JdbcUtil.getDbConnection(DaoMutation.class);
pstmt = con.prepareStatement("DELETE from mutation WHERE GENETIC_PROFILE_ID=?");
pstmt.setLong(1, geneticProfileId);
pstmt.executeUpdate();
} catch (SQLException e) {
throw new DaoException(e);
} finally {
JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs);
}
}
public static void deleteAllRecords() throws DaoException {
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = JdbcUtil.getDbConnection(DaoMutation.class);
pstmt = con.prepareStatement("TRUNCATE TABLE mutation");
pstmt.executeUpdate();
pstmt = con.prepareStatement("TRUNCATE TABLE mutation_event");
pstmt.executeUpdate();
} catch (SQLException e) {
throw new DaoException(e);
} finally {
JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs);
}
}
}
|
package alpaca;
import java.util.ArrayList;
import java.util.HashMap;
import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.firebase.client.ValueEventListener;
import alpaca.Alpaca;
/**
* This class is used to store alpaca objects. It first
* retrieves the name and tracker ID of each alpaca from
* the database and creates an alpaca object that can be
* used to update the information of the alpaca in the
* database.
*
* Process representations
*
* Loading
* [DB] -> [PacaCollection] = [x number of Alpaca objects]
*
* Updating
* [Alpaca object] -> [Update] -> [DB]
*
* @author Clayton Peterson
*
*/
public class PacaCollection {
/* URL and reference to the Firebase database */
private String url;
private Firebase dataRef;
/* The working collection of alpacas */
private ArrayList <Alpaca> alpacas;
public PacaCollection ()
{
url = "https://crackling-fire-2064.firebaseio.com/alpacas";
dataRef = new Firebase (url);
alpacas = new ArrayList <Alpaca> ();
loadAlpacasFromDatabase ();
}
private void loadAlpacasFromDatabase ()
{
dataRef.addListenerForSingleValueEvent (new ValueEventListener()
{
@Override
public void onDataChange (DataSnapshot snapshot)
{
ArrayList <?> database = (ArrayList <?>) snapshot.getValue ();
for (int ID = 0; ID < database.size (); ID++)
{
HashMap <?,?> alpacaDetails = (HashMap <?, ?>) database.get (ID);
alpacas.add (createAlpaca (ID, alpacaDetails));
}
}
@Override
public void onCancelled (FirebaseError arg0)
{
System.out.println ("Error loading from database");
}
});
}
private Alpaca createAlpaca (int ID, HashMap <?,?> alpacaDetails)
{
Alpaca out = new Alpaca ();
out.setDBRef (url, ID);
out.setName ((alpacaDetails.get ("name")).toString());
out.setTrackerID ((alpacaDetails.get ("trackerID")).toString());
out.hardware.setBatteryLife (((Long)
alpacaDetails.get ("trackerBatteryLife")).intValue());
return out;
}
public void update ()
{
for (int i = 0; i < alpacas.size (); i ++)
{
Alpaca a = alpacas.get (i);
Firebase dataRef = new Firebase (a.getDatabaseRef());
// Location
dataRef.child ("lat").setValue (a.hardware.getLatitudeDecimalDegrees ());
dataRef.child ("lng").setValue (a.hardware.getLongitudeDecimalDegrees ());
// Movement
dataRef.child ("speed").setValue (a.hardware.getSpeed ());
dataRef.child ("course").setValue (a.hardware.getCourse ());
// Flying
dataRef.child ("altitude").setValue (a.hardware.getAltitude ());
dataRef.child ("roll").setValue (a.hardware.getRoll ());
dataRef.child ("pitch").setValue (a.hardware.getPitch ());
// Vitals
dataRef.child ("heartRate").setValue (a.hardware.getHeartRate ());
dataRef.child ("temperature").setValue (a.hardware.getTemperature ());
// Tracker details
dataRef.child ("trackerBatteryLife").setValue (a.hardware.getBatteryLife ());
dataRef.child ("hasFix").setValue (a.hardware.haveFix());
dataRef.child ("numSatellites").setValue (a.hardware.getNumSatellites ());
dataRef.child ("signalQuality").setValue (a.hardware.getSignalQuality ());
}
}
public ArrayList <Alpaca> getAlpacas ()
{
return alpacas;
}
}
|
package com.galvarez.ttw.model;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.artemis.Aspect;
import com.artemis.ComponentMapper;
import com.artemis.Entity;
import com.artemis.annotations.Wire;
import com.artemis.systems.EntityProcessingSystem;
import com.badlogic.gdx.utils.IntIntMap;
import com.badlogic.gdx.utils.IntIntMap.Entry;
import com.galvarez.ttw.model.DiplomaticSystem.Action;
import com.galvarez.ttw.model.DiplomaticSystem.State;
import com.galvarez.ttw.model.components.AIControlled;
import com.galvarez.ttw.model.components.Diplomacy;
import com.galvarez.ttw.model.components.InfluenceSource;
import com.galvarez.ttw.model.map.GameMap;
import com.galvarez.ttw.model.map.Influence;
import com.galvarez.ttw.model.map.MapPosition;
import com.galvarez.ttw.rendering.components.Name;
@Wire
public final class AIDiplomaticSystem extends EntityProcessingSystem {
private static final Logger log = LoggerFactory.getLogger(AIDiplomaticSystem.class);
private ComponentMapper<Diplomacy> relations;
private ComponentMapper<MapPosition> positions;
private ComponentMapper<InfluenceSource> sources;
private DiplomaticSystem diplomaticSystem;
private final GameMap map;
@SuppressWarnings("unchecked")
public AIDiplomaticSystem(GameMap map) {
super(Aspect.getAspectForAll(AIControlled.class, Diplomacy.class));
this.map = map;
}
@Override
protected boolean checkProcessing() {
return true;
}
@Override
protected void process(Entity entity) {
Diplomacy diplo = relations.get(entity);
// TODO have a real AI algorithm for diplomacy
// neighbors from the nicest to the baddest
List<Entity> neighbors = getNeighboringSources(entity);
if (diplo.knownStates.contains(State.TREATY) && neighbors.size() > 2) {
// sign treaty with half the neighbors, not the last one (WAR for him!)
for (int i = 0; i < neighbors.size() / 2 && i < neighbors.size() - 1; i++) {
Entity target = neighbors.get(i);
makeProposal(entity, diplo, target, Action.SIGN_TREATY);
}
}
if (diplo.knownStates.contains(State.WAR)) {
// try to be at war with somebody, and only that somebody
List<Entity> atWarWith = diplo.getEmpires(State.WAR);
Entity target = neighbors.isEmpty() ? null : neighbors.get(neighbors.size() - 1);
// to change our war target, first make peace with preceding one
for (Entity war : atWarWith) {
if (target != war)
makeProposal(entity, diplo, war, Action.MAKE_PEACE);
}
if (target != null && !atWarWith.contains(target))
makeProposal(entity, diplo, target, Action.DECLARE_WAR);
}
}
private void makeProposal(Entity entity, Diplomacy diplo, Entity target, Action action) {
if (diplomaticSystem.getPossibleActions(diplo, target).contains(action)
// do not change status if same proposal is already on the table
&& diplo.proposals.get(target) != action
// do no make proposal to ourself
&& entity != target) {
log.debug("{} wants to {} with {}", entity.getComponent(Name.class), action.str, target.getComponent(Name.class));
diplo.proposals.put(target, action);
}
}
/** Neighbors from the nicest to the worst. */
private List<Entity> getNeighboringSources(Entity entity) {
IntIntMap neighbors = new IntIntMap(16);
MapPosition pos = positions.get(entity);
for (int i = 1; i < 10; i++) {
// TODO really search for all tiles
addInfluencer(neighbors, entity, pos.x + i, pos.y + i);
addInfluencer(neighbors, entity, pos.x - i, pos.y + i);
addInfluencer(neighbors, entity, pos.x + i, pos.y - i);
addInfluencer(neighbors, entity, pos.x - i, pos.y - i);
}
List<Entry> entries = new ArrayList<>();
neighbors.entries().forEach(e -> entries.add(e));
entries.sort((e1, e2) -> Integer.compare(e1.value, e2.value));
List<Entity> res = new ArrayList<>(entries.size());
entries.forEach(e -> res.add(world.getEntity(e.key)));
return res;
}
private void addInfluencer(IntIntMap neighbors, Entity capital, int x, int y) {
Influence inf = map.getInfluenceAt(x, y);
if (inf != null && !inf.isMainInfluencer(capital) && inf.hasMainInfluence())
neighbors.getAndIncrement(inf.getMainInfluenceSource(), 0, 1);
}
}
|
package jenkins.model;
import com.google.common.base.Predicate;
import hudson.Extension;
import hudson.Util;
import hudson.model.Job;
import hudson.model.PermalinkProjectAction.Permalink;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.model.listeners.RunListener;
import hudson.util.AtomicFileWriter;
import hudson.util.StreamTaskListener;
import org.apache.commons.io.FileUtils;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Convenient base implementation for {@link Permalink}s that satisfy
* certain properties.
*
* <p>
* For a permalink to be able to use this, it has to satisfy the following:
*
* <blockquote>
* Given a job J, permalink is a function F that computes a build B.
* A peephole permalink is a subset of this function that can be
* deduced to the "peep-hole" function G(B)->bool:
*
* <pre>
* F(J) = { newest B | G(B)==true }
* </pre>
* </blockquote>
*
* <p>
* Intuitively speaking, a peep-hole permalink resolves to the latest build that
* satisfies a certain characteristics that can be determined solely by looking
* at the build and nothing else (most commonly its build result.)
*
* <p>
* This base class provides a file-based caching mechanism that avoids
* walking the long build history. The cache is a symlink to the build directory
* where symlinks are supported, and text file that contains the build number otherwise.
*
* <p>
* The implementation transparently tolerates G(B) that goes from true to false over time
* (it simply scans the history till find the new matching build.) To tolerate G(B)
* that goes from false to true, you need to be able to intercept whenever G(B) changes
* from false to true, then call {@link #resolve(Job)} to check the current permalink target
* is up to date, then call {@link #updateCache(Job, Run)} if it needs updating.
*
* @author Kohsuke Kawaguchi
* @since 1.507
*/
public abstract class PeepholePermalink extends Permalink implements Predicate<Run<?,?>> {
/**
* Checks if the given build satisfies the peep-hole criteria.
*
* This is the "G(B)" as described in the class javadoc.
*/
public abstract boolean apply(Run<?,?> run);
/**
* The file in which the permalink target gets recorded.
*/
protected File getPermalinkFile(Job<?,?> job) {
return new File(job.getBuildDir(),getId());
}
/**
* Resolves the permalink by using the cache if possible.
*/
@Override
public Run<?, ?> resolve(Job<?, ?> job) {
File f = getPermalinkFile(job);
Run<?,?> b=null;
try {
String target = readSymlink(f);
if (target!=null) {
int n = Integer.parseInt(Util.getFileName(target));
if (n==RESOLVES_TO_NONE) return null;
b = job.getBuildByNumber(n);
if (b!=null && apply(b))
return b; // found it (in the most efficient way possible)
// the cache is stale. start the search
if (b==null)
b=job.getNearestOldBuild(n);
}
} catch (InterruptedException e) {
LOGGER.log(Level.WARNING, "Failed to read permalink cache:" + f, e);
// if we fail to read the cache, fall back to the re-computation
} catch (IOException e) {
// this happens when the symlink doesn't exist
// (and it cannot be distinguished from the case when the actual I/O error happened
}
if (b==null) {
// no cache
b = job.getLastBuild();
}
// start from the build 'b' and locate the build that matches the criteria going back in time
b = find(b);
updateCache(job,b);
return b;
}
/**
* Start from the build 'b' and locate the build that matches the criteria going back in time
*/
private Run<?,?> find(Run<?,?> b) {
for ( ; b!=null && !apply(b); b=b.getPreviousBuild())
;
return b;
}
/**
* Remembers the value 'n' in the cache for future {@link #resolve(Job)}.
*/
protected void updateCache(@Nonnull Job<?,?> job, @Nullable Run<?,?> b) {
final int n = b==null ? RESOLVES_TO_NONE : b.getNumber();
File cache = getPermalinkFile(job);
cache.getParentFile().mkdirs();
try {
String target = String.valueOf(n);
if (b != null && !new File(job.getBuildDir(), target).exists()) {
// (re)create the build Number->Id symlink
Util.createSymlink(job.getBuildDir(),b.getId(),target,TaskListener.NULL);
}
writeSymlink(cache, String.valueOf(n));
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to update "+job+" "+getId()+" permalink for " + b, e);
cache.delete();
} catch (InterruptedException e) {
LOGGER.log(Level.WARNING, "Failed to update "+job+" "+getId()+" permalink for " + b, e);
cache.delete();
}
}
// File.exists returns false for a link with a missing target, so for Java 6 compatibility we have to use this circuitous method to see if it was created.
private static boolean exists(File link) {
File[] kids = link.getParentFile().listFiles();
return kids != null && Arrays.asList(kids).contains(link);
}
static String readSymlink(File cache) throws IOException, InterruptedException {
String target = Util.resolveSymlink(cache);
if (target==null && cache.exists()) {
// if this file isn't a symlink, it must be a regular file
target = FileUtils.readFileToString(cache,"UTF-8").trim();
}
return target;
}
static void writeSymlink(File cache, String target) throws IOException, InterruptedException {
StringWriter w = new StringWriter();
StreamTaskListener listener = new StreamTaskListener(w);
Util.createSymlink(cache.getParentFile(),target,cache.getName(),listener);
// Avoid calling resolveSymlink on a nonexistent file as it will probably throw an IOException:
if (!exists(cache) || Util.resolveSymlink(cache)==null) {
// symlink not supported. use a regular file
AtomicFileWriter cw = new AtomicFileWriter(cache);
try {
cw.write(target);
cw.commit();
} finally {
cw.abort();
}
}
}
@Extension
public static class RunListenerImpl extends RunListener<Run<?,?>> {
/**
* If any of the peephole permalink points to the build to be deleted, update it to point to the new location.
*/
@Override
public void onDeleted(Run run) {
Job<?, ?> j = run.getParent();
for (PeepholePermalink pp : Util.filter(j.getPermalinks(), PeepholePermalink.class)) {
if (pp.apply(run)) {
if (pp.resolve(j)==run) {
pp.updateCache(j,pp.find(run.getPreviousBuild()));
}
}
}
}
/**
* See if the new build matches any of the peephole permalink.
*/
@Override
public void onCompleted(Run<?,?> run, @Nonnull TaskListener listener) {
Job<?, ?> j = run.getParent();
for (PeepholePermalink pp : Util.filter(j.getPermalinks(), PeepholePermalink.class)) {
if (pp.apply(run)) {
Run<?, ?> cur = pp.resolve(j);
if (cur==null || cur.getNumber()<run.getNumber())
pp.updateCache(j,run);
}
}
}
}
private static final int RESOLVES_TO_NONE = -1;
private static final Logger LOGGER = Logger.getLogger(PeepholePermalink.class.getName());
}
|
package hudson.model;
import hudson.model.MultiStageTimeSeries.TimeScale;
import junit.framework.TestCase;
import org.apache.commons.io.IOUtils;
import org.jfree.chart.JFreeChart;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* @author Kohsuke Kawaguchi
*/
public class LoadStatisticsTest extends TestCase {
public void testGraph() throws IOException {
LoadStatistics ls = new LoadStatistics(0, 0) {
public int computeIdleExecutors() {
throw new UnsupportedOperationException();
}
public int computeTotalExecutors() {
throw new UnsupportedOperationException();
}
public int computeQueueLength() {
throw new UnsupportedOperationException();
}
};
for (int i = 0; i < 50; i++) {
ls.totalExecutors.update(4);
ls.busyExecutors.update(3);
ls.queueLength.update(3);
}
for (int i = 0; i < 50; i++) {
ls.totalExecutors.update(0);
ls.busyExecutors.update(0);
ls.queueLength.update(1);
}
JFreeChart chart = ls.createTrendChart(TimeScale.SEC10).createChart();
BufferedImage image = chart.createBufferedImage(400, 200);
File tempFile = File.createTempFile("chart-", "png");
FileOutputStream os = new FileOutputStream(tempFile);
try {
ImageIO.write(image, "PNG", os);
} finally {
IOUtils.closeQuietly(os);
tempFile.delete();
}
}
}
|
package com.ionic.keyboard;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.LOG;
import org.apache.cordova.PluginResult.Status;
import org.json.JSONArray;
import org.json.JSONException;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.OrientationEventListener;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.ValueCallback;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.content.Context;
import android.graphics.Rect;
import android.util.DisplayMetrics;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.inputmethod.InputMethodManager;
public class IonicKeyboard extends CordovaPlugin{
public void initialize(final CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
//calculate density-independent pixels (dp)
DisplayMetrics dm = new DisplayMetrics();
cordova.getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
final float density = dm.density;
final CordovaWebView appView = webView;
final View rootView = cordova.getActivity().getWindow().getDecorView().findViewById(android.R.id.content).getRootView();
OnGlobalLayoutListener list = new OnGlobalLayoutListener() {
int previousHeightDiff = 0;
@Override
public void onGlobalLayout() {
Rect r = new Rect();
//r will be populated with the coordinates of your view that area still visible.
rootView.getWindowVisibleDisplayFrame(r);
View v = rootView.getRootView();
appView.sendJavascript("cordova.fireWindowEvent('native.viewPortChanged', " +
"{" +
"density: '" + Float.toString(density) + "', " +
"viewPort: {" +
"top: " + Integer.toString(r.top) + ", " +
"bottom: " + Integer.toString(r.bottom) + ", " +
"left: " + Integer.toString(r.left) + ", " +
"right: " + Integer.toString(r.right) + ", " +
"width: " + Integer.toString(r.width()) + ", " +
"height: " + Integer.toString(r.height()) +
"}, " +
"device: {" +
"top: " + Integer.toString(v.getTop()) + ", " +
"bottom: " + Integer.toString(v.getBottom()) + ", " +
"left: " + Integer.toString(v.getLeft()) + ", " +
"top: " + Integer.toString(v.getTop()) + ", " +
"width: " + Integer.toString(v.getWidth()) + ", " +
"height: " + Integer.toString(v.getHeight()) +
"}"+
"});");
}
};
rootView.getViewTreeObserver().addOnGlobalLayoutListener(list);
}
public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException {
if ("close".equals(action)) {
cordova.getThreadPool().execute(new Runnable() {
public void run() {
InputMethodManager inputManager = (InputMethodManager) cordova.getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
View v = cordova.getActivity().getCurrentFocus();
if (v == null) {
callbackContext.error("No current focus");
} else {
inputManager.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
callbackContext.success(); // Thread-safe.
}
}
});
return true;
}
if ("show".equals(action)) {
cordova.getThreadPool().execute(new Runnable() {
public void run() {
((InputMethodManager) cordova.getActivity().getSystemService(Context.INPUT_METHOD_SERVICE)).toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY);
callbackContext.success(); // Thread-safe.
}
});
return true;
}
if ("applyFullScreenOption".equals(action)) {
final String show = args.getString(0);
cordova.getThreadPool().execute(new Runnable() {
public void run() {
final Window window = cordova.getActivity().getWindow();
if (show == "immersive") {
goImmersive(window);
}
else if (show == "full") {
goFullScreen(window);
}
else if (show == "nonimmersive") {
goFullScreen(window);
}
else {
goNonFullScreen(window);
}
callbackContext.success(); // Thread-safe.
}
});
return true;
}
return false; // Returning false results in a "MethodNotFound" error.
}
private void goImmersive(Window window) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
else {
window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
}
private void goNonImmersive(Window window) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
else {
window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
}
private void goFullScreen(Window window) {
window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
private void goNonFullScreen(Window window) {
window.clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
}
}
|
package com.marketo.plugin;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import android.app.Activity;
import com.marketo.Marketo;
import com.marketo.MarketoActionMetaData;
import com.marketo.MarketoConfig;
import com.marketo.MarketoLead;
import com.marketo.errors.MktoException;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONException;
import marketo.utils.MktoUtils;
public class MarketoPlugin extends CordovaPlugin {
public static final String KEY_ACTION_TYPE = "Action Type";
public static final String KEY_ACTION_DETAILS = "Action Details";
public static final String KEY_ACTION_METRIC = "Action Metric";
public static final String KEY_ACTION_LENGTH = "Action Length";
public static final String KEY_FIRST_NAME = "firstName";
public static final String KEY_LAST_NAME = "lastName";
public static final String KEY_ADDRESS = "address";
public static final String KEY_CITY = "city";
public static final String KEY_STATE = "state";
public static final String KEY_COUNTRY = "country";
public static final String KEY_POSTAL_CODE = "postalCode";
public static final String KEY_GENDER = "gender";
public static final String KEY_EMAIL = "email";
public static final String KEY_TWITTER = "twitterId";
public static final String KEY_FACEBOOK = "facebookId";
public static final String KEY_LINKEDIN = "linkedinId";
public static final String KEY_LEAD_SOURCE = "leadSource";
public static final String KEY_BIRTHDAY = "dateOfBirth";
public static final String KEY_FACEBOOK_PROFILE_URL = "facebookProfileURL";
public static final String KEY_FACEBOOK_PROFILE_PIC = "facebookPhotoURL";
public static final String KEY_FOR_NOTIFICATION_ICON = "notificaion.icon_path";
private CallbackContext callbackContext;
private Activity activityContext;
@Override
public boolean execute(String action, JSONArray args, CallbackContext _callbackContext) throws JSONException {
try {
callbackContext = _callbackContext;
activityContext = this.cordova.getActivity();
final Marketo marketo = Marketo.getInstance(activityContext);
Log.d("MarketoSDK", "Action " + action);
if ("initialize".equals(action)) {
final String MUCHKIN_ID = args.optString(0);
final String SECRET_KEY = args.optString(1);
this.cordova.getThreadPool().execute(new Runnable() {
@Override
public void run() {
marketo.initializeSDK(MUCHKIN_ID, SECRET_KEY);
callbackContext.success();
}
});
return true;
} else if ("initializeMarketoPush".equals(action)) {
final String PROJECT_ID = args.optString(0);
this.cordova.getThreadPool().execute(new Runnable() {
@Override
public void run() {
marketo.initializeMarketoPush(PROJECT_ID);
callbackContext.success();
}
});
return true;
} else if ("associateLead".equals(action)) {
final JSONObject jsonObject = new JSONObject(args.optString(0));
this.cordova.getThreadPool().execute(new Runnable() {
@Override
public void run() {
marketo.associateLead(getLeaad(jsonObject));
callbackContext.success();
}
});
return true;
} else if ("onStop".equals(action)) {
this.cordova.getThreadPool().execute(new Runnable() {
@Override
public void run() {
Marketo.onStop(activityContext);
callbackContext.success();
}
});
return true;
} else if ("onStart".equals(action)) {
this.cordova.getThreadPool().execute(new Runnable() {
@Override
public void run() {
Marketo.onStart(activityContext);
callbackContext.success();
}
});
return true;
} else if ("reportaction".equals(action)) {
final String REPORT_ACTION = args.optString(0);
final JSONObject json = new JSONObject(args.optString(1));
this.cordova.getThreadPool().execute(new Runnable() {
@Override
public void run() {
Marketo.reportAction(REPORT_ACTION, getMetadata(json));
callbackContext.success();
}
});
return true;
} else if ("removeSecureSignature".equals(action)) {
this.cordova.getThreadPool().execute(new Runnable() {
@Override
public void run() {
marketo.removeSecureSignature();
callbackContext.success();
}
});
return true;
} else if ("isSecureModeEnabled".equals(action)) {
this.cordova.getThreadPool().execute(new Runnable() {
@Override
public void run() {
callbackContext.success(Marketo.isSecureModeEnabled()?0:1);
}
});
return true;
} else if ("setSecureSignature".equals(action)) {
final String accessKey = args.optString(0);
final String signature = args.optString(1);
final String email = args.optString(2);
final long timestamp = args.optLong(3);
this.cordova.getThreadPool().execute(new Runnable() {
@Override
public void run() {
MarketoConfig.SecureMode secureMode = new MarketoConfig.SecureMode();
secureMode.setAccessKey(accessKey);
secureMode.setEmail(email);
secureMode.setSignature(signature);
secureMode.setTimestamp(timestamp);
marketo.setSecureSignature(secureMode);
callbackContext.success();
}
});
return true;
} else if ("getDeviceId".equals(action)) {
this.cordova.getThreadPool().execute(new Runnable() {
@Override
public void run() {
callbackContext.success(marketo.getDeviceId());
}
});
return true;
} else if ("setNotificationConfig".equals(action)) {
final Bitmap bitmap = getBitMap(args.optString(0));
final int id = getResourceID(args.optString(1));
this.cordova.getThreadPool().execute(new Runnable() {
@Override
public void run() {
MarketoConfig.Notification config = new MarketoConfig.Notification();
config.setNotificationLargeIcon(bitmap);
config.setNotificationSmallIcon(id);
marketo.setNotificationConfig(config);
callbackContext.success();
}
});
return true;
} else if ("getNotificationConfig".equals(action)) {
this.cordova.getThreadPool().execute(new Runnable() {
@Override
public void run() {
MarketoConfig.Notification config = marketo.getNotificationConfig();
JSONArray object = new JSONArray();
object.put(BitMapPath(config.getNotificationLargeIcon()));
object.put(getResourseName(config.getNotificationSmallIcon()));
callbackContext.success(object);
}
});
return true;
} else if ("settimeout".equals(action)) {
final int TIME_OUT = args.optInt(0);
this.cordova.getThreadPool().execute(new Runnable() {
@Override
public void run() {
Marketo.setNetworkTimeout(TIME_OUT);
callbackContext.success();
}
});
return true;
}
return false;
} catch (Exception e) {
e.printStackTrace();
callbackContext.error(e.getMessage());
return false;
}
}
public int getResourceID(String resourceName){
return activityContext.getResources().getIdentifier(resourceName , "drawable", activityContext.getPackageName());
}
public String getResourseName(int resoirceID){
return activityContext.getResources().getResourceEntryName(resoirceID);
}
public Bitmap getBitMap(String filePath){
MktoUtils.writePreference(activityContext, KEY_FOR_NOTIFICATION_ICON, filePath);
Bitmap bm = null;
InputStream is = null;
BufferedInputStream bis = null;
try {
URLConnection conn = new URL(filePath).openConnection();
conn.connect();
is = conn.getInputStream();
bis = new BufferedInputStream(is, 8192);
bm = BitmapFactory.decodeStream(bis);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
}catch (IOException e) {
e.printStackTrace();
}
}
if (is != null) {
try {
is.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}
return bm;
}
public String BitMapPath(Bitmap bitmap){
return MktoUtils.readPreference(activityContext, KEY_FOR_NOTIFICATION_ICON);
}
private MarketoActionMetaData getMetadata(JSONObject json) {
MarketoActionMetaData actionMetaData = new MarketoActionMetaData();
try {
Iterator<String> items = json.keys();
for (; items.hasNext(); ) {
String key = items.next();
String value = json.optString(key);
if (key.equals(KEY_ACTION_TYPE)) {
actionMetaData.setActionType(value);
} else if (key.equals(KEY_ACTION_DETAILS)) {
actionMetaData.setActionDetails(value);
} else if (key.equals(KEY_ACTION_LENGTH)) {
actionMetaData.setActionLength(value);
} else if (key.equals(KEY_ACTION_METRIC)) {
actionMetaData.setActionMetric(value);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return actionMetaData;
}
private MarketoLead getLeaad(JSONObject object) {
MarketoLead lead = new MarketoLead();
try {
@SuppressWarnings("unchecked")
Iterator<String> items = object.keys();
for (; items.hasNext(); ) {
String key = items.next();
String value = object.optString(key);
if (key.equals(KEY_FIRST_NAME)) {
lead.setFirstName(value);
} else if (key.equals(KEY_LAST_NAME)) {
lead.setLastName(value);
} else if (key.equals(KEY_ADDRESS)) {
lead.setAddress(value);
} else if (key.equals(KEY_CITY)) {
lead.setCity(value);
} else if (key.equals(KEY_STATE)) {
lead.setState(value);
} else if (key.equals(KEY_COUNTRY)) {
lead.setCountry(value);
} else if (key.equals(KEY_POSTAL_CODE)) {
lead.setPostalCode(value);
} else if (key.equals(KEY_GENDER)) {
lead.setGender(value);
} else if (key.equals(KEY_EMAIL)) {
try {
lead.setEmail(value);
} catch (MktoException e) {
e.printStackTrace();
}
} else if (key.equals(KEY_TWITTER)) {
lead.setTwitterId(value);
} else if (key.equals(KEY_FACEBOOK)) {
lead.setFacebookId(value);
} else if (key.equals(KEY_LINKEDIN)) {
lead.setLinkedinId(value);
} else if (key.equals(KEY_LEAD_SOURCE)) {
lead.setLeadSource(value);
} else if (key.equals(KEY_BIRTHDAY)) {
lead.setBirthDay(value);
} else if (key.equals(KEY_FACEBOOK_PROFILE_PIC)) {
lead.setFacebookProfilePicURL(value);
} else if (key.equals(KEY_FACEBOOK_PROFILE_URL)) {
lead.setFacebookProfileURL(value);
} else {
lead.setCustomField(key, value);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return lead;
}
}
|
package bam.display.opengl;
import bam.display.DisplayParams;
import lombok.extern.slf4j.Slf4j;
import nativelibs.NativeLibsBinder;
import nativelibs.NativeLibsJarIntrospectSearch;
import nativelibs.NativeLibsSearch;
import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.GL11;
import java.io.File;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.ProviderNotFoundException;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
@Slf4j
public class OpenGlDisplay {
private AtomicBoolean displayEnable = new AtomicBoolean();
private final OpenGlSetup openGlSetup;
private final int fpsLimit;
private final float width;
private final float height;
public OpenGlDisplay(DisplayParams displayParams) {
fpsLimit = displayParams.getFpsLimit();
width = displayParams.getWidth();
height = displayParams.getHeight();
openGlSetup = new OpenGlSetup(displayParams);
}
public void init() {
if (!displayEnable.get()) {
try {
bindNativeLibs();
Display.create();
openGlSetup.setup();
displayEnable.set(true);
} catch (LWJGLException e) {
log.info(e.getMessage(), e);
}
}
}
public void destroy() {
if (displayEnable.get()) {
Display.destroy();
}
}
public void draw(Runnable redrawing) {
if (displayEnable.get()) {
// Clear The Screen And The Depth Buffer
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);
GL11.glPushMatrix();
redrawing.run();
GL11.glLoadIdentity();
GL11.glPopMatrix();
GL11.glFlush();
Display.sync(fpsLimit);
Display.update();
}
}
public boolean isDisplayEnabled() {
return displayEnable.get() && !Display.isCloseRequested();
}
public float getDisplayWidth() {
return width;
}
public float getDisplayHeight() {
return height;
}
private void bindNativeLibs() {
Set<Path> pathStream;
try {
pathStream = new NativeLibsJarIntrospectSearch().getNativeLibraries();
} catch (ProviderNotFoundException e) {
log.error(e.getMessage());
pathStream = new NativeLibsIDEIntrospectSearch().getNativeLibraries();
}
new NativeLibsBinder().bindLibs(pathStream);
}
private class NativeLibsIDEIntrospectSearch implements NativeLibsSearch {
@Override
public Optional<Path> transform(Path targetPath) {
final URL dirURL = OpenGlDisplay.class.getClassLoader().getResource(targetPath.toString());
if (Objects.nonNull(dirURL)) {
String dirName = dirURL.getFile();
return Optional.of(new File(dirName).toPath());
}
return Optional.empty();
}
}
}
|
package org.ethereum.core;
import org.ethereum.crypto.ECKey;
import org.ethereum.db.ByteArrayWrapper;
import org.ethereum.manager.WorldManager;
import org.ethereum.net.submit.WalletTransaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spongycastle.util.encoders.Hex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
/**
* The Wallet handles the management of accounts with addresses and private keys.
* New accounts can be generated and added to the wallet and existing accounts can be queried.
*/
@Component
@DependsOn("worldManager")
public class Wallet {
private Logger logger = LoggerFactory.getLogger("wallet");
// TODO: a) the values I need to keep for address state is balance & nonce & ECKey
// TODO: b) keep it to be easy accessed by the toAddress()
// private HashMap<Address, BigInteger> rows = new HashMap<>();
// This map of transaction designed
// to approve the tx by external trusted peer
private Map<String, WalletTransaction> walletTransactions = new ConcurrentHashMap<>();
// <address, info> table for a wallet
private Map<String, Account> rows = new HashMap<>();
private long high;
@Autowired
private WorldManager worldManager;
@Autowired
private ApplicationContext context;
private List<WalletListener> listeners = new ArrayList<>();
private Map<ByteArrayWrapper, Transaction> transactionMap = new HashMap<>();
public void setWorldManager(WorldManager worldManager) {
this.worldManager = worldManager;
}
public void addNewAccount() {
Account account = new Account();
account.init();
String address = Hex.toHexString(account.getEcKey().getAddress());
rows.put(address, account);
for (WalletListener listener : listeners)
listener.valueChanged();
}
public void importKey(byte[] privKey) {
Account account = context.getBean(Account.class);
account.init(ECKey.fromPrivate(privKey));
String address = Hex.toHexString(account.getEcKey().getAddress());
rows.put(address, account);
notifyListeners();
}
public void addListener(WalletListener walletListener) {
this.listeners.add(walletListener);
}
public Collection<Account> getAccountCollection() {
return rows.values();
}
public AccountState getAccountState(byte[] address) {
AccountState accountState =
worldManager.getRepository().getAccountState(address);
return accountState;
}
public BigInteger totalBalance() {
BigInteger sum = BigInteger.ZERO;
for (Account account : rows.values()) {
sum = sum.add(account.getBalance());
}
return sum;
}
/**
* The wallet will call this method once transaction been send to the network,
* once the the GET_TRANSACTION will be answered with that particular transaction
* it will be considered as received by the net.
*/
public WalletTransaction addByWalletTransaction(Transaction transaction) {
String hash = Hex.toHexString(transaction.getHash());
WalletTransaction walletTransaction = new WalletTransaction(transaction);
this.walletTransactions.put(hash, walletTransaction);
return walletTransaction;
}
/**
* <ol>
* <li> the dialog put a pending transaction on the list
* <li> the dialog send the transaction to a net
* <li> wherever the transaction got in from the wire it will change to approve state
* <li> only after the approve a) Wallet state changes
* <li> after the block is received with that tx the pending been clean up
* </ol>
*/
public WalletTransaction addTransaction(Transaction transaction) {
String hash = Hex.toHexString(transaction.getHash());
logger.info("pending transaction placed hash: {}", hash);
WalletTransaction walletTransaction = this.walletTransactions.get(hash);
if (walletTransaction != null)
walletTransaction.incApproved();
else {
walletTransaction = new WalletTransaction(transaction);
this.walletTransactions.put(hash, walletTransaction);
}
this.applyTransaction(transaction);
return walletTransaction;
}
public void addTransactions(List<Transaction> transactions) {
for (Transaction transaction : transactions) {
this.addTransaction(transaction);
}
}
public void removeTransactions(List<Transaction> transactions) {
for (Transaction tx : transactions) {
if (logger.isDebugEnabled())
logger.debug("pending cleanup: tx.hash: [{}]", Hex.toHexString(tx.getHash()));
this.removeTransaction(tx);
}
}
public void removeTransaction(Transaction transaction) {
String hash = Hex.toHexString(transaction.getHash());
logger.info("pending transaction removed with hash: {} ", hash);
walletTransactions.remove(hash);
}
public void applyTransaction(Transaction transaction) {
transactionMap.put(new ByteArrayWrapper(transaction.getHash()), transaction);
byte[] senderAddress = transaction.getSender();
Account sender = rows.get(Hex.toHexString(senderAddress));
if (sender != null) {
sender.addPendingTransaction(transaction);
logger.info("Pending transaction added to " +
"\n account: [{}], " +
"\n tx: [{}]",
Hex.toHexString(sender.getAddress()), Hex.toHexString(transaction.getHash()));
}
byte[] receiveAddress = transaction.getReceiveAddress();
if (receiveAddress != null) {
Account receiver = rows.get(Hex.toHexString(receiveAddress));
if (receiver != null) {
receiver.addPendingTransaction(transaction);
logger.info("Pending transaction added to " +
"\n account: [{}], " +
"\n tx: [{}]",
Hex.toHexString(receiver.getAddress()), Hex.toHexString(transaction.getHash()));
}
}
this.notifyListeners();
}
public void processBlock(Block block) {
for (Account account : getAccountCollection()) {
account.clearAllPendingTransactions();
}
notifyListeners();
}
/**
* Load wallet file from the disk
*/
public void load() throws IOException, SAXException, ParserConfigurationException {
/**
<wallet high="8933">
<row id=1>
<address nonce="1" >7c63d6d8b6a4c1ec67766ae123637ca93c199935<address/>
<privkey>roman<privkey/>
<value>20000000<value/>
</row>
<row id=2>
<address nonce="6" >b5da3e0ba57da04f94793d1c334e476e7ce7b873<address/>
<privkey>cow<privkey/>
<value>900099909<value/>
</row>
</wallet>
*/
String dir = System.getProperty("user.dir");
String fileName = dir + "/wallet.xml";
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fileName);
Node walletNode = doc.getElementsByTagName("wallet").item(0);
String high = walletNode.getAttributes().getNamedItem("high").getTextContent();
this.setHigh(Long.parseLong(high));
NodeList rowNodes = walletNode.getChildNodes();
for (int i = 0; i < rowNodes.getLength(); ++i) {
Node rowNode = rowNodes.item(i);
Node addrNode = rowNode.getChildNodes().item(0);
Node privNode = rowNode.getChildNodes().item(1);
Node valueNode = rowNode.getChildNodes().item(2);
// TODO: complete load func
// byte[] privKey = Hex.decode(privNode.getTextContent());
// Address address = new Address(privKey);
// BigInteger value = new BigInteger(valueNode.getTextContent());
// this.importKey(privKey);
// this.setBalance(address, value);
}
}
/**
* Save wallet file to the disk
*/
public void save() throws ParserConfigurationException, ParserConfigurationException, TransformerException {
/**
<wallet high="8933">
<row id=1>
<address nonce="1" >7c63d6d8b6a4c1ec67766ae123637ca93c199935<address/>
<privkey>roman<privkey/>
<value>20000000<value/>
</row>
<row id=2>
<address nonce="6" >b5da3e0ba57da04f94793d1c334e476e7ce7b873<address/>
<privkey>cow<privkey/>
<value>900099909<value/>
</row>
</wallet>
*/
String dir = System.getProperty("user.dir");
String fileName = dir + "/wallet.xml";
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Element walletElement = doc.createElement("wallet");
doc.appendChild(walletElement);
Attr high = doc.createAttribute("high");
high.setValue(Long.toString(this.high));
walletElement.setAttributeNode(high);
int i = 0;
for (Account account : getAccountCollection()) {
Element raw = doc.createElement("raw");
Attr id = doc.createAttribute("id");
id.setValue(Integer.toString(i++));
raw.setAttributeNode(id);
Element addressE = doc.createElement("address");
addressE.setTextContent(Hex.toHexString(account.getEcKey().getAddress()));
Attr nonce = doc.createAttribute("nonce");
nonce.setValue("0");
addressE.setAttributeNode(nonce);
Element privKey = doc.createElement("privkey");
privKey.setTextContent(Hex.toHexString(account.getEcKey().getPrivKeyBytes()));
Element value = doc.createElement("value");
value.setTextContent(account.getBalance().toString());
raw.appendChild(addressE);
raw.appendChild(privKey);
raw.appendChild(value);
walletElement.appendChild(raw);
}
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(fileName));
// Output to console for testing
// StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);
}
private void notifyListeners() {
for (WalletListener listener : listeners)
listener.valueChanged();
}
public interface WalletListener {
public void valueChanged();
}
public BigInteger getBalance(byte[] addressBytes) {
String address = Hex.toHexString(addressBytes);
return rows.get(address).getBalance();
}
public long getHigh() {
return high;
}
public void setHigh(long high) {
this.high = high;
}
}
|
package org.ethereum.mine;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import org.apache.commons.lang3.tuple.Pair;
import org.ethereum.config.SystemProperties;
import org.ethereum.core.Block;
import org.ethereum.core.BlockHeader;
import org.ethereum.util.ByteUtil;
import org.ethereum.util.FastByteComparisons;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.concurrent.*;
import static org.ethereum.crypto.HashUtil.sha3;
import static org.ethereum.util.ByteUtil.longToBytes;
public class Ethash {
private static final Logger logger = LoggerFactory.getLogger("mine");
private static EthashParams ethashParams = new EthashParams();
private static Ethash cachedInstance = null;
private static long cachedBlockEpoch = 0;
// private static ExecutorService executor = Executors.newSingleThreadExecutor();
private static ListeningExecutorService executor = MoreExecutors.listeningDecorator(
new ThreadPoolExecutor(8, 8, 0L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()));
public static boolean fileCacheEnabled = true;
/**
* Returns instance for the specified block number either from cache or calculates a new one
*/
public static Ethash getForBlock(SystemProperties config, long blockNumber) {
long epoch = blockNumber / ethashParams.getEPOCH_LENGTH();
if (cachedInstance == null || epoch != cachedBlockEpoch) {
cachedInstance = new Ethash(config, epoch * ethashParams.getEPOCH_LENGTH());
cachedBlockEpoch = epoch;
}
return cachedInstance;
}
private EthashAlgo ethashAlgo = new EthashAlgo(ethashParams);
private long blockNumber;
private int[] cacheLight = null;
private int[] fullData = null;
private SystemProperties config;
public Ethash(SystemProperties config, long blockNumber) {
this.config = config;
this.blockNumber = blockNumber;
}
public synchronized int[] getCacheLight() {
if (cacheLight == null) {
File file = new File(config.databaseDir(), "mine-dag-light.dat");
if (fileCacheEnabled && file.canRead()) {
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {
logger.info("Loading light dataset from " + file.getAbsolutePath());
long bNum = ois.readLong();
if (bNum == blockNumber) {
cacheLight = (int[]) ois.readObject();
logger.info("Dataset loaded.");
} else {
logger.info("Dataset block number miss: " + bNum + " != " + blockNumber);
}
} catch (IOException | ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
if (cacheLight == null) {
logger.info("Calculating light dataset...");
cacheLight = getEthashAlgo().makeCache(getEthashAlgo().getParams().getCacheSize(blockNumber),
getEthashAlgo().getSeedHash(blockNumber));
logger.info("Light dataset calculated.");
if (fileCacheEnabled) {
file.getParentFile().mkdirs();
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file))){
logger.info("Writing light dataset to " + file.getAbsolutePath());
oos.writeLong(blockNumber);
oos.writeObject(cacheLight);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
return cacheLight;
}
public synchronized int[] getFullDataset() {
if (fullData == null) {
File file = new File(config.databaseDir(), "mine-dag.dat");
if (fileCacheEnabled && file.canRead()) {
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {
logger.info("Loading dataset from " + file.getAbsolutePath());
long bNum = ois.readLong();
if (bNum == blockNumber) {
fullData = (int[]) ois.readObject();
logger.info("Dataset loaded.");
} else {
logger.info("Dataset block number miss: " + bNum + " != " + blockNumber);
}
} catch (IOException | ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
if (fullData == null){
logger.info("Calculating full dataset...");
fullData = getEthashAlgo().calcDataset(getFullSize(), getCacheLight());
logger.info("Full dataset calculated.");
if (fileCacheEnabled) {
file.getParentFile().mkdirs();
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file))) {
logger.info("Writing dataset to " + file.getAbsolutePath());
oos.writeLong(blockNumber);
oos.writeObject(fullData);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
return fullData;
}
private long getFullSize() {
return getEthashAlgo().getParams().getFullSize(blockNumber);
}
private EthashAlgo getEthashAlgo() {
return ethashAlgo;
}
/**
* See {@link EthashAlgo#hashimotoLight}
*/
public Pair<byte[], byte[]> hashimotoLight(BlockHeader header, long nonce) {
return hashimotoLight(header, longToBytes(nonce));
}
private Pair<byte[], byte[]> hashimotoLight(BlockHeader header, byte[] nonce) {
return getEthashAlgo().hashimotoLight(getFullSize(), getCacheLight(),
sha3(header.getEncodedWithoutNonce()), nonce);
}
/**
* See {@link EthashAlgo#hashimotoFull}
*/
public Pair<byte[], byte[]> hashimotoFull(BlockHeader header, long nonce) {
return getEthashAlgo().hashimotoFull(getFullSize(), getFullDataset(), sha3(header.getEncodedWithoutNonce()),
longToBytes(nonce));
}
public ListenableFuture<Long> mine(final Block block) {
return mine(block, 1);
}
/**
* Mines the nonce for the specified Block with difficulty BlockHeader.getDifficulty()
* When mined the Block 'nonce' and 'mixHash' fields are updated
* Uses the full dataset i.e. it faster but takes > 1Gb of memory and may
* take up to 10 mins for starting up (depending on whether the dataset was cached)
*
* @param block The block to mine. The difficulty is taken from the block header
* This block is updated when mined
* @param nThreads CPU threads to mine on
* @return the task which may be cancelled. On success returns nonce
*/
public ListenableFuture<Long> mine(final Block block, int nThreads) {
return new MineTask(block, nThreads, new Callable<Long>() {
@Override
public Long call() throws Exception {
return getEthashAlgo().mine(getFullSize(), getFullDataset(),
sha3(block.getHeader().getEncodedWithoutNonce()),
ByteUtil.byteArrayToLong(block.getHeader().getDifficulty()));
}
}).submit();
}
public ListenableFuture<Long> mineLight(final Block block) {
return mineLight(block, 1);
}
/**
* Mines the nonce for the specified Block with difficulty BlockHeader.getDifficulty()
* When mined the Block 'nonce' and 'mixHash' fields are updated
* Uses the light cache i.e. it slower but takes only ~16Mb of memory and takes less
* time to start up
*
* @param block The block to mine. The difficulty is taken from the block header
* This block is updated when mined
* @param nThreads CPU threads to mine on
* @return the task which may be cancelled. On success returns nonce
*/
public ListenableFuture<Long> mineLight(final Block block, int nThreads) {
return new MineTask(block, nThreads, new Callable<Long>() {
@Override
public Long call() throws Exception {
return getEthashAlgo().mineLight(getFullSize(), getCacheLight(),
sha3(block.getHeader().getEncodedWithoutNonce()),
ByteUtil.byteArrayToLong(block.getHeader().getDifficulty()));
}
}).submit();
}
/**
* Validates the BlockHeader against its getDifficulty() and getNonce()
*/
public boolean validate(BlockHeader header) {
byte[] boundary = header.getPowBoundary();
byte[] hash = hashimotoLight(header, header.getNonce()).getRight();
return FastByteComparisons.compareTo(hash, 0, 32, boundary, 0, 32) < 0;
}
class MineTask extends AnyFuture<Long> {
Block block;
int nThreads;
Callable<Long> miner;
public MineTask(Block block, int nThreads, Callable<Long> miner) {
this.block = block;
this.nThreads = nThreads;
this.miner = miner;
}
public MineTask submit() {
for (int i = 0; i < nThreads; i++) {
ListenableFuture<Long> f = executor.submit(miner);
add(f);
}
return this;
}
@Override
protected void postProcess(Long nonce) {
Pair<byte[], byte[]> pair = hashimotoLight(block.getHeader(), nonce);
block.setNonce(longToBytes(nonce));
block.setMixHash(pair.getLeft());
}
}
}
|
package enc;
import static java.lang.System.out;
import java.io.IOException;
import java.util.Random;
import org.apache.parquet.bytes.HeapByteBufferAllocator;
import org.apache.parquet.column.values.delta.DeltaBinaryPackingValuesWriterForInteger;
import org.apache.parquet.column.values.plain.PlainValuesWriter;
public class GenerateNumberTestCases {
private static final HeapByteBufferAllocator A = new HeapByteBufferAllocator();
private static void printLine() {
out.println("===============================================\n");
}
private static void printBytes(byte[] bytes) {
out.print("{\ndata: []byte{");
for (byte b : bytes) {
out.printf("0x%02X, ", b);
}
out.println("},");
}
private static void genFloats() throws IOException {
PlainValuesWriter w = new PlainValuesWriter(10000, 10000, A);
float[] values = new float[] {/* Float.NaN, */ Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY, 0.0f, 1.0f, -1.0f};
for (float v: values) {
out.print(v + ", ");
w.writeFloat(v);
}
out.println();
printBytes(w.getBytes().toByteArray());
printLine();
}
private static void genDoubles() throws IOException {
PlainValuesWriter w = new PlainValuesWriter(10000, 10000, A);
double[] values = new double[] {Double.NaN, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, 0.0, 1.5, -1.25};
for (double v: values) {
out.print(v + ", ");
w.writeDouble(v);
}
out.println();
printBytes(w.getBytes().toByteArray());
printLine();
}
private static void genInt32s() throws IOException {
PlainValuesWriter w = new PlainValuesWriter(10000, 10000, A);
int[] values = new int[] {Integer.MIN_VALUE, Integer.MAX_VALUE, 0, -100, 234};
for (int v: values) {
out.print(v + ", ");
w.writeInteger(v);
}
out.println();
printBytes(w.getBytes().toByteArray());
printLine();
}
private static void genDeltaInt32s(int... values) throws IOException {
DeltaBinaryPackingValuesWriterForInteger w = new DeltaBinaryPackingValuesWriterForInteger(128, 8, 10000, 10000, A);
for (int v: values) {
w.writeInteger(v);
}
printBytes(w.getBytes().toByteArray());
out.print("decoded: []interface{} {");
for (int v: values) {
out.print("int32(" + v + "), ");
}
out.println("},\n},\n");
}
private static void genInt64s() throws IOException {
PlainValuesWriter w = new PlainValuesWriter(10000, 10000, A);
long[] values = new long[] {Long.MIN_VALUE, Long.MAX_VALUE, 0, -100, 234};
for (long v: values) {
out.print(v + ", ");
w.writeLong(v);
}
out.println();
printBytes(w.getBytes().toByteArray());
printLine();
}
public static int[] rangeInt(int s, int e) {
int[] r = new int[e-s+1];
for (int i = s; i <= e; i++) {
r[i-s] = i;
}
return r;
}
public static int[] randInts(int n) {
Random rnd = new Random(123);
int[] r = new int[n];
for (int i = 0; i < n; i++) {
r[i] = rnd.nextInt(40) + 100;
}
return r;
}
public static void main(String[] args) throws IOException {
genFloats();
genDoubles();
genInt32s();
genInt64s();
genDeltaInt32s(Integer.MIN_VALUE, Integer.MAX_VALUE, 0, -100, 234);
genDeltaInt32s(200_003, 200_001, 200_002, 200_003, 200_002, 200_001, 200_000);
genDeltaInt32s(rangeInt(1, 20));
genDeltaInt32s(randInts(200));
}
}
|
package com.liferay.lms;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import com.liferay.counter.service.CounterLocalServiceUtil;
import com.liferay.lms.course.diploma.CourseDiploma;
import com.liferay.lms.course.diploma.CourseDiplomaRegistry;
import com.liferay.lms.learningactivity.LearningActivityType;
import com.liferay.lms.learningactivity.LearningActivityTypeRegistry;
import com.liferay.lms.learningactivity.courseeval.CourseEval;
import com.liferay.lms.learningactivity.courseeval.CourseEvalRegistry;
import com.liferay.lms.model.AsynchronousProcessAudit;
import com.liferay.lms.model.Course;
import com.liferay.lms.model.CourseCompetence;
import com.liferay.lms.model.CourseType;
import com.liferay.lms.model.CourseTypeFactory;
import com.liferay.lms.model.CourseTypeI;
import com.liferay.lms.model.LearningActivity;
import com.liferay.lms.model.LmsPrefs;
import com.liferay.lms.model.Module;
import com.liferay.lms.model.impl.ModuleImpl;
import com.liferay.lms.service.AsynchronousProcessAuditLocalServiceUtil;
import com.liferay.lms.service.CourseCompetenceLocalServiceUtil;
import com.liferay.lms.service.CourseLocalServiceUtil;
import com.liferay.lms.service.CourseTypeLocalServiceUtil;
import com.liferay.lms.service.LearningActivityLocalServiceUtil;
import com.liferay.lms.service.LmsPrefsLocalServiceUtil;
import com.liferay.lms.service.ModuleLocalServiceUtil;
import com.liferay.lms.util.LmsConstant;
import com.liferay.portal.DuplicateGroupException;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.json.JSONFactoryUtil;
import com.liferay.portal.kernel.json.JSONObject;
import com.liferay.portal.kernel.language.LanguageUtil;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.messaging.Message;
import com.liferay.portal.kernel.messaging.MessageBusUtil;
import com.liferay.portal.kernel.messaging.MessageListener;
import com.liferay.portal.kernel.messaging.MessageListenerException;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.model.Group;
import com.liferay.portal.model.ResourceConstants;
import com.liferay.portal.model.ResourcePermission;
import com.liferay.portal.model.Role;
import com.liferay.portal.model.RoleConstants;
import com.liferay.portal.model.User;
import com.liferay.portal.security.auth.PrincipalThreadLocal;
import com.liferay.portal.security.permission.ActionKeys;
import com.liferay.portal.security.permission.PermissionChecker;
import com.liferay.portal.security.permission.PermissionCheckerFactoryUtil;
import com.liferay.portal.security.permission.PermissionThreadLocal;
import com.liferay.portal.service.GroupLocalServiceUtil;
import com.liferay.portal.service.ResourcePermissionLocalServiceUtil;
import com.liferay.portal.service.RoleLocalServiceUtil;
import com.liferay.portal.service.ServiceContext;
import com.liferay.portal.service.UserGroupRoleLocalServiceUtil;
import com.liferay.portal.service.UserLocalServiceUtil;
import com.liferay.portal.theme.ThemeDisplay;
import com.liferay.portal.util.PortalUtil;
import com.liferay.portlet.announcements.model.AnnouncementsEntry;
import com.liferay.portlet.announcements.model.AnnouncementsFlagConstants;
import com.liferay.portlet.announcements.service.AnnouncementsEntryServiceUtil;
import com.liferay.portlet.announcements.service.AnnouncementsFlagLocalServiceUtil;
import com.liferay.portlet.asset.model.AssetEntry;
import com.liferay.portlet.asset.service.AssetEntryLocalServiceUtil;
import com.liferay.portlet.documentlibrary.model.DLFolderConstants;
import com.liferay.portlet.expando.model.ExpandoBridge;
import com.liferay.portlet.messageboards.model.MBCategory;
import com.liferay.portlet.messageboards.service.MBCategoryLocalServiceUtil;
import com.liferay.util.CourseCopyUtil;
public class CloneCourse extends CourseCopyUtil implements MessageListener {
private static Log log = LogFactoryUtil.getLog(CloneCourse.class);
static String evalclassName="com.liferay.lms.learningactivity.courseeval.PonderatedCourseEval";
long groupId;
String newCourseName;
ThemeDisplay themeDisplay;
ServiceContext serviceContext;
Date startDate;
Date endDate;
Date startExecutionDate;
Date endExecutionDate;
boolean visible;
boolean includeTeacher;
AsynchronousProcessAudit process = null;
String statusMessage ="";
boolean error= false;
boolean cloneForum;
boolean cloneDocuments;
boolean cloneModuleClassification;
boolean cloneActivityClassificationTypes;
public CloneCourse(long groupId, String newCourseName, ThemeDisplay themeDisplay, Date startDate, Date endDate, boolean cloneForum, boolean cloneDocuments,
boolean cloneModuleClassification, boolean cloneActivityClassificationTypes, ServiceContext serviceContext) {
super();
this.groupId = groupId;
this.newCourseName = newCourseName;
this.themeDisplay = themeDisplay;
this.startDate = startDate;
this.endDate = endDate;
this.cloneForum = cloneForum;
this.cloneDocuments = cloneDocuments;
this.cloneModuleClassification = cloneModuleClassification;
this.cloneActivityClassificationTypes = cloneActivityClassificationTypes;
this.serviceContext = serviceContext;
}
public CloneCourse() {
}
@Override
public void receive(Message message) throws MessageListenerException {
try {
long processId = message.getLong("asynchronousProcessAuditId");
process = AsynchronousProcessAuditLocalServiceUtil.fetchAsynchronousProcessAudit(processId);
process = AsynchronousProcessAuditLocalServiceUtil.updateProcessStatus(process, null, LmsConstant.STATUS_IN_PROGRESS, "");
statusMessage ="";
error = false;
this.groupId = message.getLong("groupId");
this.newCourseName = message.getString("newCourseName");
this.startDate = (Date)message.get("startDate");
this.endDate = (Date)message.get("endDate");
this.startExecutionDate = (Date) message.get("startExecutionDate");
this.endExecutionDate = (Date) message.get("endExecutionDate");
this.serviceContext = (ServiceContext)message.get("serviceContext");
this.themeDisplay = (ThemeDisplay)message.get("themeDisplay");
this.visible = message.getBoolean("visible");
this.includeTeacher = message.getBoolean("includeTeacher");
this.cloneForum = message.getBoolean("cloneForum");
this.cloneDocuments = message.getBoolean("cloneDocuments");
this.cloneModuleClassification = message.getBoolean("cloneModuleClassification");
this.cloneActivityClassificationTypes = message.getBoolean("cloneActivityClassificationTypes");
Role adminRole = RoleLocalServiceUtil.getRole(themeDisplay.getCompanyId(),"Administrator");
List<User> adminUsers = UserLocalServiceUtil.getRoleUsers(adminRole.getRoleId());
PrincipalThreadLocal.setName(adminUsers.get(0).getUserId());
PermissionChecker permissionChecker =PermissionCheckerFactoryUtil.create(adminUsers.get(0), true);
PermissionThreadLocal.setPermissionChecker(permissionChecker);
doCloneCourse();
} catch (Exception e) {
e.printStackTrace();
}
}
public void doCloneCourse() throws Exception {
log.debug("Course to clone\n........................." + groupId);
Group group = GroupLocalServiceUtil.fetchGroup(groupId);
Course course = CourseLocalServiceUtil.fetchByGroupCreatedId(groupId);
if(log.isDebugEnabled()){
log.debug("Course to clone\n.........................");
log.debug(" + groupId: "+groupId);
log.debug(" + course: "+course.getTitle(themeDisplay.getLocale()));
}
Date today=new Date(System.currentTimeMillis());
String courseTemplate = this.serviceContext.getRequest().getParameter("courseTemplate");
long layoutSetPrototypeId = 0;
if(courseTemplate.indexOf("&")>-1){
layoutSetPrototypeId = Long.parseLong(courseTemplate.split("&")[1]);
}else{
layoutSetPrototypeId = Long.parseLong(courseTemplate);
}
if(log.isDebugEnabled()){
log.debug(" + layoutSetPrototypeId: "+layoutSetPrototypeId);
}
try{
log.debug(" + AssetCategoryIds: "+AssetEntryLocalServiceUtil.getEntry(Course.class.getName(), course.getCourseId()).getCategoryIds().toString());
log.debug(" + AssetCategoryIds Service Context: "+serviceContext.getAssetCategoryIds());
log.debug(" + AssetTagNames: "+AssetEntryLocalServiceUtil.getEntry(Course.class.getName(), course.getCourseId()).getTagNames());
log.debug(" + AssetTagNames Service Context: "+serviceContext.getAssetTagNames());
serviceContext.setAssetCategoryIds(AssetEntryLocalServiceUtil.getEntry(Course.class.getName(), course.getCourseId()).getCategoryIds());
serviceContext.setAssetTagNames(AssetEntryLocalServiceUtil.getEntry(Course.class.getName(), course.getCourseId()).getTagNames());
AssetEntryLocalServiceUtil.validate(course.getGroupCreatedId(), Course.class.getName(), serviceContext.getAssetCategoryIds(), serviceContext.getAssetTagNames());
}catch(Exception e){
serviceContext.setAssetCategoryIds(new long[]{});
//serviceContext.setAssetTagNames(AssetEntryLocalServiceUtil.getEntry(Course.class.getName(), course.getCourseId()).getTags());
}
//Course newCourse = CourseLocalServiceUtil.addCourse(newCourseName, course.getDescription(), "", themeDisplay.getLocale() , today, startDate, endDate, serviceContext, course.getCalificationType());
//when lmsprefs has more than one lmstemplate selected the addcourse above throws an error.
int typeSite = GroupLocalServiceUtil.getGroup(course.getGroupCreatedId()).getType();
Course newCourse = null;
String summary = null;
long courseTypeId = 0;
try{
AssetEntry entry = AssetEntryLocalServiceUtil.getEntry(Course.class.getName(), course.getCourseId());
summary = entry.getSummary(themeDisplay.getLocale());
courseTypeId = entry.getClassTypeId();
newCourse = CourseLocalServiceUtil.addCourse(newCourseName, course.getDescription(themeDisplay.getLocale()),summary
, "", themeDisplay.getLocale(), today, startDate, endDate, layoutSetPrototypeId, typeSite, serviceContext, course.getCalificationType(), (int)course.getMaxusers(),true);
newCourse.setWelcome(course.getWelcome());
newCourse.setWelcomeMsg(course.getWelcomeMsg());
newCourse.setWelcomeSubject(course.getWelcomeSubject());
newCourse.setDeniedInscription(course.isDeniedInscription());
newCourse.setDeniedInscriptionSubject(course.getDeniedInscriptionSubject());
newCourse.setDeniedInscriptionMsg(course.getDeniedInscriptionMsg());
newCourse.setGoodbye(course.getGoodbye());
newCourse.setGoodbyeMsg(course.getGoodbyeMsg());
newCourse.setGoodbyeSubject(course.getGoodbyeSubject());
newCourse.setCourseEvalId(course.getCourseEvalId());
newCourse.setStartDate(startDate);
newCourse.setEndDate(endDate);
newCourse.setExecutionStartDate(startExecutionDate);
newCourse.setExecutionEndDate(endExecutionDate);
StringBuilder extraContent = new StringBuilder();
Course parentcourse = null;
try {
parentcourse = course.getParentCourse();
} catch (SystemException | PortalException e) {
log.debug("Parent course not found");
}
if(Validator.isNotNull(parentcourse) ) {
extraContent.append(LanguageUtil.get(themeDisplay.getLocale(), "course-admin.parent-course"))
.append(StringPool.COLON).append(StringPool.SPACE)
.append(course.getParentCourse().getTitle(themeDisplay.getLocale())).append("<br>");
}
extraContent.append(LanguageUtil.get(themeDisplay.getLocale(), "course.label"))
.append(StringPool.COLON).append(StringPool.SPACE)
.append(course.getTitle(themeDisplay.getLocale()));
extraContent.append("<br>").append(LanguageUtil.get(themeDisplay.getLocale(), "new-course"))
.append(StringPool.COLON).append(StringPool.SPACE)
.append(newCourse.getTitle(themeDisplay.getLocale()));
JSONObject json =JSONFactoryUtil.createJSONObject();
json.put("data", extraContent.toString());
process.setExtraContent(json.toString());
process.setClassPK(newCourse.getCourseId());
process = AsynchronousProcessAuditLocalServiceUtil.updateAsynchronousProcessAudit(process);
} catch(DuplicateGroupException e){
if(log.isDebugEnabled())e.printStackTrace();
process = AsynchronousProcessAuditLocalServiceUtil.updateProcessStatus(process, new Date(), LmsConstant.STATUS_ERROR, e.getMessage());
throw new DuplicateGroupException();
}
copyExpandos (newCourse, course, serviceContext);
List<CourseCompetence> courseCompetences= CourseCompetenceLocalServiceUtil.findBycourseId(course.getCourseId(), false);
for(CourseCompetence courseCompetence:courseCompetences)
{
long courseCompetenceId = CounterLocalServiceUtil.increment(CourseCompetence.class.getName());
CourseCompetence cc = CourseCompetenceLocalServiceUtil.createCourseCompetence(courseCompetenceId);
cc.setCourseId(newCourse.getCourseId());
cc.setCompetenceId(courseCompetence.getCompetenceId());
cc.setCachedModel(courseCompetence.getCondition());
cc.setCondition(courseCompetence.getCondition());
CourseCompetenceLocalServiceUtil.updateCourseCompetence(cc, true);
}
courseCompetences= CourseCompetenceLocalServiceUtil.findBycourseId(course.getCourseId(), true);
CourseCompetence cc=null;
for(CourseCompetence courseCompetence:courseCompetences){
long courseCompetenceId = CounterLocalServiceUtil.increment(CourseCompetence.class.getName());
cc = CourseCompetenceLocalServiceUtil.createCourseCompetence(courseCompetenceId);
cc.setCourseId(newCourse.getCourseId());
cc.setCompetenceId(courseCompetence.getCompetenceId());
cc.setCachedModel(courseCompetence.getCondition());
cc.setCondition(courseCompetence.getCondition());
CourseCompetenceLocalServiceUtil.updateCourseCompetence(cc, true);
}
Group newGroup = GroupLocalServiceUtil.getGroup(newCourse.getGroupCreatedId());
serviceContext.setScopeGroupId(newCourse.getGroupCreatedId());
newCourse.setParentCourseId(course.getParentCourseId());
Role siteMemberRole = RoleLocalServiceUtil.getRole(themeDisplay.getCompanyId(), RoleConstants.SITE_MEMBER);
newCourse.setIcon(course.getIcon());
try{
newCourse = CourseLocalServiceUtil.modCourse(newCourse, summary, courseTypeId, serviceContext, visible);
AssetEntry newEntry = AssetEntryLocalServiceUtil.getEntry(Course.class.getName(),newCourse.getCourseId());
newEntry.setVisible(visible);
newEntry.setSummary(summary);
newEntry.setClassTypeId(courseTypeId);
AssetEntryLocalServiceUtil.updateAssetEntry(newEntry);
newGroup.setName(newCourse.getTitle(themeDisplay.getLocale(), true));
newGroup.setDescription(summary);
GroupLocalServiceUtil.updateGroup(newGroup);
}catch(Exception e){
if(log.isDebugEnabled())e.printStackTrace();
error=true;
statusMessage += e.getMessage() + "\n";
}
newCourse.setUserId(themeDisplay.getUserId());
if(log.isDebugEnabled()){
log.debug("
log.debug(" + to course: "+ newCourse.getTitle(Locale.getDefault()) +", GroupCreatedId: "+newCourse.getGroupCreatedId()+", GroupId: "+newCourse.getGroupId());
}
//Update especific content of diploma (if exists)
CourseDiplomaRegistry cdr = new CourseDiplomaRegistry();
if(cdr!=null){
CourseDiploma courseDiploma = cdr.getCourseDiploma();
if(courseDiploma!=null){
String courseDiplomaError = courseDiploma.copyCourseDiploma(course.getCourseId(), newCourse.getCourseId());
log.debug("****CourseDiplomaError:"+courseDiplomaError);
if(Validator.isNotNull(courseDiplomaError)){
statusMessage += courseDiplomaError + "\n";
error = true;
}
}
}
/**
* METO AL USUARIO CREADOR DEL CURSO COMO PROFESOR
*/
if(includeTeacher){
log.debug(includeTeacher);
LmsPrefs lmsPrefs=LmsPrefsLocalServiceUtil.getLmsPrefs(themeDisplay.getCompanyId());
long teacherRoleId=RoleLocalServiceUtil.getRole(lmsPrefs.getEditorRole()).getRoleId();
UserGroupRoleLocalServiceUtil.addUserGroupRoles(new long[] { themeDisplay.getUserId() }, newCourse.getGroupCreatedId(), teacherRoleId);
if (!GroupLocalServiceUtil.hasUserGroup(themeDisplay.getUserId(), newCourse.getGroupCreatedId())) {
GroupLocalServiceUtil.addUserGroups(themeDisplay.getUserId(), new long[] { newCourse.getGroupCreatedId() });
}
}
CourseLocalServiceUtil.copyModulesAndActivities(themeDisplay.getUserId(), course, newCourse, this.cloneActivityClassificationTypes, true, serviceContext);
CourseEvalRegistry registry = new CourseEvalRegistry();
CourseEval courseEval = registry.getCourseEval(course.getCourseEvalId());
courseEval.cloneCourseEval(course, newCourse);
CourseTypeFactoryRegistry courseTypeFactoryRegistry = new CourseTypeFactoryRegistry();
AssetEntry entry=AssetEntryLocalServiceUtil.getEntry(Course.class.getName(),newCourse.getCourseId());
if(entry.getClassTypeId() > 0){
CourseType courseType = CourseTypeLocalServiceUtil.getCourseType(entry.getClassTypeId());
if(courseType.getClassNameId() > 0){
CourseTypeFactory courseTypeFactory = courseTypeFactoryRegistry.getCourseTypeFactory(courseType.getClassNameId());
if(courseTypeFactory != null){
CourseTypeI courseTypeI = courseTypeFactory.getCourseType(newCourse);
courseTypeI.copyCourse(course, serviceContext);
}
}
}
if(this.cloneForum){
//Categorias y subcategorias del foro
List<MBCategory> listCategories = MBCategoryLocalServiceUtil.getCategories(groupId);
//Si existen las categorias se clonan
if(listCategories!=null && listCategories.size()>0){
if(log.isDebugEnabled()){
log.debug("
}
long newCourseGroupId = newCourse.getGroupCreatedId();//Para asociar las categorias creadas con el nuevo curso
boolean resultCloneForo = cloneForo(newCourseGroupId, listCategories);
if(log.isDebugEnabled()){
log.debug("
}
}
}
if(this.cloneDocuments){
if(log.isDebugEnabled())
log.debug(":: Clone course :: Clone docs ::");
long newCourseGroupId = newCourse.getGroupCreatedId();
long repositoryId = DLFolderConstants.getDataRepositoryId(groupId, DLFolderConstants.DEFAULT_PARENT_FOLDER_ID);
long newRepositoryId = DLFolderConstants.getDataRepositoryId(newCourseGroupId, DLFolderConstants.DEFAULT_PARENT_FOLDER_ID);
duplicateFoldersAndFileEntriesInsideFolder(Boolean.TRUE, themeDisplay.getUserId(), typeSite, themeDisplay.getCompanyId(), DLFolderConstants.DEFAULT_PARENT_FOLDER_ID, repositoryId, newCourseGroupId, DLFolderConstants.DEFAULT_PARENT_FOLDER_ID, newRepositoryId, serviceContext);
}
if(log.isDebugEnabled()){
log.debug(" ENDS!");
}
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss");
dateFormat.setTimeZone(themeDisplay.getTimeZone());
String[] args = {newCourse.getTitle(themeDisplay.getLocale()), dateFormat.format(startDate), dateFormat.format(endDate)};
sendNotification(LanguageUtil.get(themeDisplay.getLocale(),"courseadmin.clone.confirmation.title"), LanguageUtil.format(themeDisplay.getLocale(),"courseadmin.clone.confirmation.message", args), themeDisplay.getPortalURL()+"/web/"+newGroup.getFriendlyURL(), "Avisos", 1);
Date endDate = new Date();
if(!error){
AsynchronousProcessAuditLocalServiceUtil.updateProcessStatus(process, endDate, LmsConstant.STATUS_FINISH, "asynchronous-proccess-audit.status-ok");
}else{
AsynchronousProcessAuditLocalServiceUtil.updateProcessStatus(process, endDate, LmsConstant.STATUS_ERROR, statusMessage);
}
log.debug("Enviando mensaje liferay/lms/courseClonePostAction con newCourseId "+newCourse.getCourseId() + " y originCourseId "+course.getCourseId());
Message postActionMessage=new Message();
postActionMessage.put("originCourseId", course.getCourseId());
postActionMessage.put("newCourseId", newCourse.getCourseId());
MessageBusUtil.sendMessage("liferay/lms/courseClonePostAction", postActionMessage);
}
private void sendNotification(String title, String content, String url, String type, int priority){
//ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
SimpleDateFormat formatDay = new SimpleDateFormat("dd");
formatDay.setTimeZone(themeDisplay.getTimeZone());
SimpleDateFormat formatMonth = new SimpleDateFormat("MM");
formatMonth.setTimeZone(themeDisplay.getTimeZone());
SimpleDateFormat formatYear = new SimpleDateFormat("yyyy");
formatYear.setTimeZone(themeDisplay.getTimeZone());
SimpleDateFormat formatHour = new SimpleDateFormat("HH");
formatHour.setTimeZone(themeDisplay.getTimeZone());
SimpleDateFormat formatMin = new SimpleDateFormat("mm");
formatMin.setTimeZone(themeDisplay.getTimeZone());
Date today=new Date(System.currentTimeMillis());
int displayDateDay=Integer.parseInt(formatDay.format(today));
int displayDateMonth=Integer.parseInt(formatMonth.format(today))-1;
int displayDateYear=Integer.parseInt(formatYear.format(today));
int displayDateHour=Integer.parseInt(formatHour.format(today));
int displayDateMinute=Integer.parseInt(formatMin.format(today));
int expirationDateDay=Integer.parseInt(formatDay.format(today));
int expirationDateMonth=Integer.parseInt(formatMonth.format(today))-1;
int expirationDateYear=Integer.parseInt(formatYear.format(today))+1;
int expirationDateHour=Integer.parseInt(formatHour.format(today));
int expirationDateMinute=Integer.parseInt(formatMin.format(today));
long classNameId=PortalUtil.getClassNameId(User.class.getName());
long classPK=themeDisplay.getUserId();
AnnouncementsEntry ae;
try {
ae = AnnouncementsEntryServiceUtil.addEntry(
themeDisplay.getPlid(), classNameId, classPK, title, content, url, type,
displayDateMonth, displayDateDay, displayDateYear, displayDateHour, displayDateMinute,
expirationDateMonth, expirationDateDay, expirationDateYear, expirationDateHour, expirationDateMinute,
priority, false);
AnnouncementsFlagLocalServiceUtil.addFlag(classPK,ae.getEntryId(),AnnouncementsFlagConstants.UNREAD);
} catch (PortalException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SystemException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Clona las categorias/subcategorias/subsubcategorias... del foro
* @param newCourseGroupId: groupId del curso clonado
* @param listCategories: lista de categorias del foro del curso
*
* @return: boolean = true -> Se realiza correctamente
* boolean = false -> Se ha producido algun error durante el proceso
*/
private boolean cloneForo(long newCourseGroupId, List<MBCategory> listCategories){
boolean resultCloneForo = true;
List<MBCategory> listParentCat = new ArrayList<MBCategory>();
List<MBCategory> listSubCat = new ArrayList<MBCategory>();
long parentCategoryId = 0;
for(MBCategory category:listCategories){
if(0 == category.getParentCategoryId()) listParentCat.add(category);
else listSubCat.add(category);
}
resultCloneForo = subCategories(parentCategoryId, newCourseGroupId, listParentCat, listSubCat);
return resultCloneForo;
}
/**
*
* Funcion recursiva que clona las categorias del foro y busca si cada categoria tiene una subcategoria para
* volver a realizar la misma operacion
*
* @param parentCategoryId: Id de la categoria padre (la clonada)
* @param newCourseGroupId: Id del curso clonado
* @param listParentCat
* @param listSubCat
* @return: boolean = true -> Si se realiza el proceso correctamente
* boolean = false -> Si se produce algun error durante el proceso
*/
private boolean subCategories(long parentCategoryId, long newCourseGroupId, List<MBCategory> listParentCat, List<MBCategory> listSubCat){
if(log.isDebugEnabled()){
log.debug("
}
boolean result = true;
long newParentCategoryId;
MBCategory newCourseCategory = null;
List<MBCategory> listSubSubCat= new ArrayList<MBCategory>();
List<MBCategory> listParentSubCat= new ArrayList<MBCategory>();
for(MBCategory category:listParentCat){
newCourseCategory = createNewCategory(newCourseGroupId, category, parentCategoryId);
if (newCourseCategory==null) return false;
newParentCategoryId = newCourseCategory.getCategoryId();
if(listSubCat.size()>0) {
listParentSubCat = new ArrayList<MBCategory>();
listSubSubCat = new ArrayList<MBCategory>();
for(MBCategory subCategory:listSubCat) {
if(category.getCategoryId() == subCategory.getParentCategoryId()) listParentSubCat.add(subCategory);
else listSubSubCat.add(subCategory);
}
if(listParentSubCat.size()>0){//Si encuentro subcategorias de esta categoria vuelvo a llamar a esta misma funcion
result = subCategories(newParentCategoryId, newCourseGroupId, listParentSubCat, listSubSubCat);
if(!result) return result;
}
}
}
return result;
}
/**
*
* Crea una categoria del foro
*
* @param newCourseGroupId: Id del curso clonado
* @param category: Datos de la categoria que se quiere clonar
* @param parentCategoryId: Id de la categoria de la que depende esta categoria (parentCategoryId=0 si no depende de ninguna categoria, y si tiene
* dependencia, parentCategoryId = categoryId de la categoria de la que depende)
* @return null -> en caso de que se produzca algun error
* Objeto MBCategory creado en caso de que la operacion se realice correctamente
*/
private MBCategory createNewCategory(long newCourseGroupId, MBCategory category, long parentCategoryId) {
log.debug("
MBCategory newCourseCategory = null;
try {
newCourseCategory = MBCategoryLocalServiceUtil.createMBCategory(CounterLocalServiceUtil.increment(MBCategory.class.getName()));
newCourseCategory.setGroupId(newCourseGroupId);
newCourseCategory.setCompanyId(category.getCompanyId());
newCourseCategory.setName(category.getName());
newCourseCategory.setDescription(category.getDescription());
newCourseCategory.setCreateDate(Calendar.getInstance().getTime());
newCourseCategory.setModifiedDate(Calendar.getInstance().getTime());
newCourseCategory.setDisplayStyle(category.getDisplayStyle());
newCourseCategory.setUserId(themeDisplay.getUserId());
newCourseCategory.setUserName(themeDisplay.getUser().getFullName());
newCourseCategory.setParentCategoryId(parentCategoryId);
newCourseCategory = MBCategoryLocalServiceUtil.addMBCategory(newCourseCategory);
// Copiar permisos de la categoria antigua en la nueva
List<ResourcePermission> resourcePermissionList = new ArrayList<ResourcePermission>();
ResourcePermission rpNew = null;
long resourcePermissionId = 0;
int [] scopeIds = ResourceConstants.SCOPES;
for(int scope : scopeIds) {
resourcePermissionList = ResourcePermissionLocalServiceUtil.getResourcePermissions(category.getCompanyId(), MBCategory.class.getName(), scope, String.valueOf(category.getPrimaryKey()));
for(ResourcePermission resourcePermission : resourcePermissionList) {
resourcePermissionId = CounterLocalServiceUtil.increment(ResourcePermission.class.getName());
rpNew = ResourcePermissionLocalServiceUtil.createResourcePermission(resourcePermissionId);
rpNew.setActionIds(resourcePermission.getActionIds());
rpNew.setCompanyId(resourcePermission.getCompanyId());
rpNew.setName(resourcePermission.getName());
rpNew.setRoleId(resourcePermission.getRoleId());
rpNew.setScope(resourcePermission.getScope());
rpNew.setPrimKey(String.valueOf(newCourseCategory.getCategoryId()));
rpNew.setOwnerId(resourcePermission.getOwnerId());
rpNew = ResourcePermissionLocalServiceUtil.updateResourcePermission(rpNew);
}
}
return newCourseCategory;
} catch (SystemException e) {
log.error(e.getMessage());
return null;
}
}
}
|
package ru.revdaalex.oodsrp;
import org.junit.Assert;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
public class InteractCalcTest {
/**
* Test add.
*/
@Test
public void whenTakeSumAndExit(){
MockIO mockIO = new MockIO(new String[]{"1", "1", "1", "7"});
Calculator calculator = new Calculator();
new InteractCalc(calculator, mockIO).start();
Assert.assertThat(calculator.getResult(), is(2.0));
}
/**
* Test subtraction.
*/
@Test
public void whenTakeSubAndExit(){
MockIO mockIO = new MockIO(new String[]{"2", "10", "5", "7"});
Calculator calculator = new Calculator();
new InteractCalc(calculator, mockIO).start();
Assert.assertThat(calculator.getResult(), is(5.0));
}
/**
* Test multiplication.
*/
@Test
public void whenTakeMultAndExit(){
MockIO mockIO = new MockIO(new String[]{"3", "10", "2", "7"});
Calculator calculator = new Calculator();
new InteractCalc(calculator, mockIO).start();
Assert.assertThat(calculator.getResult(), is(20.0));
}
/**
* Test division.
*/
@Test
public void whenTakeDivAndExit(){
MockIO mockIO = new MockIO(new String[]{"4", "10", "5", "7"});
Calculator calculator = new Calculator();
new InteractCalc(calculator, mockIO).start();
Assert.assertThat(calculator.getResult(), is(2.0));
}
/**
* Test add and addition reuse result.
*/
@Test
public void whenTakeSumAndSumReuseResultThenExit(){
MockIO mockIO = new MockIO(new String[]{"1", "10", "5", "5", "5", "1", "7"});
Calculator calculator = new Calculator();
new InteractCalc(calculator, mockIO).start();
Assert.assertThat(calculator.getResult(), is(20.0));
}
/**
* Test clear result.
*/
@Test
public void whenTakeSumThenClearResultAndExit(){
MockIO mockIO = new MockIO(new String[]{"1", "100", "30", "6", "7"});
Calculator calculator = new Calculator();
new InteractCalc(calculator, mockIO).start();
Assert.assertThat(calculator.getResult(), is(0.0));
}
}
|
package edu.umd.cs.findbugs.ba;
import java.util.*;
import org.apache.bcel.Constants;
import org.apache.bcel.classfile.*;
import org.apache.bcel.generic.*;
/**
* A forward dataflow analysis to determine the types of all values
* in the Java stack frame at all points in a Java method.
* The values include local variables and values on the Java operand stack.
*
* <p> As a side effect, the analysis computes the exception
* set throwable on each exception edge in the CFG.
* This information can be used to prune infeasible exception
* edges, and mark exception edges which propagate only
* implicit exceptions.
*
* @see Dataflow
* @see DataflowAnalysis
* @see TypeFrame
* @author David Hovemeyer
*/
public class TypeAnalysis extends FrameDataflowAnalysis<Type, TypeFrame> {
private static final boolean DEBUG = Boolean.getBoolean("ta.debug");
private static class CachedExceptionSet {
private TypeFrame result;
private ExceptionSet exceptionSet;
public CachedExceptionSet(TypeFrame result, ExceptionSet exceptionSet) {
this.result = result;
this.exceptionSet = exceptionSet;
}
public boolean isUpToDate(TypeFrame result) {
return this.result.equals(result);
}
public ExceptionSet getExceptionSet() {
return exceptionSet;
}
}
private MethodGen methodGen;
private TypeMerger typeMerger;
private TypeFrameModelingVisitor visitor;
private Map<BasicBlock, CachedExceptionSet> exceptionSetMap;
private RepositoryLookupFailureCallback lookupFailureCallback;
/**
* Constructor.
* @param methodGen the MethodGen whose CFG we'll be analyzing
* @param dfs DepthFirstSearch of the method
* @param typeMerger object to merge types
* @param visitor a TypeFrameModelingVisitor to use to model the effect
* of instructions
* @param lookupFailureCallback lookup failure callback
*/
public TypeAnalysis(MethodGen methodGen, DepthFirstSearch dfs, TypeMerger typeMerger, TypeFrameModelingVisitor visitor,
RepositoryLookupFailureCallback lookupFailureCallback) {
super(dfs);
this.methodGen = methodGen;
this.typeMerger = typeMerger;
this.visitor = visitor;
this.lookupFailureCallback = lookupFailureCallback;
this.exceptionSetMap = new HashMap<BasicBlock, CachedExceptionSet>();
}
/**
* Constructor.
* @param methodGen the MethodGen whose CFG we'll be analyzing
* @param dfs DepthFirstSearch of the method
* @param typeMerger object to merge types
* @param lookupFailureCallback lookup failure callback
*/
public TypeAnalysis(MethodGen methodGen, DepthFirstSearch dfs, TypeMerger typeMerger,
RepositoryLookupFailureCallback lookupFailureCallback) {
this(methodGen, dfs, typeMerger, new TypeFrameModelingVisitor(methodGen.getConstantPool()), lookupFailureCallback);
}
/**
* Constructor which uses StandardTypeMerger.
* @param methodGen the MethodGen whose CFG we'll be analyzing
* @param dfs DepthFirstSearch of the method
* @param lookupFailureCallback callback for Repository lookup failures
*/
public TypeAnalysis(MethodGen methodGen, DepthFirstSearch dfs, RepositoryLookupFailureCallback lookupFailureCallback) {
this(methodGen, dfs, new StandardTypeMerger(lookupFailureCallback), lookupFailureCallback);
}
public TypeFrame createFact() {
return new TypeFrame(methodGen.getMaxLocals(), typeMerger);
}
public void initEntryFact(TypeFrame result) {
// Make the frame valid
result.setValid();
int slot = 0;
// Clear the stack slots in the frame
result.clearStack();
// Add local for "this" pointer, if present
if (!methodGen.isStatic())
result.setValue(slot++, new ObjectType(methodGen.getClassName()));
// Add locals for parameters.
// Note that long and double parameters need to be handled
// specially because they occupy two locals.
Type[] argumentTypes = methodGen.getArgumentTypes();
for (int i = 0; i < argumentTypes.length; ++i) {
Type argType = argumentTypes[i];
// Add special "extra" type for long or double params.
// These occupy the slot before the "plain" type.
if (argType.getType() == Constants.T_LONG) {
result.setValue(slot++, TypeFrame.getLongExtraType());
} else if (argType.getType() == Constants.T_DOUBLE) {
result.setValue(slot++, TypeFrame.getDoubleExtraType());
}
// Add the plain parameter type.
result.setValue(slot++, argType);
}
// Set remaining locals to BOTTOM; this will cause any
// uses of them to be flagged
while (slot < methodGen.getMaxLocals())
result.setValue(slot++, TypeFrame.getBottomType());
}
public void copy(TypeFrame source, TypeFrame dest) {
dest.copyFrom(source);
}
public void initResultFact(TypeFrame result) {
// This is important. Sometimes we need to use a result value
// before having a chance to initialize it. We don't want such
// values to corrupt other TypeFrame values that we merge them with.
// So, all result values must be TOP.
result.setTop();
}
public void makeFactTop(TypeFrame fact) {
fact.setTop();
}
public boolean isFactValid(TypeFrame fact) {
return fact.isValid();
}
public boolean same(TypeFrame fact1, TypeFrame fact2) {
return fact1.sameAs(fact2);
}
public void transferInstruction(InstructionHandle handle, BasicBlock basicBlock, TypeFrame fact)
throws DataflowAnalysisException {
visitor.setFrame(fact);
handle.getInstruction().accept(visitor);
}
public void endTransfer(BasicBlock basicBlock, InstructionHandle end, Object result) throws DataflowAnalysisException {
// Figure out what exceptions can be thrown out
// of the basic block. That way, we'll remember
// exactly what kinds of exceptions can
// be caught later on.
if (basicBlock.isExceptionThrower()) {
try {
computeExceptionTypes(basicBlock, (TypeFrame) result);
} catch (ClassNotFoundException e) {
lookupFailureCallback.reportMissingClass(e);
throw new DataflowAnalysisException("Could not enumerate exception types for block", e);
}
}
}
public void meetInto(TypeFrame fact, Edge edge, TypeFrame result) throws DataflowAnalysisException {
BasicBlock basicBlock = edge.getTarget();
if (basicBlock.isExceptionHandler() && fact.isValid()) {
// Special case: when merging predecessor facts for entry to
// an exception handler, we clear the stack and push a
// single entry for the exception object. That way, the locals
// can still be merged.
CodeExceptionGen exceptionGen = basicBlock.getExceptionGen();
TypeFrame tmpFact = createFact();
tmpFact.copyFrom(fact);
tmpFact.clearStack();
Type catchType = exceptionGen.getCatchType();
if (catchType == null)
catchType = Type.THROWABLE; // handle catches anything throwable
tmpFact.pushValue(catchType);
fact = tmpFact;
}
result.mergeWith(fact);
}
public static void main(String[] argv) throws Exception {
if (argv.length != 1) {
System.err.println("Usage: " + TypeAnalysis.class.getName() + " <class file>");
System.exit(1);
}
DataflowTestDriver<TypeFrame, TypeAnalysis> driver = new DataflowTestDriver<TypeFrame, TypeAnalysis>() {
public Dataflow<TypeFrame, TypeAnalysis> createDataflow(ClassContext classContext, Method method)
throws CFGBuilderException, DataflowAnalysisException {
return classContext.getTypeDataflow(method);
}
};
driver.execute(argv[0]);
}
private CachedExceptionSet getCachedExceptionSet(BasicBlock basicBlock) {
CachedExceptionSet cachedExceptionSet = exceptionSetMap.get(basicBlock);
if (cachedExceptionSet == null) {
// When creating the cached exception type set for the first time:
// - the block result is set to TOP, so it won't match
// any block result that has actually been computed
// using the analysis transfer function
// - the exception set is created as empty (which makes it
// return TOP as its common superclass)
TypeFrame top = createFact();
makeFactTop(top);
cachedExceptionSet = new CachedExceptionSet(top, new ExceptionSet());
exceptionSetMap.put(basicBlock, cachedExceptionSet);
}
return cachedExceptionSet;
}
private void computeExceptionTypes(BasicBlock basicBlock, TypeFrame result)
throws ClassNotFoundException, DataflowAnalysisException {
CachedExceptionSet cachedExceptionSet = getCachedExceptionSet(basicBlock);
if (cachedExceptionSet.isUpToDate(result))
return;
ExceptionSet exceptionSet = enumerateExceptionTypes(basicBlock);
TypeFrame copyOfResult = createFact();
copy(result, copyOfResult);
cachedExceptionSet = new CachedExceptionSet(copyOfResult, exceptionSet);
exceptionSetMap.put(basicBlock, cachedExceptionSet);
}
private ExceptionSet enumerateExceptionTypes(BasicBlock basicBlock)
throws ClassNotFoundException, DataflowAnalysisException {
ExceptionSet exceptionTypeSet = new ExceptionSet();
InstructionHandle pei = basicBlock.getExceptionThrower();
Instruction ins = pei.getInstruction();
// Get the exceptions that BCEL knows about.
// Note that all of these are unchecked.
ExceptionThrower exceptionThrower = (ExceptionThrower) ins;
Class[] exceptionList = exceptionThrower.getExceptions();
for (int i = 0; i < exceptionList.length; ++i) {
exceptionTypeSet.addImplicit(new ObjectType(exceptionList[i].getName()));
}
// Assume that an Error may be thrown by any instruction.
exceptionTypeSet.addImplicit(Hierarchy.ERROR_TYPE);
if (ins instanceof ATHROW) {
// For ATHROW instructions, we generate *two* blocks
// for which the ATHROW is an exception thrower.
// - The first, empty basic block, does the null check
// - The second block, which actually contains the ATHROW,
// throws the object on the top of the operand stack
// We make a special case of the block containing the ATHROW,
// by removing all of the implicit exceptions,
// and using type information to figure out what is thrown.
if (basicBlock.containsInstruction(pei)) {
// This is the actual ATHROW, not the null check
// and implicit exceptions.
exceptionTypeSet.clear();
// The frame containing the thrown value is the start fact
// for the block, because ATHROW is guaranteed to be
// the only instruction in the block.
TypeFrame frame = getStartFact(basicBlock);
// Check whether or not the frame is valid.
// Sun's javac sometimes emits unreachable code.
// For example, it will emit code that follows a JSR
// subroutine call that never returns.
// If the frame is invalid, then we can just make
// a conservative assumption that anything could be
// thrown at this ATHROW.
if (!frame.isValid()) {
exceptionTypeSet.addExplicit(Type.THROWABLE);
} else {
Type throwType = frame.getTopValue();
if (!(throwType instanceof ObjectType))
throw new DataflowAnalysisException("Non object type thrown by " + pei);
exceptionTypeSet.addExplicit((ObjectType) throwType);
}
}
}
// If it's an InvokeInstruction, add declared exceptions and RuntimeException
if (ins instanceof InvokeInstruction) {
ConstantPoolGen cpg = methodGen.getConstantPool();
InvokeInstruction inv = (InvokeInstruction) ins;
ObjectType[] declaredExceptionList = Hierarchy.findDeclaredExceptions(inv, cpg);
if (declaredExceptionList == null) {
// Couldn't find declared exceptions,
// so conservatively assume it could thrown any checked exception.
if (DEBUG) System.out.println("Couldn't find declared exceptions for " +
SignatureConverter.convertMethodSignature(inv, cpg));
exceptionTypeSet.addExplicit(Hierarchy.EXCEPTION_TYPE);
} else {
for (int i = 0; i < declaredExceptionList.length; ++i) {
exceptionTypeSet.addExplicit(declaredExceptionList[i]);
}
}
exceptionTypeSet.addImplicit(Hierarchy.RUNTIME_EXCEPTION_TYPE);
}
if (DEBUG) System.out.println(pei + " can throw " + exceptionTypeSet);
return exceptionTypeSet;
}
}
// vim:ts=4
|
package bisq.network.p2p.peers;
import bisq.network.p2p.BundleOfEnvelopes;
import bisq.network.p2p.NodeAddress;
import bisq.network.p2p.network.Connection;
import bisq.network.p2p.network.NetworkNode;
import bisq.network.p2p.storage.messages.BroadcastMessage;
import bisq.common.Timer;
import bisq.common.UserThread;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.SettableFuture;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
@Slf4j
public class BroadcastHandler implements PeerManager.Listener {
private static final long BASE_TIMEOUT_MS = TimeUnit.SECONDS.toMillis(60);
// Listener
interface ResultHandler {
void onCompleted(BroadcastHandler broadcastHandler);
}
public interface Listener {
void onSufficientlyBroadcast(List<Broadcaster.BroadcastRequest> broadcastRequests);
void onNotSufficientlyBroadcast(int numOfCompletedBroadcasts, int numOfFailedBroadcast);
}
// Instance fields
private final NetworkNode networkNode;
private final PeerManager peerManager;
private final ResultHandler resultHandler;
private final String uid;
private boolean stopped, timeoutTriggered;
private int numOfCompletedBroadcasts, numOfFailedBroadcasts, numPeersForBroadcast;
private Timer timeoutTimer;
// Constructor
BroadcastHandler(NetworkNode networkNode, PeerManager peerManager, ResultHandler resultHandler) {
this.networkNode = networkNode;
this.peerManager = peerManager;
this.resultHandler = resultHandler;
uid = UUID.randomUUID().toString();
peerManager.addListener(this);
}
// API
public void broadcast(List<Broadcaster.BroadcastRequest> broadcastRequests, boolean shutDownRequested) {
List<Connection> confirmedConnections = new ArrayList<>(networkNode.getConfirmedConnections());
Collections.shuffle(confirmedConnections);
int delay;
if (shutDownRequested) {
delay = 1;
// We sent to all peers as in case we had offers we want that it gets removed with higher reliability
numPeersForBroadcast = confirmedConnections.size();
} else {
if (requestsContainOwnMessage(broadcastRequests)) {
// The broadcastRequests contains at least 1 message we have originated, so we send to all peers and
// with shorter delay
numPeersForBroadcast = confirmedConnections.size();
delay = 50;
} else {
// Relay nodes only send to max 7 peers and with longer delay
numPeersForBroadcast = Math.min(7, confirmedConnections.size());
delay = 100;
}
}
setupTimeoutHandler(broadcastRequests, delay, shutDownRequested);
int iterations = numPeersForBroadcast;
for (int i = 0; i < iterations; i++) {
long minDelay = (i + 1) * delay;
long maxDelay = (i + 2) * delay;
Connection connection = confirmedConnections.get(i);
UserThread.runAfterRandomDelay(() -> {
if (stopped) {
return;
}
// We use broadcastRequests which have excluded the requests for messages the connection has
// originated to avoid sending back the message we received. We also remove messages not satisfying
// capability checks.
List<Broadcaster.BroadcastRequest> broadcastRequestsForConnection = getBroadcastRequestsForConnection(connection, broadcastRequests);
// Could be empty list...
if (broadcastRequestsForConnection.isEmpty()) {
// We decrease numPeers in that case for making completion checks correct.
if (numPeersForBroadcast > 0) {
numPeersForBroadcast
}
checkForCompletion();
return;
}
if (connection.isStopped()) {
// Connection has died in the meantime. We skip it.
// We decrease numPeers in that case for making completion checks correct.
if (numPeersForBroadcast > 0) {
numPeersForBroadcast
}
checkForCompletion();
return;
}
sendToPeer(connection, broadcastRequestsForConnection);
}, minDelay, maxDelay, TimeUnit.MILLISECONDS);
}
}
public void cancel() {
stopped = true;
cleanup();
}
// PeerManager.Listener implementation
@Override
public void onAllConnectionsLost() {
cleanup();
}
@Override
public void onNewConnectionAfterAllConnectionsLost() {
}
@Override
public void onAwakeFromStandby() {
}
// Private
// Check if we have at least one message originated by ourselves
private boolean requestsContainOwnMessage(List<Broadcaster.BroadcastRequest> broadcastRequests) {
NodeAddress myAddress = networkNode.getNodeAddress();
if (myAddress == null)
return false;
return broadcastRequests.stream().anyMatch(e -> myAddress.equals(e.getSender()));
}
private void setupTimeoutHandler(List<Broadcaster.BroadcastRequest> broadcastRequests,
int delay,
boolean shutDownRequested) {
// In case of shutdown we try to complete fast and set a short 1 second timeout
long baseTimeoutMs = shutDownRequested ? TimeUnit.SECONDS.toMillis(1) : BASE_TIMEOUT_MS;
long timeoutDelay = baseTimeoutMs + delay * (numPeersForBroadcast + 1); // We added 1 in the loop
timeoutTimer = UserThread.runAfter(() -> {
if (stopped) {
return;
}
timeoutTriggered = true;
log.warn("Broadcast did not complete after {} sec.\n" +
"numPeersForBroadcast={}\n" +
"numOfCompletedBroadcasts={}\n" +
"numOfFailedBroadcasts={}",
timeoutDelay / 1000d,
numPeersForBroadcast,
numOfCompletedBroadcasts,
numOfFailedBroadcasts);
maybeNotifyListeners(broadcastRequests);
cleanup();
}, timeoutDelay, TimeUnit.MILLISECONDS);
}
// We exclude the requests containing a message we received from that connection
// Also we filter out messages which requires a capability but peer does not support it.
private List<Broadcaster.BroadcastRequest> getBroadcastRequestsForConnection(Connection connection,
List<Broadcaster.BroadcastRequest> broadcastRequests) {
return broadcastRequests.stream()
.filter(broadcastRequest -> !connection.getPeersNodeAddressOptional().isPresent() ||
!connection.getPeersNodeAddressOptional().get().equals(broadcastRequest.getSender()))
.filter(broadcastRequest -> connection.noCapabilityRequiredOrCapabilityIsSupported(broadcastRequest.getMessage()))
.collect(Collectors.toList());
}
private void sendToPeer(Connection connection, List<Broadcaster.BroadcastRequest> broadcastRequestsForConnection) {
// Can be BundleOfEnvelopes or a single BroadcastMessage
BroadcastMessage broadcastMessage = getMessage(broadcastRequestsForConnection);
SettableFuture<Connection> future = networkNode.sendMessage(connection, broadcastMessage);
Futures.addCallback(future, new FutureCallback<>() {
@Override
public void onSuccess(Connection connection) {
numOfCompletedBroadcasts++;
if (stopped) {
return;
}
maybeNotifyListeners(broadcastRequestsForConnection);
checkForCompletion();
}
@Override
public void onFailure(@NotNull Throwable throwable) {
log.warn("Broadcast to {} failed. ErrorMessage={}", connection.getPeersNodeAddressOptional(),
throwable.getMessage());
numOfFailedBroadcasts++;
if (stopped) {
return;
}
maybeNotifyListeners(broadcastRequestsForConnection);
checkForCompletion();
}
});
}
private BroadcastMessage getMessage(List<Broadcaster.BroadcastRequest> broadcastRequests) {
if (broadcastRequests.size() == 1) {
// If we only have 1 message we avoid the overhead of the BundleOfEnvelopes and send the message directly
return broadcastRequests.get(0).getMessage();
} else {
return new BundleOfEnvelopes(broadcastRequests.stream()
.map(Broadcaster.BroadcastRequest::getMessage)
.collect(Collectors.toList()));
}
}
private void maybeNotifyListeners(List<Broadcaster.BroadcastRequest> broadcastRequests) {
int numOfCompletedBroadcastsTarget = Math.max(1, Math.min(numPeersForBroadcast, 3));
// We use equal checks to avoid duplicated listener calls as it would be the case with >= checks.
if (numOfCompletedBroadcasts == numOfCompletedBroadcastsTarget) {
// We have heard back from 3 peers (or all peers if numPeers is lower) so we consider the message was sufficiently broadcast.
broadcastRequests.stream()
.filter(broadcastRequest -> broadcastRequest.getListener() != null)
.map(Broadcaster.BroadcastRequest::getListener)
.forEach(listener -> listener.onSufficientlyBroadcast(broadcastRequests));
} else {
// We check if number of open requests to peers is less than we need to reach numOfCompletedBroadcastsTarget.
// Thus we never can reach required resilience as too many numOfFailedBroadcasts occurred.
int maxPossibleSuccessCases = numPeersForBroadcast - numOfFailedBroadcasts;
// We subtract 1 as we want to have it called only once, with a < comparision we would trigger repeatedly.
boolean notEnoughSucceededOrOpen = maxPossibleSuccessCases == numOfCompletedBroadcastsTarget - 1;
// We did not reach resilience level and timeout prevents to reach it later
boolean timeoutAndNotEnoughSucceeded = timeoutTriggered && numOfCompletedBroadcasts < numOfCompletedBroadcastsTarget;
if (notEnoughSucceededOrOpen || timeoutAndNotEnoughSucceeded) {
broadcastRequests.stream()
.filter(broadcastRequest -> broadcastRequest.getListener() != null)
.map(Broadcaster.BroadcastRequest::getListener)
.forEach(listener -> listener.onNotSufficientlyBroadcast(numOfCompletedBroadcasts, numOfFailedBroadcasts));
}
}
}
private void checkForCompletion() {
if (numOfCompletedBroadcasts + numOfFailedBroadcasts == numPeersForBroadcast) {
cleanup();
}
}
private void cleanup() {
stopped = true;
if (timeoutTimer != null) {
timeoutTimer.stop();
timeoutTimer = null;
}
peerManager.removeListener(this);
resultHandler.onCompleted(this);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof BroadcastHandler)) return false;
BroadcastHandler that = (BroadcastHandler) o;
return uid.equals(that.uid);
}
@Override
public int hashCode() {
return uid.hashCode();
}
}
|
package com.redhat.ceylon.compiler.java.metadata;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* A type parameter of a Ceylon type or method (should be contained in an
* {@link TypeParameters @TypeParameters()}).
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({})
public @interface TypeParameter {
/** The name of the type parameter */
String value();
/**
* String representation of the types that this type parameter is
* constrained to satisfy (in the {@code given ... satisfies ...} clause).
* May contain fully-qualified type names and type parameter names
*/
String[] satisfies() default {};
/**
* String representation of the case types that this type parameter is
* constrained to be (in the {@code given ... of ...} clause).
* May contain fully-qualified type names and type parameter names
*/
String[] caseTypes() default {};
/** The variance of this type parameter */
Variance variance() default Variance.NONE;
/**
* The default value for this type parameter if it is optional and defaulted.
* Defaults to the empty string if this type parameter is not optional.
* May contain fully-qualified type names and type parameter names.
*/
String defaultValue() default "";
}
|
package rx.android.preferences;
import android.content.SharedPreferences;
import rx.Observable;
import rx.functions.Action1;
import rx.functions.Func1;
/** A preference of type {@link T}. Instances can be created from {@link RxSharedPreferences}. */
public final class Preference<T> {
/** Stores and retrieves instances of {@code T} in {@link SharedPreferences}. */
public interface Adapter<T> {
/**
* Retrieve the value for {@code key} from {@code preferences}, using {@code defaultValue} if
* no value exists.
*/
T get(String key, T defaultValue, SharedPreferences preferences);
/**
* Store nullable {@code value} for {@code key} in {@code editor}.
* <p>
* Note: Implementations <b>must not</b> call {@code commit()} or {@code apply()} on
* {@code editor}.
*/
void set(String key, T value, SharedPreferences.Editor editor);
}
private final SharedPreferences preferences;
private final String key;
private final T defaultValue;
private final Adapter<T> adapter;
private final Observable<T> values;
Preference(SharedPreferences preferences, final String key, T defaultValue, Adapter<T> adapter,
Observable<String> keyChanges) {
this.preferences = preferences;
this.key = key;
this.defaultValue = defaultValue;
this.adapter = adapter;
this.values = keyChanges
.filter(new Func1<String, Boolean>() {
@Override public Boolean call(String changedKey) {
return key.equals(changedKey);
}
})
.startWith("<init>") // Dummy value to trigger initial load.
.map(new Func1<String, T>() {
@Override public T call(String ignored) {
return get();
}
});
}
/** The key for which this preference will store and retrieve values. */
public String key() {
return key;
}
/** The value used if none is stored. May be {@code null}. */
public T defaultValue() {
return defaultValue;
}
/**
* Retrieve the current value for this preference. Returns {@link #defaultValue()} if no value is
* set.
*/
public T get() {
return adapter.get(key, defaultValue, preferences);
}
/** Change this preference's stored value to {@code value}. */
public void set(T value) {
SharedPreferences.Editor editor = preferences.edit();
adapter.set(key, value, editor);
editor.apply();
}
/** Returns true if this preference has a stored value. */
public boolean isSet() {
return preferences.contains(key);
}
/** Delete the stored value for this preference, if any. */
public void delete() {
preferences.edit().remove(key).apply();
}
/**
* Observe changes to this preference. The current value or {@link #defaultValue()} will be
* emitted on first subscribe.
*/
public Observable<T> asObservable() {
return values;
}
/** An action which stores a new value for this preference. */
public Action1<? super T> asAction() {
return new Action1<T>() {
@Override public void call(T value) {
set(value);
}
};
}
}
|
package org.davidmoten.rx.jdbc;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLSyntaxErrorException;
import java.sql.Statement;
import java.sql.Time;
import java.sql.Timestamp;
import java.sql.Types;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.davidmoten.rx.jdbc.annotations.Column;
import org.davidmoten.rx.jdbc.annotations.Index;
import org.davidmoten.rx.jdbc.annotations.Query;
import org.davidmoten.rx.jdbc.exceptions.AnnotationsNotFoundException;
import org.davidmoten.rx.jdbc.exceptions.AutomappedInterfaceInaccessibleException;
import org.davidmoten.rx.jdbc.exceptions.ColumnIndexOutOfRangeException;
import org.davidmoten.rx.jdbc.exceptions.ColumnNotFoundException;
import org.davidmoten.rx.jdbc.exceptions.MoreColumnsRequestedThanExistException;
import org.davidmoten.rx.jdbc.exceptions.NamedParameterFoundButSqlDoesNotHaveNamesException;
import org.davidmoten.rx.jdbc.exceptions.NamedParameterMissingException;
import org.davidmoten.rx.jdbc.exceptions.QueryAnnotationMissingException;
import org.davidmoten.rx.jdbc.pool.DatabaseCreator;
import org.davidmoten.rx.jdbc.pool.DatabaseType;
import org.davidmoten.rx.jdbc.pool.NonBlockingConnectionPool;
import org.davidmoten.rx.jdbc.pool.Pools;
import org.davidmoten.rx.jdbc.tuple.Tuple2;
import org.davidmoten.rx.jdbc.tuple.Tuple3;
import org.davidmoten.rx.jdbc.tuple.Tuple4;
import org.davidmoten.rx.jdbc.tuple.Tuple5;
import org.davidmoten.rx.jdbc.tuple.Tuple6;
import org.davidmoten.rx.jdbc.tuple.Tuple7;
import org.davidmoten.rx.jdbc.tuple.TupleN;
import org.davidmoten.rx.pool.PoolClosedException;
import org.h2.jdbc.JdbcSQLException;
import org.hsqldb.jdbc.JDBCBlobFile;
import org.hsqldb.jdbc.JDBCClobFile;
import org.junit.Assert;
import org.junit.FixMethodOrder;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.davidmoten.guavamini.Lists;
import com.github.davidmoten.guavamini.Sets;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import io.reactivex.Completable;
import io.reactivex.Flowable;
import io.reactivex.Observable;
import io.reactivex.Scheduler;
import io.reactivex.Single;
import io.reactivex.functions.Predicate;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.schedulers.TestScheduler;
import io.reactivex.subscribers.TestSubscriber;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class DatabaseTest {
private static final long FRED_REGISTERED_TIME = 1442515672690L;
private static final int NAMES_COUNT_BIG = 5163;
private static final Logger log = LoggerFactory.getLogger(DatabaseTest.class);
private static final int TIMEOUT_SECONDS = 10;
private static Database db() {
return DatabaseCreator.create(1);
}
private static Database blocking() {
return DatabaseCreator.createBlocking();
}
private static Database db(int poolSize) {
return DatabaseCreator.create(poolSize);
}
private static Database big(int poolSize) {
return DatabaseCreator.create(poolSize, true, Schedulers.computation());
}
@Test
public void testSelectUsingQuestionMark() {
try (Database db = db()) {
db.select("select score from person where name=?")
.parameters("FRED", "JOSEPH")
.getAs(Integer.class)
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertNoErrors()
.assertValues(21, 34)
.assertComplete();
}
}
@Test
public void testBlockingForEachWhenError() {
try {
Flowable
.error(new RuntimeException("boo"))
.blockingForEach(System.out::println);
} catch (RuntimeException e) {
assertEquals("boo", e.getMessage());
}
}
@Test
public void testSelectUsingQuestionMarkAndInClauseIssue10() {
Database.test()
.select("select score from person where name in (?) order by score")
.parameters("FRED", "JOSEPH")
.getAs(Integer.class)
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertNoErrors()
.assertValues(21, 34)
.assertComplete();
}
@Test
public void testSelectUsingQuestionMarkAndInClauseWithSetParameter() {
Database.test()
.select("select score from person where name in (?) order by score")
.parameter(Sets.newHashSet("FRED", "JOSEPH"))
.getAs(Integer.class)
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertNoErrors()
.assertValues(21, 34)
.assertComplete();
}
@Test
public void testSelectUsingQuestionMarkAndInClauseWithSetParameterUsingParametersMethod() {
Database.test()
.select("select score from person where name in (?) order by score")
.parameters(Sets.newHashSet("FRED", "JOSEPH"))
.getAs(Integer.class)
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertNoErrors()
.assertValues(21, 34)
.assertComplete();
}
@Test
public void testSelectUsingInClauseWithListParameter() {
Database.test()
.select("select score from person where score > ? and name in (?) order by score")
.parameters(0, Lists.newArrayList("FRED", "JOSEPH"))
.getAs(Integer.class)
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertNoErrors()
.assertValues(21, 34)
.assertComplete();
}
@Test
public void testSelectUsingInClauseWithNamedListParameter() {
Database.test()
.select("select score from person where score > :score and name in (:names) order by score")
.parameter("score", 0)
.parameter("names", Lists.newArrayList("FRED", "JOSEPH"))
.getAs(Integer.class)
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertNoErrors()
.assertValues(21, 34)
.assertComplete();
}
@Test
public void testSelectUsingInClauseWithRepeatedNamedListParameter() {
Database.test()
.select("select score from person where name in (:names) and name in (:names) order by score")
.parameter("names", Lists.newArrayList("FRED", "JOSEPH"))
.getAs(Integer.class)
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertNoErrors()
.assertValues(21, 34)
.assertComplete();
}
@Test
public void testSelectUsingInClauseWithRepeatedNamedListParameterAndRepeatedNonListParameter() {
Database.test()
.select("select score from person where name in (:names) and score >:score and name in (:names) and score >:score order by score")
.parameter("names", Lists.newArrayList("FRED", "JOSEPH"))
.parameter("score", 0)
.getAs(Integer.class)
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertNoErrors()
.assertValues(21, 34)
.assertComplete();
}
@Test
public void testSelectUsingNamedParameterList() {
try (Database db = db()) {
db.select("select score from person where name=:name")
.parameters(Parameter.named("name", "FRED").value("JOSEPH").list())
.getAs(Integer.class)
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertNoErrors()
.assertValues(21, 34)
.assertComplete();
}
}
@Test
public void testSelectUsingQuestionMarkFlowableParameters() {
try (Database db = db()) {
db.select("select score from person where name=?")
.parameterStream(Flowable.just("FRED", "JOSEPH"))
.getAs(Integer.class)
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertNoErrors()
.assertValues(21, 34)
.assertComplete();
}
}
@Test
public void testSelectUsingQuestionMarkFlowableParametersInLists() {
try (Database db = db()) {
db.select("select score from person where name=?")
.parameterListStream(
Flowable.just(Arrays.asList("FRED"), Arrays.asList("JOSEPH")))
.getAs(Integer.class)
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertNoErrors()
.assertValues(21, 34)
.assertComplete();
}
}
@Test
public void testDrivingSelectWithoutParametersUsingParameterStream() {
try (Database db = db()) {
db.select("select count(*) from person")
.parameters(1, 2, 3)
.getAs(Integer.class)
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValues(3, 3, 3)
.assertComplete();
}
}
@Test
public void testSelectUsingQuestionMarkFlowableParametersTwoParametersPerQuery() {
try (Database db = db()) {
db.select("select score from person where name=? and score = ?")
.parameterStream(Flowable.just("FRED", 21, "JOSEPH", 34))
.getAs(Integer.class)
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertNoErrors()
.assertValues(21, 34)
.assertComplete();
}
}
@Test
public void testSelectUsingQuestionMarkFlowableParameterListsTwoParametersPerQuery() {
try (Database db = db()) {
db.select("select score from person where name=? and score = ?")
.parameterListStream(
Flowable.just(Arrays.asList("FRED", 21), Arrays.asList("JOSEPH", 34)))
.getAs(Integer.class)
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertNoErrors()
.assertValues(21, 34)
.assertComplete();
}
}
@Test
public void testSelectUsingQuestionMarkWithPublicTestingDatabase() {
try (Database db = Database.test()) {
db
.select("select score from person where name=?")
.parameters("FRED", "JOSEPH")
.getAs(Integer.class)
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertNoErrors()
.assertValues(21, 34)
.assertComplete();
}
}
@Test
public void testSelectWithFetchSize() {
try (Database db = db()) {
db.select("select score from person order by name")
.fetchSize(2)
.getAs(Integer.class)
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertNoErrors()
.assertValues(21, 34, 25)
.assertComplete();
}
}
@Test
public void testSelectWithFetchSizeZero() {
try (Database db = db()) {
db.select("select score from person order by name")
.fetchSize(0)
.getAs(Integer.class)
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertNoErrors()
.assertValues(21, 34, 25)
.assertComplete();
}
}
@Test(expected = IllegalArgumentException.class)
public void testSelectWithFetchSizeNegative() {
try (Database db = db()) {
db.select("select score from person order by name")
.fetchSize(-1);
}
}
@Test
public void testSelectUsingNonBlockingBuilder() {
NonBlockingConnectionPool pool = Pools
.nonBlocking()
.connectionProvider(DatabaseCreator.connectionProvider())
.maxIdleTime(1, TimeUnit.MINUTES)
.idleTimeBeforeHealthCheck(1, TimeUnit.MINUTES)
.createRetryInterval(1, TimeUnit.SECONDS)
.healthCheck(c -> c.prepareStatement("select 1").execute())
.maxPoolSize(3)
.build();
try (Database db = Database.from(pool)) {
db.select("select score from person where name=?")
.parameters("FRED", "JOSEPH")
.getAs(Integer.class)
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertNoErrors()
.assertValues(21, 34)
.assertComplete();
}
}
@Test
public void testSelectSpecifyingHealthCheck() {
try (Database db = Database
.nonBlocking()
.connectionProvider(DatabaseCreator.connectionProvider())
.maxIdleTime(1, TimeUnit.MINUTES)
.idleTimeBeforeHealthCheck(1, TimeUnit.MINUTES)
.createRetryInterval(1, TimeUnit.SECONDS)
.healthCheck(DatabaseType.H2)
.maxPoolSize(3)
.build()) {
db.select("select score from person where name=?")
.parameters("FRED", "JOSEPH")
.getAs(Integer.class)
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertNoErrors()
.assertValues(21, 34)
.assertComplete();
}
}
@Test(expected = IllegalArgumentException.class)
public void testCreateTestDatabaseWithZeroSizePoolThrows() {
Database.test(0);
}
@Test
public void testSelectSpecifyingHealthCheckAsSql() {
NonBlockingConnectionPool pool = Pools
.nonBlocking()
.connectionProvider(DatabaseCreator.connectionProvider())
.maxIdleTime(1, TimeUnit.MINUTES)
.healthCheck(DatabaseType.H2)
.idleTimeBeforeHealthCheck(1, TimeUnit.MINUTES)
.createRetryInterval(1, TimeUnit.SECONDS)
.healthCheck("select 1")
.maxPoolSize(3)
.build();
try (Database db = Database.from(pool)) {
db.select("select score from person where name=?")
.parameters("FRED", "JOSEPH")
.getAs(Integer.class)
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertNoErrors()
.assertValues(21, 34)
.assertComplete();
}
}
@Test(expected = IllegalArgumentException.class)
public void testNonBlockingPoolWithTrampolineSchedulerThrows() {
Pools.nonBlocking().scheduler(Schedulers.trampoline());
}
@Test(timeout = 40000)
public void testSelectUsingNonBlockingBuilderConcurrencyTest()
throws InterruptedException, TimeoutException {
info();
try {
try (Database db = db(3)) {
Scheduler scheduler = Schedulers.from(Executors.newFixedThreadPool(50));
int n = 10000;
CountDownLatch latch = new CountDownLatch(n);
AtomicInteger count = new AtomicInteger();
for (int i = 0; i < n; i++) {
db.select("select score from person where name=?")
.parameters("FRED", "JOSEPH")
.getAs(Integer.class)
.subscribeOn(scheduler)
.toList()
.doOnSuccess(x -> {
if (!x.equals(Lists.newArrayList(21, 34))) {
throw new RuntimeException("run broken");
} else {
// log.debug(iCopy + " succeeded");
}
})
.doOnSuccess(x -> {
count.incrementAndGet();
latch.countDown();
})
.doOnError(x -> latch.countDown())
.subscribe();
}
if (!latch.await(20, TimeUnit.SECONDS)) {
throw new TimeoutException("timeout");
}
assertEquals(n, count.get());
}
} finally {
debug();
}
}
@Test(timeout = 5000)
public void testSelectConcurrencyTest() throws InterruptedException, TimeoutException {
debug();
try {
try (Database db = db(1)) {
Scheduler scheduler = Schedulers.from(Executors.newFixedThreadPool(2));
int n = 2;
CountDownLatch latch = new CountDownLatch(n);
AtomicInteger count = new AtomicInteger();
for (int i = 0; i < n; i++) {
db.select("select score from person where name=?")
.parameters("FRED", "JOSEPH")
.getAs(Integer.class)
.subscribeOn(scheduler)
.toList()
.doOnSuccess(x -> {
if (!x.equals(Lists.newArrayList(21, 34))) {
throw new RuntimeException("run broken");
}
})
.doOnSuccess(x -> {
count.incrementAndGet();
latch.countDown();
})
.doOnError(x -> latch.countDown())
.subscribe();
log.info("submitted " + i);
}
if (!latch.await(5000, TimeUnit.SECONDS)) {
throw new TimeoutException("timeout");
}
assertEquals(n, count.get());
}
} finally {
debug();
}
}
@Test
public void testDatabaseClose() {
try (Database db = db()) {
db.select("select score from person where name=?")
.parameters("FRED", "JOSEPH")
.getAs(Integer.class)
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertNoErrors()
.assertValues(21, 34)
.assertComplete();
}
}
@Test
public void testSelectUsingName() {
try (Database db = db()) {
db
.select("select score from person where name=:name")
.parameter("name", "FRED")
.parameter("name", "JOSEPH")
.getAs(Integer.class)
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValues(21, 34)
.assertComplete();
}
}
@Test
public void testSelectUsingNameNotGiven() {
try (Database db = db()) {
db
.select("select score from person where name=:name and name<>:name2")
.parameter("name", "FRED")
.parameter("name", "JOSEPH")
.getAs(Integer.class)
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertError(NamedParameterMissingException.class)
.assertNoValues();
}
}
@Test
public void testSelectUsingParameterNameNullNameWhenSqlHasNoNames() {
db()
.select("select score from person where name=?")
.parameter(Parameter.create("name", "FRED"))
.getAs(Integer.class)
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertError(NamedParameterFoundButSqlDoesNotHaveNamesException.class)
.assertNoValues();
}
@Test
public void testUpdateWithNull() {
try (Database db = db()) {
db
.update("update person set date_of_birth = :dob")
.parameter(Parameter.create("dob", null))
.counts()
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValue(3)
.assertComplete();
}
}
@Test
public void testUpdateClobWithNull() {
try (Database db = db()) {
insertNullClob(db);
db
.update("update person_clob set document = :doc")
.parameter("doc", Database.NULL_CLOB)
.counts()
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValue(1)
.assertComplete();
}
}
@Test
public void testUpdateClobWithClob() throws SQLException {
try (Database db = db()) {
Clob clob = new JDBCClobFile(new File("src/test/resources/big.txt"));
insertNullClob(db);
db
.update("update person_clob set document = :doc")
.parameter("doc", clob)
.counts()
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValue(1)
.assertComplete();
}
}
@Test
public void testUpdateClobWithReader() throws FileNotFoundException {
try (Database db = db()) {
Reader reader = new FileReader(new File("src/test/resources/big.txt"));
insertNullClob(db);
db
.update("update person_clob set document = :doc")
.parameter("doc", reader)
.counts()
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValue(1)
.assertComplete();
}
}
@Test
public void testUpdateBlobWithBlob() throws SQLException {
try (Database db = db()) {
Blob blob = new JDBCBlobFile(new File("src/test/resources/big.txt"));
insertPersonBlob(db);
db
.update("update person_blob set document = :doc")
.parameter("doc", blob)
.counts()
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValue(1)
.assertComplete();
}
}
@Test
public void testUpdateBlobWithNull() {
try (Database db = db()) {
insertPersonBlob(db);
db
.update("update person_blob set document = :doc")
.parameter("doc", Database.NULL_BLOB)
.counts()
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValue(1)
.assertComplete();
}
}
@Test(expected = NullPointerException.class)
public void testSelectUsingNullNameInParameter() {
try (Database db = db()) {
db
.select("select score from person where name=:name")
.parameter(null, "FRED");
}
}
@Test(expected = IllegalArgumentException.class)
public void testSelectUsingNameDoesNotExist() {
try (Database db = db()) {
db
.select("select score from person where name=:name")
.parameters("nam", "FRED");
}
}
@Test(expected = IllegalArgumentException.class)
public void testSelectUsingNameWithoutSpecifyingNameThrowsImmediately() {
try (Database db = db()) {
db
.select("select score from person where name=:name")
.parameters("FRED", "JOSEPH");
}
}
@Test
public void testSelectTransacted() {
try (Database db = db()) {
db
.select("select score from person where name=?")
.parameters("FRED", "JOSEPH")
.transacted()
.getAs(Integer.class)
.doOnNext(tx -> log
.debug(tx.isComplete() ? "complete" : String.valueOf(tx.value())))
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValueCount(3)
.assertComplete();
}
}
@Test
public void testSelectAutomappedAnnotatedTransacted() {
try (Database db = db()) {
db
.select(Person10.class)
.transacted()
.valuesOnly()
.get().test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValueCount(3)
.assertComplete();
}
}
@Test
public void testSelectAutomappedTransactedValuesOnly() {
try (Database db = db()) {
db
.select("select name, score from person")
.transacted()
.valuesOnly()
.autoMap(Person2.class)
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValueCount(3)
.assertComplete();
}
}
@Test
public void testSelectAutomappedTransacted() {
try (Database db = db()) {
db
.select("select name, score from person")
.transacted()
.autoMap(Person2.class)
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValueCount(4)
.assertComplete();
}
}
@Test
public void testSelectTransactedTuple2() {
try (Database db = db()) {
Tx<Tuple2<String, Integer>> t = db
.select("select name, score from person where name=?")
.parameters("FRED")
.transacted()
.getAs(String.class, Integer.class)
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValueCount(2)
.assertComplete()
.values().get(0);
assertEquals("FRED", t.value()._1());
assertEquals(21, (int) t.value()._2());
}
}
@Test
public void testSelectTransactedTuple3() {
try (Database db = db()) {
Tx<Tuple3<String, Integer, String>> t = db
.select("select name, score, name from person where name=?")
.parameters("FRED")
.transacted()
.getAs(String.class, Integer.class, String.class)
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValueCount(2)
.assertComplete()
.values().get(0);
assertEquals("FRED", t.value()._1());
assertEquals(21, (int) t.value()._2());
assertEquals("FRED", t.value()._3());
}
}
@Test
public void testSelectTransactedTuple4() {
try (Database db = db()) {
Tx<Tuple4<String, Integer, String, Integer>> t = db
.select("select name, score, name, score from person where name=?")
.parameters("FRED")
.transacted()
.getAs(String.class, Integer.class, String.class, Integer.class)
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValueCount(2)
.assertComplete()
.values().get(0);
assertEquals("FRED", t.value()._1());
assertEquals(21, (int) t.value()._2());
assertEquals("FRED", t.value()._3());
assertEquals(21, (int) t.value()._4());
}
}
@Test
public void testSelectTransactedTuple5() {
try (Database db = db()) {
Tx<Tuple5<String, Integer, String, Integer, String>> t = db
.select("select name, score, name, score, name from person where name=?")
.parameters("FRED")
.transacted()
.getAs(String.class, Integer.class, String.class, Integer.class, String.class)
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValueCount(2)
.assertComplete()
.values().get(0);
assertEquals("FRED", t.value()._1());
assertEquals(21, (int) t.value()._2());
assertEquals("FRED", t.value()._3());
assertEquals(21, (int) t.value()._4());
assertEquals("FRED", t.value()._5());
}
}
@Test
public void testSelectTransactedTuple6() {
try (Database db = db()) {
Tx<Tuple6<String, Integer, String, Integer, String, Integer>> t = db
.select("select name, score, name, score, name, score from person where name=?")
.parameters("FRED")
.transacted()
.getAs(String.class, Integer.class, String.class, Integer.class, String.class,
Integer.class)
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValueCount(2)
.assertComplete()
.values().get(0);
assertEquals("FRED", t.value()._1());
assertEquals(21, (int) t.value()._2());
assertEquals("FRED", t.value()._3());
assertEquals(21, (int) t.value()._4());
assertEquals("FRED", t.value()._5());
assertEquals(21, (int) t.value()._6());
}
}
@Test
public void testSelectTransactedTuple7() {
try (Database db = db()) {
Tx<Tuple7<String, Integer, String, Integer, String, Integer, String>> t = db
.select("select name, score, name, score, name, score, name from person where name=?")
.parameters("FRED")
.transacted()
.getAs(String.class, Integer.class, String.class, Integer.class, String.class,
Integer.class, String.class)
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValueCount(2)
.assertComplete()
.values().get(0);
assertEquals("FRED", t.value()._1());
assertEquals(21, (int) t.value()._2());
assertEquals("FRED", t.value()._3());
assertEquals(21, (int) t.value()._4());
assertEquals("FRED", t.value()._5());
assertEquals(21, (int) t.value()._6());
assertEquals("FRED", t.value()._7());
}
}
@Test
public void testSelectTransactedTupleN() {
try (Database db = db()) {
List<Tx<TupleN<Object>>> list = db
.select("select name, score from person where name=?")
.parameters("FRED")
.transacted()
.getTupleN()
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValueCount(2)
.assertComplete()
.values();
assertEquals("FRED", list.get(0).value().values().get(0));
assertEquals(21, (int) list.get(0).value().values().get(1));
assertTrue(list.get(1).isComplete());
assertEquals(2, list.size());
}
}
@Test
public void testSelectTransactedCount() {
try (Database db = db()) {
db
.select("select name, score, name, score, name, score, name from person where name=?")
.parameters("FRED")
.transacted()
.count()
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValueCount(1)
.assertComplete();
}
}
@Test
public void testSelectTransactedGetAs() {
try (Database db = db()) {
db
.select("select name from person")
.transacted()
.getAs(String.class)
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValueCount(4)
.assertComplete();
}
}
@Test
public void testSelectTransactedGetAsOptional() {
try (Database db = db()) {
List<Tx<Optional<String>>> list = db
.select("select name from person where name=?")
.parameters("FRED")
.transacted()
.getAsOptional(String.class)
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValueCount(2)
.assertComplete()
.values();
assertTrue(list.get(0).isValue());
assertEquals("FRED", list.get(0).value().get());
assertTrue(list.get(1).isComplete());
}
}
@Test
public void testDatabaseFrom() {
Database.from(DatabaseCreator.nextUrl(), 3)
.select("select name from person")
.getAs(String.class)
.count()
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertError(JdbcSQLException.class);
}
@Test
public void testSelectTransactedChained() throws Exception {
try (Database db = db()) {
db
.select("select score from person where name=?")
.parameters("FRED", "JOSEPH")
.transacted()
.transactedValuesOnly()
.getAs(Integer.class)
.doOnNext(tx -> log
.debug(tx.isComplete() ? "complete" : String.valueOf(tx.value())))
.flatMap(tx -> tx
.select("select name from person where score = ?")
.parameter(tx.value())
.valuesOnly()
.getAs(String.class))
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertNoErrors()
.assertValues("FRED", "JOSEPH")
.assertComplete();
}
}
@Test
public void databaseIsAutoCloseable() {
try (Database db = db()) {
log.debug(db.toString());
}
}
private static void println(Object o) {
log.debug("{}", o);
}
@Test
public void testSelectChained() {
try (Database db = db(1)) {
// we can do this with 1 connection only!
db.select("select score from person where name=?")
.parameters("FRED", "JOSEPH")
.getAs(Integer.class)
.doOnNext(DatabaseTest::println)
.concatMap(score -> {
log.info("score={}", score);
return db
.select("select name from person where score = ?")
.parameter(score)
.getAs(String.class)
.doOnComplete(
() -> log.info("completed select where score=" + score));
})
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertNoErrors()
.assertValues("FRED", "JOSEPH")
.assertComplete();
}
}
@Test
@SuppressFBWarnings
public void testReadMeFragment1() {
try (Database db = db()) {
db.select("select name from person")
.getAs(String.class)
.forEach(DatabaseTest::println);
}
}
@Test
public void testReadMeFragmentColumnDoesNotExistEmitsSqlSyntaxErrorException() {
try (Database db = Database.test()) {
db.select("select nam from person")
.getAs(String.class)
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertNoValues()
.assertError(SQLSyntaxErrorException.class);
}
}
@Test
public void testReadMeFragmentDerbyHealthCheck() {
try (Database db = Database.test()) {
db.select("select 'a' from sysibm.sysdummy1")
.getAs(String.class)
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValue("a")
.assertComplete();
}
}
@Test
@SuppressFBWarnings
public void testTupleSupport() {
try (Database db = db()) {
db.select("select name, score from person")
.getAs(String.class, Integer.class)
.forEach(DatabaseTest::println);
}
}
@Test
public void testDelayedCallsAreNonBlocking() throws InterruptedException {
List<String> list = new CopyOnWriteArrayList<String>();
try (Database db = db(1)) {
db.select("select score from person where name=?")
.parameter("FRED")
.getAs(Integer.class)
.doOnNext(x -> Thread.sleep(1000))
.subscribeOn(Schedulers.io())
.subscribe();
Thread.sleep(100);
CountDownLatch latch = new CountDownLatch(1);
db.select("select score from person where name=?")
.parameter("FRED")
.getAs(Integer.class)
.doOnNext(x -> list.add("emitted"))
.doOnNext(x -> log.debug("emitted on " + Thread.currentThread().getName()))
.doOnNext(x -> latch.countDown())
.subscribe();
list.add("subscribed");
assertTrue(latch.await(TIMEOUT_SECONDS, TimeUnit.SECONDS));
assertEquals(Arrays.asList("subscribed", "emitted"), list);
}
}
@Test
public void testAutoMapToInterface() {
try (Database db = db()) {
db
.select("select name from person")
.autoMap(Person.class)
.map(p -> p.name())
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValueCount(3)
.assertComplete();
}
}
@Test
public void testAutoMapToInterfaceWithoutAnnotationstsError() {
try (Database db = db()) {
db
.select("select name from person")
.autoMap(PersonNoAnnotation.class)
.map(p -> p.name())
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertNoValues()
.assertError(AnnotationsNotFoundException.class);
}
}
@Test
public void testAutoMapToInterfaceWithTwoMethods() {
try (Database db = db()) {
db
.select("select name, score from person order by name")
.autoMap(Person2.class)
.firstOrError()
.map(Person2::score)
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValue(21)
.assertComplete();
}
}
@Test
public void testAutoMapToInterfaceWithExplicitColumnName() {
try (Database db = db()) {
db
.select("select name, score from person order by name")
.autoMap(Person3.class)
.firstOrError()
.map(Person3::examScore)
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValue(21)
.assertComplete();
}
}
@Test
public void testAutoMapToInterfaceWithExplicitColumnNameThatDoesNotExist() {
try (Database db = db()) {
db
.select("select name, score from person order by name")
.autoMap(Person4.class)
.firstOrError()
.map(Person4::examScore)
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertNoValues()
.assertError(ColumnNotFoundException.class);
}
}
@Test
public void testAutoMapToInterfaceWithIndex() {
try (Database db = db()) {
db
.select("select name, score from person order by name")
.autoMap(Person5.class)
.firstOrError()
.map(Person5::examScore)
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValue(21)
.assertComplete();
}
}
@Test
public void testAutoMapToInterfaceWithIndexTooLarge() {
try (Database db = db()) {
db
.select("select name, score from person order by name")
.autoMap(Person6.class)
.firstOrError()
.map(Person6::examScore)
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertNoValues()
.assertError(ColumnIndexOutOfRangeException.class);
}
}
@Test
public void testAutoMapToInterfaceWithIndexTooSmall() {
try (Database db = db()) {
db
.select("select name, score from person order by name")
.autoMap(Person7.class)
.firstOrError()
.map(Person7::examScore)
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertNoValues()
.assertError(ColumnIndexOutOfRangeException.class);
}
}
@Test
public void testAutoMapWithUnmappableColumnType() {
try (Database db = db()) {
db
.select("select name from person order by name")
.autoMap(Person8.class)
.map(p -> p.name())
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertNoValues()
.assertError(ClassCastException.class);
}
}
@Test
public void testAutoMapWithMixIndexAndName() {
try (Database db = db()) {
db
.select("select name, score from person order by name")
.autoMap(Person9.class)
.firstOrError()
.map(Person9::score)
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValue(21)
.assertComplete();
}
}
@Test
public void testAutoMapWithQueryInAnnotation() {
try (Database db = db()) {
db.select(Person10.class)
.get()
.firstOrError()
.map(Person10::score)
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValue(21)
.assertComplete();
}
}
@Test
@Ignore
public void testAutoMapForReadMe() {
try (Database db = Database.test()) {
db.select(Person10.class)
.get(Person10::name)
.blockingForEach(DatabaseTest::println);
}
}
@Test(expected = QueryAnnotationMissingException.class)
public void testAutoMapWithoutQueryInAnnotation() {
try (Database db = db()) {
db.select(Person.class);
}
}
@Test
public void testSelectWithoutWhereClause() {
try (Database db = db()) {
Assert.assertEquals(3, (long) db.select("select name from person")
.count()
.blockingGet());
}
}
@Test
public void testTuple3() {
try (Database db = db()) {
db
.select("select name, score, name from person order by name")
.getAs(String.class, Integer.class, String.class)
.firstOrError()
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertComplete()
.assertValue(Tuple3.create("FRED", 21, "FRED"));
}
}
@Test
public void testTuple4() {
try (Database db = db()) {
db
.select("select name, score, name, score from person order by name")
.getAs(String.class, Integer.class, String.class, Integer.class)
.firstOrError()
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertComplete()
.assertValue(Tuple4.create("FRED", 21, "FRED", 21));
}
}
@Test
public void testTuple5() {
try (Database db = db()) {
db
.select("select name, score, name, score, name from person order by name")
.getAs(String.class, Integer.class, String.class, Integer.class, String.class)
.firstOrError()
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertComplete().assertValue(Tuple5.create("FRED", 21, "FRED", 21, "FRED"));
}
}
@Test
public void testTuple6() {
try (Database db = db()) {
db
.select("select name, score, name, score, name, score from person order by name")
.getAs(String.class, Integer.class, String.class, Integer.class, String.class,
Integer.class)
.firstOrError()
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertComplete()
.assertValue(Tuple6.create("FRED", 21, "FRED", 21, "FRED", 21));
}
}
@Test
public void testTuple7() {
try (Database db = db()) {
db
.select("select name, score, name, score, name, score, name from person order by name")
.getAs(String.class, Integer.class, String.class, Integer.class, String.class,
Integer.class, String.class)
.firstOrError()
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertComplete()
.assertValue(Tuple7.create("FRED", 21, "FRED", 21, "FRED", 21, "FRED"));
}
}
@Test
public void testTupleN() {
try (Database db = db()) {
db
.select("select name, score, name from person order by name")
.getTupleN()
.firstOrError().test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertComplete()
.assertValue(TupleN.create("FRED", 21, "FRED"));
}
}
@Test
public void testTupleNWithClass() {
try (Database db = db()) {
db
.select("select score a, score b from person order by name")
.getTupleN(Integer.class)
.firstOrError()
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertComplete()
.assertValue(TupleN.create(21, 21));
}
}
@Test
public void testTupleNWithClassInTransaction() {
try (Database db = db()) {
db
.select("select score a, score b from person order by name")
.transactedValuesOnly()
.getTupleN(Integer.class)
.map(x -> x.value())
.firstOrError()
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertComplete()
.assertValue(TupleN.create(21, 21));
}
}
@Test
public void testHealthCheck() throws InterruptedException {
AtomicBoolean once = new AtomicBoolean(true);
testHealthCheck(c -> {
log.debug("doing health check");
return !once.compareAndSet(true, false);
});
}
@Test
public void testHealthCheckThatThrows() throws InterruptedException {
AtomicBoolean once = new AtomicBoolean(true);
testHealthCheck(c -> {
log.debug("doing health check");
if (!once.compareAndSet(true, false))
return true;
else
throw new RuntimeException("health check failed");
});
}
@Test
public void testUpdateOneRow() {
try (Database db = db()) {
db.update("update person set score=20 where name='FRED'")
.counts()
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValue(1)
.assertComplete();
}
}
@Test
public void testUpdateThreeRows() {
try (Database db = db()) {
db.update("update person set score=20")
.counts()
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValue(3)
.assertComplete();
}
}
@Test
public void testUpdateWithParameter() {
try (Database db = db()) {
db.update("update person set score=20 where name=?")
.parameter("FRED").counts()
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValue(1)
.assertComplete();
}
}
@Test
public void testUpdateWithParameterTwoRuns() {
try (Database db = db()) {
db.update("update person set score=20 where name=?")
.parameters("FRED", "JOSEPH").counts()
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValues(1, 1)
.assertComplete();
}
}
@Test
public void testUpdateAllWithParameterFourRuns() {
try (Database db = db()) {
db.update("update person set score=?")
.parameters(1, 2, 3, 4)
.counts()
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValues(3, 3, 3, 3)
.assertComplete();
}
}
@Test
public void testUpdateWithBatchSize2() {
try (Database db = db()) {
db.update("update person set score=?")
.batchSize(2)
.parameters(1, 2, 3, 4)
.counts()
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValues(3, 3, 3, 3)
.assertComplete();
}
}
@Test
public void testUpdateWithBatchSize3GreaterThanNumRecords() {
try (Database db = db()) {
db.update("update person set score=?")
.batchSize(3)
.parameters(1, 2, 3, 4)
.counts()
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValues(3, 3, 3, 3)
.assertComplete();
}
}
@Test
public void testInsert() {
try (Database db = db()) {
db.update("insert into person(name, score) values(?,?)")
.parameters("DAVE", 12, "ANNE", 18)
.counts()
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValues(1, 1)
.assertComplete();
List<Tuple2<String, Integer>> list = db.select("select name, score from person")
.getAs(String.class, Integer.class)
.toList()
.timeout(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.blockingGet();
assertTrue(list.contains(Tuple2.create("DAVE", 12)));
assertTrue(list.contains(Tuple2.create("ANNE", 18)));
}
}
@Test
public void testReturnGeneratedKeys() {
try (Database db = db()) {
// note is a table with auto increment
db.update("insert into note(text) values(?)")
.parameters("HI", "THERE")
.returnGeneratedKeys()
.getAs(Integer.class)
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValues(1, 2)
.assertComplete();
db.update("insert into note(text) values(?)")
.parameters("ME", "TOO")
.returnGeneratedKeys()
.getAs(Integer.class)
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValues(3, 4)
.assertComplete();
}
}
@Test
public void testReturnGeneratedKeysDerby() {
Database db = DatabaseCreator.createDerby(1);
// note is a table with auto increment
db.update("insert into note2(text) values(?)")
.parameters("HI", "THERE")
.returnGeneratedKeys()
.getAs(Integer.class)
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertNoErrors().assertValues(1, 3)
.assertComplete();
db.update("insert into note2(text) values(?)")
.parameters("ME", "TOO")
.returnGeneratedKeys()
.getAs(Integer.class)
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValues(5, 7)
.assertComplete();
}
@Test(expected = IllegalArgumentException.class)
public void testReturnGeneratedKeysWithBatchSizeShouldThrow() {
try (Database db = db()) {
// note is a table with auto increment
db.update("insert into note(text) values(?)")
.parameters("HI", "THERE")
.batchSize(2)
.returnGeneratedKeys();
}
}
@Test
public void testTransactedReturnGeneratedKeys() {
try (Database db = db()) {
// note is a table with auto increment
db.update("insert into note(text) values(?)")
.parameters("HI", "THERE")
.transacted()
.returnGeneratedKeys()
.valuesOnly()
.getAs(Integer.class)
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValues(1, 2)
.assertComplete();
db.update("insert into note(text) values(?)")
.parameters("ME", "TOO")
.transacted()
.returnGeneratedKeys()
.valuesOnly()
.getAs(Integer.class)
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValues(3, 4)
.assertComplete();
}
}
@Test
public void testTransactedReturnGeneratedKeys2() {
try (Database db = db()) {
// note is a table with auto increment
Flowable<Integer> a = db.update("insert into note(text) values(?)")
.parameters("HI", "THERE")
.transacted()
.returnGeneratedKeys()
.valuesOnly()
.getAs(Integer.class);
db.update("insert into note(text) values(?)")
.parameters("ME", "TOO")
.transacted()
.returnGeneratedKeys()
.valuesOnly()
.getAs(Integer.class)
.startWith(a)
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValues(1, 2, 3, 4)
.assertComplete();
}
}
@Test
public void testUpdateWithinTransaction() {
try (Database db = db()) {
db
.select("select name from person")
.transactedValuesOnly()
.getAs(String.class)
.doOnNext(DatabaseTest::println)
.flatMap(tx -> tx
.update("update person set score=-1 where name=:name")
.batchSize(1)
.parameter("name", tx.value())
.valuesOnly()
.counts())
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValues(1, 1, 1)
.assertComplete();
}
}
@Test
public void testSelectDependsOnFlowable() {
try (Database db = db()) {
Flowable<Integer> a = db.update("update person set score=100 where name=?")
.parameter("FRED")
.counts();
db.select("select score from person where name=?")
.parameter("FRED")
.dependsOn(a)
.getAs(Integer.class)
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValues(100)
.assertComplete();
}
}
@Test
public void testSelectDependsOnObservable() {
try (Database db = db()) {
Observable<Integer> a = db.update("update person set score=100 where name=?")
.parameter("FRED")
.counts().toObservable();
db.select("select score from person where name=?")
.parameter("FRED")
.dependsOn(a)
.getAs(Integer.class)
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValues(100)
.assertComplete();
}
}
@Test
public void testSelectDependsOnOnSingle() {
try (Database db = db()) {
Single<Long> a = db.update("update person set score=100 where name=?")
.parameter("FRED")
.counts().count();
db.select("select score from person where name=?")
.parameter("FRED")
.dependsOn(a)
.getAs(Integer.class)
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValues(100)
.assertComplete();
}
}
@Test
public void testSelectDependsOnCompletable() {
try (Database db = db()) {
Completable a = db.update("update person set score=100 where name=?")
.parameter("FRED")
.counts().ignoreElements();
db.select("select score from person where name=?")
.parameter("FRED")
.dependsOn(a)
.getAs(Integer.class)
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValues(100)
.assertComplete();
}
}
@Test
public void testUpdateWithinTransactionBatchSize0() {
try (Database db = db()) {
db
.select("select name from person")
.transactedValuesOnly()
.getAs(String.class)
.doOnNext(DatabaseTest::println)
.flatMap(tx -> tx
.update("update person set score=-1 where name=:name")
.batchSize(0)
.parameter("name", tx.value())
.valuesOnly()
.counts())
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValues(1, 1, 1)
.assertComplete();
}
}
private static void info() {
LogManager.getRootLogger().setLevel(Level.INFO);
}
private static void debug() {
LogManager.getRootLogger().setLevel(Level.INFO);
}
@Test
public void testCreateBig() {
info();
big(5).select("select count(*) from person")
.getAs(Integer.class)
.test().awaitDone(20, TimeUnit.SECONDS)
.assertValue(5163)
.assertComplete();
debug();
}
@Test
public void testTxWithBig() {
info();
big(1)
.select("select name from person")
.transactedValuesOnly()
.getAs(String.class)
.flatMap(tx -> tx
.update("update person set score=-1 where name=:name")
.batchSize(1)
.parameter("name", tx.value())
.valuesOnly()
.counts())
.count()
.test().awaitDone(20, TimeUnit.SECONDS)
.assertValue((long) NAMES_COUNT_BIG)
.assertComplete();
debug();
}
@Test
public void testTxWithBigInputBatchSize2000() {
info();
big(1)
.select("select name from person")
.transactedValuesOnly()
.getAs(String.class)
.flatMap(tx -> tx
.update("update person set score=-1 where name=:name")
.batchSize(2000)
.parameter("name", tx.value())
.valuesOnly()
.counts())
.count()
.test().awaitDone(20, TimeUnit.SECONDS)
.assertValue((long) NAMES_COUNT_BIG)
.assertComplete();
debug();
}
@Test
public void testInsertNullClobAndReadClobAsString() {
try (Database db = db()) {
insertNullClob(db);
db.select("select document from person_clob where name='FRED'")
.getAsOptional(String.class)
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValue(Optional.<String>empty())
.assertComplete();
}
}
private static void insertNullClob(Database db) {
db.update("insert into person_clob(name,document) values(?,?)")
.parameters("FRED", Database.NULL_CLOB)
.counts()
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValue(1)
.assertComplete();
}
@Test
public void testClobMethod() {
assertEquals(Database.NULL_CLOB, Database.clob(null));
}
@Test
public void testBlobMethod() {
assertEquals(Database.NULL_BLOB, Database.blob(null));
}
@Test
public void testClobMethodPresent() {
assertEquals("a", Database.clob("a"));
}
@Test
public void testBlobMethodPresent() {
byte[] b = new byte[1];
assertEquals(b, Database.blob(b));
}
@Test
public void testDateOfBirthNullableForReadMe() {
Database.test()
.select("select date_of_birth from person where name='FRED'")
.getAsOptional(Instant.class)
.blockingForEach(DatabaseTest::println);
}
@Test
public void testInsertNullClobAndReadClobAsTuple2() {
try (Database db = db()) {
insertNullClob(db);
db.select("select document, document from person_clob where name='FRED'")
.getAs(String.class, String.class)
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValue(Tuple2.create(null, null))
.assertComplete();
}
}
@Test
public void testInsertClobAndReadClobAsString() {
try (Database db = db()) {
db.update("insert into person_clob(name,document) values(?,?)")
.parameters("FRED", "some text here")
.counts()
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValue(1)
.assertComplete();
db.select("select document from person_clob where name='FRED'")
.getAs(String.class)
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // .assertValue("some
// text
// here")
.assertComplete();
}
}
@Test
public void testInsertClobAndReadClobUsingReader() {
try (Database db = db()) {
db.update("insert into person_clob(name,document) values(?,?)")
.parameters("FRED", "some text here")
.counts()
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValue(1)
.assertComplete();
db.select("select document from person_clob where name='FRED'")
.getAs(Reader.class)
.map(r -> read(r)).test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValue("some text here")
.assertComplete();
}
}
@Test
public void testInsertBlobAndReadBlobAsByteArray() {
try (Database db = db()) {
insertPersonBlob(db);
db.select("select document from person_blob where name='FRED'")
.getAs(byte[].class)
.map(b -> new String(b))
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValue("some text here")
.assertComplete();
}
}
private static void insertPersonBlob(Database db) {
byte[] bytes = "some text here".getBytes();
db.update("insert into person_blob(name,document) values(?,?)")
.parameters("FRED", bytes)
.counts()
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValue(1)
.assertComplete();
}
@Test
public void testInsertBlobAndReadBlobAsInputStream() {
try (Database db = db()) {
byte[] bytes = "some text here".getBytes();
db.update("insert into person_blob(name,document) values(?,?)")
.parameters("FRED", new ByteArrayInputStream(bytes))
.counts()
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValue(1)
.assertComplete();
db.select("select document from person_blob where name='FRED'")
.getAs(InputStream.class)
.map(is -> read(is))
.map(b -> new String(b))
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValue("some text here")
.assertComplete();
}
}
private static String read(Reader reader) throws IOException {
StringBuffer s = new StringBuffer();
char[] ch = new char[128];
int n = 0;
while ((n = reader.read(ch)) != -1) {
s.append(ch, 0, n);
}
reader.close();
return s.toString();
}
private static byte[] read(InputStream is) throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
byte[] b = new byte[128];
int n = 0;
while ((n = is.read(b)) != -1) {
bytes.write(b, 0, n);
}
is.close();
return bytes.toByteArray();
}
private void testHealthCheck(Predicate<Connection> healthy) throws InterruptedException {
TestScheduler scheduler = new TestScheduler();
NonBlockingConnectionPool pool = Pools
.nonBlocking()
.connectionProvider(DatabaseCreator.connectionProvider())
.maxIdleTime(10, TimeUnit.MINUTES)
.idleTimeBeforeHealthCheck(0, TimeUnit.MINUTES)
.healthCheck(healthy)
.scheduler(scheduler)
.maxPoolSize(1)
.build();
try (Database db = Database.from(pool)) {
TestSubscriber<Integer> ts0 = db.select(
"select score from person where name=?")
.parameter("FRED")
.getAs(Integer.class)
.test();
ts0.assertValueCount(0)
.assertNotComplete();
scheduler.advanceTimeBy(1, TimeUnit.MINUTES);
ts0.assertValueCount(1)
.assertComplete();
TestSubscriber<Integer> ts = db.select(
"select score from person where name=?")
.parameter("FRED")
.getAs(Integer.class)
.test()
.assertValueCount(0);
log.debug("done2");
scheduler.advanceTimeBy(1, TimeUnit.MINUTES);
Thread.sleep(200);
ts.assertValueCount(1);
Thread.sleep(200);
ts.assertValue(21)
.assertComplete();
}
}
@Test
public void testShutdownBeforeUse() {
NonBlockingConnectionPool pool = Pools
.nonBlocking()
.connectionProvider(DatabaseCreator.connectionProvider())
.scheduler(Schedulers.io())
.maxPoolSize(1)
.build();
pool.close();
Database.from(pool)
.select("select score from person where name=?")
.parameter("FRED")
.getAs(Integer.class)
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertNoValues()
.assertError(PoolClosedException.class);
}
@Test
public void testFewerColumnsMappedThanAvailable() {
try (Database db = db()) {
db.select("select name, score from person where name='FRED'")
.getAs(String.class)
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValues("FRED")
.assertComplete();
}
}
@Test
public void testMoreColumnsMappedThanAvailable() {
try (Database db = db()) {
db
.select("select name, score from person where name='FRED'")
.getAs(String.class, Integer.class, String.class)
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertNoValues()
.assertError(MoreColumnsRequestedThanExistException.class);
}
}
@Test
public void testSelectTimestamp() {
try (Database db = db()) {
db
.select("select registered from person where name='FRED'")
.getAs(Long.class)
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValue(FRED_REGISTERED_TIME)
.assertComplete();
}
}
@Test
public void testSelectTimestampAsDate() {
try (Database db = db()) {
db
.select("select registered from person where name='FRED'")
.getAs(Date.class)
.map(d -> d.getTime())
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValue(FRED_REGISTERED_TIME)
.assertComplete();
}
}
@Test
public void testSelectTimestampAsInstant() {
try (Database db = db()) {
db
.select("select registered from person where name='FRED'")
.getAs(Instant.class)
.map(d -> d.toEpochMilli())
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValue(FRED_REGISTERED_TIME)
.assertComplete();
}
}
@Test
public void testUpdateCalendarParameter() {
Calendar c = GregorianCalendar.from(ZonedDateTime.parse("2017-03-25T15:37Z"));
try (Database db = db()) {
db.update("update person set registered=?")
.parameter(c)
.counts()
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValue(3)
.assertComplete();
db.select("select registered from person")
.getAs(Long.class)
.firstOrError()
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValue(c.getTimeInMillis())
.assertComplete();
}
}
@Test
public void testUpdateTimeParameter() {
try (Database db = db()) {
Time t = new Time(1234);
db.update("update person set registered=?")
.parameter(t)
.counts()
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValue(3)
.assertComplete();
db.select("select registered from person")
.getAs(Long.class)
.firstOrError()
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValue(1234L)
.assertComplete();
}
}
@Test
public void testUpdateTimestampParameter() {
try (Database db = db()) {
Timestamp t = new Timestamp(1234);
db.update("update person set registered=?")
.parameter(t)
.counts()
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValue(3)
.assertComplete();
db.select("select registered from person")
.getAs(Long.class)
.firstOrError()
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValue(1234L)
.assertComplete();
}
}
@Test
public void testUpdateSqlDateParameter() {
try (Database db = db()) {
java.sql.Date t = new java.sql.Date(1234);
db.update("update person set registered=?")
.parameter(t)
.counts()
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValue(3)
.assertComplete();
db.select("select registered from person")
.getAs(Long.class)
.firstOrError()
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
// TODO make a more accurate comparison using the current TZ
.assertValue(x -> Math.abs(x - 1234) <= TimeUnit.HOURS.toMillis(24))
.assertComplete();
}
}
@Test
public void testUpdateUtilDateParameter() {
try (Database db = db()) {
Date d = new Date(1234);
db.update("update person set registered=?")
.parameter(d)
.counts()
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValue(3)
.assertComplete();
db.select("select registered from person")
.getAs(Long.class)
.firstOrError()
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValue(1234L)
.assertComplete();
}
}
@Test
public void testUpdateTimestampAsInstant() {
try (Database db = db()) {
db.update("update person set registered=? where name='FRED'")
.parameter(Instant.ofEpochMilli(FRED_REGISTERED_TIME))
.counts()
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValue(1)
.assertComplete();
db.select("select registered from person where name='FRED'")
.getAs(Long.class)
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValue(FRED_REGISTERED_TIME)
.assertComplete();
}
}
@Test
public void testUpdateTimestampAsZonedDateTime() {
try (Database db = db()) {
db.update("update person set registered=? where name='FRED'")
.parameter(ZonedDateTime.ofInstant(Instant.ofEpochMilli(FRED_REGISTERED_TIME),
ZoneOffset.UTC.normalized()))
.counts()
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValue(1)
.assertComplete();
db.select("select registered from person where name='FRED'")
.getAs(Long.class)
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValue(FRED_REGISTERED_TIME)
.assertComplete();
}
}
@Test
public void testCompleteCompletes() {
try (Database db = db(1)) {
db
.update("update person set score=-3 where name='FRED'")
.complete()
.timeout(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.blockingAwait();
int score = db.select("select score from person where name='FRED'")
.getAs(Integer.class)
.timeout(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.blockingFirst();
assertEquals(-3, score);
}
}
@Test
public void testComplete() throws InterruptedException {
try (Database db = db(1)) {
Completable a = db
.update("update person set score=-3 where name='FRED'")
.complete();
db.update("update person set score=-4 where score = -3")
.dependsOn(a)
.counts()
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValue(1)
.assertComplete();
}
}
@Test
public void testCountsOnlyInTransaction() {
try (Database db = db()) {
db.update("update person set score = -3")
.transacted()
.countsOnly()
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValues(3)
.assertComplete();
}
}
@Test
public void testCountsInTransaction() {
try (Database db = db()) {
db.update("update person set score = -3")
.transacted()
.counts()
.doOnNext(DatabaseTest::println)
.toList()
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValue(list -> list.get(0).isValue() && list.get(0).value() == 3
&& list.get(1).isComplete() && list.size() == 2)
.assertComplete();
}
}
@Test
public void testTx() throws InterruptedException {
Database db = db(3);
Single<Tx<?>> transaction = db
.update("update person set score=-3 where name='FRED'")
.transaction();
transaction
.doOnDispose(() -> log.debug("disposing"))
.doOnSuccess(DatabaseTest::println)
.flatMapPublisher(tx -> {
log.debug("flatmapping");
return tx
.update("update person set score = -4 where score = -3")
.countsOnly()
.doOnSubscribe(s -> log.debug("subscribed"))
.doOnNext(num -> log.debug("num=" + num));
})
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertNoErrors()
.assertValue(1)
.assertComplete();
}
@Test
public void testTxAfterSelect() {
Database db = db(3);
Single<Tx<Integer>> transaction = db
.select("select score from person where name='FRED'")
.transactedValuesOnly()
.getAs(Integer.class)
.firstOrError();
transaction
.doOnDispose(() -> log.debug("disposing"))
.doOnSuccess(DatabaseTest::println)
.flatMapPublisher(tx -> {
log.debug("flatmapping");
return tx
.update("update person set score = -4 where score = ?")
.parameter(tx.value())
.countsOnly()
.doOnSubscribe(s -> log.debug("subscribed"))
.doOnNext(num -> log.debug("num=" + num));
})
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertNoErrors()
.assertValue(1)
.assertComplete();
}
@Test
public void testSingleFlatMap() {
Single.just(1).flatMapPublisher(n -> Flowable.just(1)).test(1).assertValue(1)
.assertComplete();
}
@Test
public void testAutomappedInstanceHasMeaningfulToStringMethod() {
info();
String s = Database.test()
.select("select name, score from person where name=?")
.parameterStream(Flowable.just("FRED"))
.autoMap(Person2.class)
.map(x -> x.toString())
.blockingSingle();
assertEquals("Person2[name=FRED, score=21]", s);
}
@Test
public void testAutomappedEquals() {
boolean b = Database.test()
.select("select name, score from person where name=?")
.parameterStream(Flowable.just("FRED"))
.autoMap(Person2.class)
.map(x -> x.equals(x))
.blockingSingle();
assertTrue(b);
}
@Test
public void testAutomappedDoesNotEqualNull() {
boolean b = Database.test()
.select("select name, score from person where name=?")
.parameterStream(Flowable.just("FRED"))
.autoMap(Person2.class)
.map(x -> x.equals(null))
.blockingSingle();
assertFalse(b);
}
@Test
public void testAutomappedDoesNotEqual() {
boolean b = Database.test()
.select("select name, score from person where name=?")
.parameterStream(Flowable.just("FRED"))
.autoMap(Person2.class)
.map(x -> x.equals(new Object()))
.blockingSingle();
assertFalse(b);
}
@Test
public void testAutomappedHashCode() {
Person2 p = Database.test()
.select("select name, score from person where name=?")
.parameterStream(Flowable.just("FRED"))
.autoMap(Person2.class)
.blockingSingle();
assertTrue(p.hashCode() != 0);
}
@Test
public void testAutomappedWithParametersThatProvokesMoreThanOneQuery() {
Database.test()
.select("select name, score from person where name=?")
.parameters("FRED", "FRED")
.autoMap(Person2.class)
.doOnNext(DatabaseTest::println)
.test()
.awaitDone(2000, TimeUnit.SECONDS)
.assertNoErrors()
.assertValueCount(2)
.assertComplete();
}
@Test
public void testAutomappedObjectsEqualsAndHashCodeIsDistinctOnValues() {
Database.test()
.select("select name, score from person where name=?")
.parameters("FRED", "FRED")
.autoMap(Person2.class)
.distinct()
.doOnNext(DatabaseTest::println)
.test()
.awaitDone(2000, TimeUnit.SECONDS)
.assertNoErrors()
.assertValueCount(1)
.assertComplete();
}
@Test
public void testAutomappedObjectsEqualsDifferentiatesDifferentInterfacesWithSameMethodNamesAndValues() {
PersonDistinct1 p1 = Database.test()
.select("select name, score from person where name=?")
.parameters("FRED")
.autoMap(PersonDistinct1.class)
.blockingFirst();
PersonDistinct2 p2 = Database.test()
.select("select name, score from person where name=?")
.parameters("FRED")
.autoMap(PersonDistinct2.class)
.blockingFirst();
assertNotEquals(p1, p2);
}
@Test
public void testAutomappedObjectsWhenDefaultMethodInvoked() {
// only run test if java 8
if (System.getProperty("java.version").startsWith("1.8.")) {
PersonWithDefaultMethod p = Database.test()
.select("select name, score from person where name=?")
.parameters("FRED")
.autoMap(PersonWithDefaultMethod.class)
.blockingFirst();
assertEquals("fred", p.nameLower());
}
}
@Test(expected = AutomappedInterfaceInaccessibleException.class)
public void testAutomappedObjectsWhenDefaultMethodInvokedAndIsNonPublicThrows() {
PersonWithDefaultMethodNonPublic p = Database.test()
.select("select name, score from person where name=?")
.parameters("FRED")
.autoMap(PersonWithDefaultMethodNonPublic.class)
.blockingFirst();
p.nameLower();
}
@Test
public void testBlockingDatabase() {
Database db = blocking();
db.select("select score from person where name=?")
.parameters("FRED", "JOSEPH")
.getAs(Integer.class)
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertNoErrors()
.assertValues(21, 34)
.assertComplete();
}
@Test
public void testBlockingDatabaseTransacted() {
Database db = blocking();
db.select("select score from person where name=?")
.parameters("FRED", "JOSEPH")
.transactedValuesOnly()
.getAs(Integer.class)
.map(x -> x.value())
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertNoErrors()
.assertValues(21, 34)
.assertComplete();
}
@Test
public void testBlockingDatabaseTransactedNested() {
Database db = blocking();
db.select("select score from person where name=?")
.parameters("FRED", "JOSEPH")
.transactedValuesOnly()
.getAs(Integer.class)
.flatMap(tx -> tx.select("select name from person where score=?")
.parameter(tx.value())
.valuesOnly()
.getAs(String.class))
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertNoErrors()
.assertValues("FRED", "JOSEPH")
.assertComplete();
}
@Test
public void testUsingNormalJDBCApi() {
Database db = db(1);
db.apply(con -> {
try (PreparedStatement stmt = con
.prepareStatement("select count(*) from person where name='FRED'");
ResultSet rs = stmt.executeQuery()) {
rs.next();
return rs.getInt(1);
}
})
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValue(1)
.assertComplete();
// now check that the connection was returned to the pool
db.select("select count(*) from person where name='FRED'")
.getAs(Integer.class)
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValue(1)
.assertComplete();
}
@Test
public void testUsingNormalJDBCApiCompletable() {
Database db = db(1);
db.apply(con -> {
try (PreparedStatement stmt = con
.prepareStatement("select count(*) from person where name='FRED'");
ResultSet rs = stmt.executeQuery()) {
rs.next();
}
})
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertComplete();
// now check that the connection was returned to the pool
db.select("select count(*) from person where name='FRED'")
.getAs(Integer.class)
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValue(1)
.assertComplete();
}
@Test
public void testCallableStatement() {
Database db = DatabaseCreator.createDerbyWithStoredProcs(1);
db.apply(con -> {
try (Statement stmt = con.createStatement()) {
CallableStatement st = con.prepareCall("call getPersonCount(?, ?)");
st.setInt(1, 0);
st.registerOutParameter(2, Types.INTEGER);
st.execute();
assertEquals(2, st.getInt(2));
}
}).blockingAwait(TIMEOUT_SECONDS, TimeUnit.SECONDS);
}
@Test
public void testCallableStatementReturningResultSets() {
Database db = DatabaseCreator.createDerbyWithStoredProcs(1);
db.apply(con -> {
try (Statement stmt = con.createStatement()) {
CallableStatement st = con.prepareCall("call in1out0rs2(?)");
st.setInt(1, 0);
st.execute();
ResultSet rs1 = st.getResultSet();
st.getMoreResults(Statement.KEEP_CURRENT_RESULT);
ResultSet rs2 = st.getResultSet();
rs1.next();
assertEquals("FRED", rs1.getString(1));
rs2.next();
assertEquals("SARAH", rs2.getString(1));
}
}).blockingAwait(TIMEOUT_SECONDS, TimeUnit.SECONDS);
}
@Test
public void testCallableApiNoParameters() {
Database db = DatabaseCreator.createDerbyWithStoredProcs(1);
db
.call("call zero()")
.once().test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertComplete();
}
@Test
public void testCallableApiOneInOutParameter() {
Database db = DatabaseCreator.createDerbyWithStoredProcs(1);
db
.call("call inout1(?)")
.inOut(Type.INTEGER, Integer.class)
.in(4)
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValue(5)
.assertComplete();
}
@Test
public void testCallableApiTwoInOutParameters() {
Database db = DatabaseCreator.createDerbyWithStoredProcs(1);
db
.call("call inout2(?, ?)")
.inOut(Type.INTEGER, Integer.class)
.inOut(Type.INTEGER, Integer.class)
.in(4, 10)
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValue(x -> x._1() == 5 && x._2() == 12)
.assertComplete();
}
@Test
public void testCallableApiThreeInOutParameters() {
Database db = DatabaseCreator.createDerbyWithStoredProcs(1);
db
.call("call inout3(?, ?, ?)")
.inOut(Type.INTEGER, Integer.class)
.inOut(Type.INTEGER, Integer.class)
.inOut(Type.INTEGER, Integer.class)
.in(4, 10, 13)
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValue(x -> x._1() == 5 && x._2() == 12 && x._3() == 16)
.assertComplete();
}
@Test
public void testCallableApiReturningOneOutParameter() throws InterruptedException {
Database db = DatabaseCreator.createDerbyWithStoredProcs(1);
db
.call("call in1out1(?,?)")
.in()
.out(Type.INTEGER, Integer.class)
.in(0, 10, 20)
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValues(0, 10, 20)
.assertComplete();
}
@Test
public void testCallableApiReturningTwoOutParameters() throws InterruptedException {
Database db = DatabaseCreator.createDerbyWithStoredProcs(1);
db
.call("call in1out2(?,?,?)")
.in()
.out(Type.INTEGER, Integer.class)
.out(Type.INTEGER, Integer.class)
.in(0, 10, 20)
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValueCount(3)
.assertValueAt(0, x -> x._1() == 0 && x._2() == 1)
.assertValueAt(1, x -> x._1() == 10 && x._2() == 11)
.assertValueAt(2, x -> x._1() == 20 && x._2() == 21)
.assertComplete();
}
@Test
public void testCallableApiReturningThreeOutParameters() throws InterruptedException {
Database db = DatabaseCreator.createDerbyWithStoredProcs(1);
db
.call("call in1out3(?,?,?,?)")
.in()
.out(Type.INTEGER, Integer.class)
.out(Type.INTEGER, Integer.class)
.out(Type.INTEGER, Integer.class)
.in(0, 10, 20)
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValueCount(3)
.assertValueAt(0, x -> x._1() == 0 && x._2() == 1 && x._3() == 2)
.assertValueAt(1, x -> x._1() == 10 && x._2() == 11 && x._3() == 12)
.assertValueAt(2, x -> x._1() == 20 && x._2() == 21 && x._3() == 22)
.assertComplete();
}
@Test
public void testCallableApiReturningOneResultSet() throws InterruptedException {
Database db = DatabaseCreator.createDerbyWithStoredProcs(1);
db
.call("call in0out0rs1()")
.autoMap(Person2.class)
.in(0, 10, 20)
.doOnNext(x -> {
assertTrue(x.outs().isEmpty());
})
.flatMap(x -> x.results())
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValueAt(0, p -> "FRED".equalsIgnoreCase(p.name()) && p.score() == 24)
.assertValueAt(1, p -> "SARAH".equalsIgnoreCase(p.name()) && p.score() == 26)
.assertValueAt(2, p -> "FRED".equalsIgnoreCase(p.name()) && p.score() == 24)
.assertValueAt(3, p -> "SARAH".equalsIgnoreCase(p.name()) && p.score() == 26)
.assertValueAt(4, p -> "FRED".equalsIgnoreCase(p.name()) && p.score() == 24)
.assertValueAt(5, p -> "SARAH".equalsIgnoreCase(p.name()) && p.score() == 26)
.assertValueCount(6)
.assertComplete();
}
@Test
public void testCallableApiReturningTwoResultSets() throws InterruptedException {
Database db = DatabaseCreator.createDerbyWithStoredProcs(1);
db
.call("call in1out0rs2(?)")
.in()
.autoMap(Person2.class)
.autoMap(Person2.class)
.in(0, 10, 20)
.doOnNext(x -> assertTrue(x.outs().isEmpty()))
.flatMap(x -> x.results1().zipWith(x.results2(), (y, z) -> y.name() + z.name()))
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValues("FREDSARAH", "SARAHFRED", "FREDSARAH", "SARAHFRED", "FREDSARAH",
"SARAHFRED")
.assertComplete();
}
@Test
public void testCallableApiReturningTwoResultSetsSwitchOrder1() throws InterruptedException {
Database db = DatabaseCreator.createDerbyWithStoredProcs(1);
db
.call("call in1out0rs2(?)")
.autoMap(Person2.class)
.in()
.autoMap(Person2.class)
.in(0, 10, 20)
.doOnNext(x -> assertTrue(x.outs().isEmpty()))
.flatMap(x -> x.results1().zipWith(x.results2(), (y, z) -> y.name() + z.name()))
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValues("FREDSARAH", "SARAHFRED", "FREDSARAH", "SARAHFRED", "FREDSARAH",
"SARAHFRED")
.assertComplete();
}
@Test
public void testCallableApiReturningTwoResultSetsSwitchOrder2() throws InterruptedException {
Database db = DatabaseCreator.createDerbyWithStoredProcs(1);
db
.call("call in1out0rs2(?)")
.autoMap(Person2.class)
.autoMap(Person2.class)
.in()
.in(0, 10, 20)
.doOnNext(x -> assertTrue(x.outs().isEmpty()))
.flatMap(x -> x.results1().zipWith(x.results2(), (y, z) -> y.name() + z.name()))
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValues("FREDSARAH", "SARAHFRED", "FREDSARAH", "SARAHFRED", "FREDSARAH",
"SARAHFRED")
.assertComplete();
}
@Test
public void testCallableApiReturningTwoOutputThreeResultSets() throws InterruptedException {
Database db = DatabaseCreator.createDerbyWithStoredProcs(1);
db
.call("call in0out2rs3(?, ?)")
.out(Type.INTEGER, Integer.class)
.out(Type.INTEGER, Integer.class)
.autoMap(Person2.class)
.autoMap(Person2.class)
.autoMap(Person2.class)
.in(0, 10, 20)
.doOnNext(x -> {
assertEquals(2, x.outs().size());
assertEquals(1, x.outs().get(0));
assertEquals(2, x.outs().get(1));
})
.flatMap(x -> x.results1().zipWith(x.results2(), (y, z) -> y.name() + z.name())
.zipWith(x.results3(), (y, z) -> y + z.name()))
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertNoErrors()
.assertValues("FREDSARAHFRED", "SARAHFREDSARAH", "FREDSARAHFRED", "SARAHFREDSARAH",
"FREDSARAHFRED", "SARAHFREDSARAH")
.assertComplete();
}
@Test
public void testCallableApiReturningTenOutParameters() {
Database db = DatabaseCreator.createDerbyWithStoredProcs(1);
db
.call("call out10(?,?,?,?,?,?,?,?,?,?)")
.out(Type.INTEGER, Integer.class)
.out(Type.INTEGER, Integer.class)
.out(Type.INTEGER, Integer.class)
.out(Type.INTEGER, Integer.class)
.out(Type.INTEGER, Integer.class)
.out(Type.INTEGER, Integer.class)
.out(Type.INTEGER, Integer.class)
.out(Type.INTEGER, Integer.class)
.out(Type.INTEGER, Integer.class)
.out(Type.INTEGER, Integer.class)
.in(0, 10)
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertNoErrors()
.assertValueCount(2)
.assertComplete();
}
@Test
public void testCallableApiReturningTenResultSets() {
Database db = DatabaseCreator.createDerbyWithStoredProcs(1);
db
.call("call rs10()")
.autoMap(Person2.class)
.autoMap(Person2.class)
.autoMap(Person2.class)
.autoMap(Person2.class)
.autoMap(Person2.class)
.autoMap(Person2.class)
.autoMap(Person2.class)
.autoMap(Person2.class)
.autoMap(Person2.class)
.autoMap(Person2.class)
.in(0, 10)
.doOnNext(x -> {
assertEquals(0, x.outs().size());
assertEquals(10, x.results().size());
})
// just zip the first and last result sets
.flatMap(x -> x.results(0)
.zipWith(x.results(9),
(y, z) -> ((Person2) y).name() + ((Person2) z).name()))
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertNoErrors()
.assertValues("FREDSARAH", "SARAHFRED", "FREDSARAH", "SARAHFRED")
.assertComplete();
}
@Test
public void testCallableApiReturningOneResultSetGetAs() throws InterruptedException {
Database db = DatabaseCreator.createDerbyWithStoredProcs(1);
db
.call("call in0out0rs1()")
.getAs(String.class, Integer.class)
.in(1)
.flatMap(x -> x.results())
.test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.assertValueAt(0, p -> "FRED".equalsIgnoreCase(p._1()) && p._2() == 24)
.assertValueAt(1, p -> "SARAH".equalsIgnoreCase(p._1()) && p._2() == 26)
.assertComplete();
}
@Test
public void testH2InClauseWithoutSetArray() {
db().apply(con -> {
try (PreparedStatement ps = con
.prepareStatement("select count(*) from person where name in (?, ?)")) {
ps.setString(1, "FRED");
ps.setString(2, "JOSEPH");
ResultSet rs = ps.executeQuery();
rs.next();
return rs.getInt(1);
}
}).test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS).assertComplete()
.assertValue(2);
}
@Test
@Ignore
public void testH2InClauseWithSetArray() {
db().apply(con -> {
try (PreparedStatement ps = con
.prepareStatement("select count(*) from person where name in (?)")) {
ps.setArray(1, con.createArrayOf("VARCHAR", new String[] { "FRED", "JOSEPH" }));
ResultSet rs = ps.executeQuery();
rs.next();
return rs.getInt(1);
}
}).test()
.awaitDone(TIMEOUT_SECONDS, TimeUnit.DAYS).assertComplete()
.assertValue(2);
}
public interface PersonWithDefaultMethod {
@Column
String name();
@Column
int score();
public default String nameLower() {
return name().toLowerCase();
}
}
interface PersonWithDefaultMethodNonPublic {
@Column
String name();
@Column
int score();
default String nameLower() {
return name().toLowerCase();
}
}
interface PersonDistinct1 {
@Column
String name();
@Column
int score();
}
interface PersonDistinct2 {
@Column
String name();
@Column
int score();
}
interface Score {
@Column
int score();
}
interface Person {
@Column
String name();
}
interface Person2 {
@Column
String name();
@Column
int score();
}
interface Person3 {
@Column("name")
String fullName();
@Column("score")
int examScore();
}
interface Person4 {
@Column("namez")
String fullName();
@Column("score")
int examScore();
}
interface Person5 {
@Index(1)
String fullName();
@Index(2)
int examScore();
}
interface Person6 {
@Index(1)
String fullName();
@Index(3)
int examScore();
}
interface Person7 {
@Index(1)
String fullName();
@Index(0)
int examScore();
}
interface Person8 {
@Column
int name();
}
interface Person9 {
@Column
String name();
@Index(2)
int score();
}
interface PersonNoAnnotation {
String name();
}
@Query("select name, score from person order by name")
interface Person10 {
@Column
String name();
@Column
int score();
}
}
|
package phrase;
import io.FileUtil;
import joptsimple.OptionParser;
import joptsimple.OptionSet;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintStream;
import java.util.List;
import java.util.Random;
import phrase.Corpus.Edge;
import arr.F;
public class Trainer
{
public static void main(String[] args)
{
OptionParser parser = new OptionParser();
parser.accepts("help");
parser.accepts("in").withRequiredArg().ofType(File.class);
parser.accepts("test").withRequiredArg().ofType(File.class);
parser.accepts("out").withRequiredArg().ofType(File.class);
parser.accepts("start").withRequiredArg().ofType(File.class);
parser.accepts("parameters").withRequiredArg().ofType(File.class);
parser.accepts("topics").withRequiredArg().ofType(Integer.class).defaultsTo(5);
parser.accepts("iterations").withRequiredArg().ofType(Integer.class).defaultsTo(10);
parser.accepts("threads").withRequiredArg().ofType(Integer.class).defaultsTo(0);
parser.accepts("scale-phrase").withRequiredArg().ofType(Double.class).defaultsTo(0.0);
parser.accepts("scale-context").withRequiredArg().ofType(Double.class).defaultsTo(0.0);
parser.accepts("seed").withRequiredArg().ofType(Long.class).defaultsTo(0l);
parser.accepts("convergence-threshold").withRequiredArg().ofType(Double.class).defaultsTo(1e-6);
parser.accepts("variational-bayes");
parser.accepts("alpha-emit").withRequiredArg().ofType(Double.class).defaultsTo(0.1);
parser.accepts("alpha-pi").withRequiredArg().ofType(Double.class).defaultsTo(0.01);
parser.accepts("agree");
parser.accepts("no-parameter-cache");
parser.accepts("skip-large-phrases").withRequiredArg().ofType(Integer.class).defaultsTo(5);
OptionSet options = parser.parse(args);
if (options.has("help") || !options.has("in"))
{
try {
parser.printHelpOn(System.err);
} catch (IOException e) {
System.err.println("This should never happen.");
e.printStackTrace();
}
System.exit(1);
}
int tags = (Integer) options.valueOf("topics");
int iterations = (Integer) options.valueOf("iterations");
double scale_phrase = (Double) options.valueOf("scale-phrase");
double scale_context = (Double) options.valueOf("scale-context");
int threads = (Integer) options.valueOf("threads");
double threshold = (Double) options.valueOf("convergence-threshold");
boolean vb = options.has("variational-bayes");
double alphaEmit = (vb) ? (Double) options.valueOf("alpha-emit") : 0;
double alphaPi = (vb) ? (Double) options.valueOf("alpha-pi") : 0;
int skip = (Integer) options.valueOf("skip-large-phrases");
if (options.has("seed"))
F.rng = new Random((Long) options.valueOf("seed"));
if (tags <= 1 || scale_phrase < 0 || scale_context < 0 || threshold < 0)
{
System.err.println("Invalid arguments. Try again!");
System.exit(1);
}
Corpus corpus = null;
File infile = (File) options.valueOf("in");
try {
System.out.println("Reading concordance from " + infile);
corpus = Corpus.readFromFile(FileUtil.reader(infile));
corpus.printStats(System.out);
} catch (IOException e) {
System.err.println("Failed to open input file: " + infile);
e.printStackTrace();
System.exit(1);
}
if (!options.has("agree"))
System.out.println("Running with " + tags + " tags " +
"for " + iterations + " iterations " +
((skip > 0) ? "skipping large phrases for first " + skip + " iterations " : "") +
"with scale " + scale_phrase + " phrase and " + scale_context + " context " +
"and " + threads + " threads");
else
System.out.println("Running agreement model with " + tags + " tags " +
"for " + iterations);
System.out.println();
PhraseCluster cluster = null;
Agree agree = null;
if (options.has("agree"))
agree = new Agree(tags, corpus);
else
{
cluster = new PhraseCluster(tags, corpus);
if (threads > 0) cluster.useThreadPool(threads);
if (vb) cluster.initialiseVB(alphaEmit, alphaPi);
if (options.has("no-parameter-cache"))
cluster.cacheLambda = false;
if (options.has("start"))
{
try {
System.err.println("Reading starting parameters from " + options.valueOf("start"));
cluster.loadParameters(FileUtil.reader((File)options.valueOf("start")));
} catch (IOException e) {
System.err.println("Failed to open input file: " + options.valueOf("start"));
e.printStackTrace();
}
}
}
double last = 0;
for (int i=0; i < iterations; i++)
{
double o;
if (agree != null)
o = agree.EM();
else
{
if (i < skip)
System.out.println("Skipping phrases of length > " + (i+1));
if (scale_phrase <= 0 && scale_context <= 0)
{
if (!vb)
o = cluster.EM((i < skip) ? i+1 : 0);
else
o = cluster.VBEM(alphaEmit, alphaPi);
}
else
o = cluster.PREM(scale_phrase, scale_context, (i < skip) ? i+1 : 0);
}
System.out.println("ITER: "+i+" objective: " + o);
// sometimes takes a few iterations to break the ties
if (i > 5 && Math.abs((o - last) / o) < threshold)
{
last = o;
break;
}
last = o;
}
if (cluster == null)
cluster = agree.model1;
double pl1lmax = cluster.phrase_l1lmax();
double cl1lmax = cluster.context_l1lmax();
System.out.println("\nFinal posterior phrase l1lmax " + pl1lmax + " context l1lmax " + cl1lmax);
if (options.has("out"))
{
File outfile = (File) options.valueOf("out");
try {
PrintStream ps = FileUtil.printstream(outfile);
List<Edge> test;
if (!options.has("test")) // just use the training
test = corpus.getEdges();
else
{ // if --test supplied, load up the file
infile = (File) options.valueOf("test");
System.out.println("Reading testing concordance from " + infile);
test = corpus.readEdges(FileUtil.reader(infile));
}
cluster.displayPosterior(ps, test);
ps.close();
} catch (IOException e) {
System.err.println("Failed to open either testing file or output file");
e.printStackTrace();
System.exit(1);
}
}
if (options.has("parameters"))
{
File outfile = (File) options.valueOf("parameters");
PrintStream ps;
try {
ps = FileUtil.printstream(outfile);
cluster.displayModelParam(ps);
ps.close();
} catch (IOException e) {
System.err.println("Failed to open output parameters file: " + outfile);
e.printStackTrace();
System.exit(1);
}
}
if (cluster.pool != null)
cluster.pool.shutdown();
}
}
|
package phrase;
import io.FileUtil;
import joptsimple.OptionParser;
import joptsimple.OptionSet;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintStream;
import java.util.List;
import java.util.Random;
import phrase.Corpus.Edge;
import arr.F;
public class Trainer
{
public static void main(String[] args)
{
OptionParser parser = new OptionParser();
parser.accepts("help");
parser.accepts("in").withRequiredArg().ofType(File.class);
parser.accepts("in1").withRequiredArg().ofType(File.class);
parser.accepts("test").withRequiredArg().ofType(File.class);
parser.accepts("out").withRequiredArg().ofType(File.class);
parser.accepts("start").withRequiredArg().ofType(File.class);
parser.accepts("parameters").withRequiredArg().ofType(File.class);
parser.accepts("topics").withRequiredArg().ofType(Integer.class).defaultsTo(5);
parser.accepts("iterations").withRequiredArg().ofType(Integer.class).defaultsTo(10);
parser.accepts("threads").withRequiredArg().ofType(Integer.class).defaultsTo(0);
parser.accepts("scale-phrase").withRequiredArg().ofType(Double.class).defaultsTo(0.0);
parser.accepts("scale-context").withRequiredArg().ofType(Double.class).defaultsTo(0.0);
parser.accepts("seed").withRequiredArg().ofType(Long.class).defaultsTo(0l);
parser.accepts("convergence-threshold").withRequiredArg().ofType(Double.class).defaultsTo(1e-6);
parser.accepts("variational-bayes");
parser.accepts("alpha-emit").withRequiredArg().ofType(Double.class).defaultsTo(0.1);
parser.accepts("alpha-pi").withRequiredArg().ofType(Double.class).defaultsTo(0.01);
parser.accepts("agree-direction");
parser.accepts("agree-language");
parser.accepts("no-parameter-cache");
parser.accepts("skip-large-phrases").withRequiredArg().ofType(Integer.class).defaultsTo(5);
OptionSet options = parser.parse(args);
if (options.has("help") || !options.has("in"))
{
try {
parser.printHelpOn(System.err);
} catch (IOException e) {
System.err.println("This should never happen.");
e.printStackTrace();
}
System.exit(1);
}
int tags = (Integer) options.valueOf("topics");
int iterations = (Integer) options.valueOf("iterations");
double scale_phrase = (Double) options.valueOf("scale-phrase");
double scale_context = (Double) options.valueOf("scale-context");
int threads = (Integer) options.valueOf("threads");
double threshold = (Double) options.valueOf("convergence-threshold");
boolean vb = options.has("variational-bayes");
double alphaEmit = (vb) ? (Double) options.valueOf("alpha-emit") : 0;
double alphaPi = (vb) ? (Double) options.valueOf("alpha-pi") : 0;
int skip = (Integer) options.valueOf("skip-large-phrases");
if (options.has("seed"))
F.rng = new Random((Long) options.valueOf("seed"));
if (tags <= 1 || scale_phrase < 0 || scale_context < 0 || threshold < 0)
{
System.err.println("Invalid arguments. Try again!");
System.exit(1);
}
Corpus corpus = null;
File infile = (File) options.valueOf("in");
Corpus corpus1 = null;
File infile1 = (File) options.valueOf("in1");
try {
System.out.println("Reading concordance from " + infile);
corpus = Corpus.readFromFile(FileUtil.reader(infile));
corpus.printStats(System.out);
if(options.has("in1")){
corpus1 = Corpus.readFromFile(FileUtil.reader(infile1));
corpus1.printStats(System.out);
}
} catch (IOException e) {
System.err.println("Failed to open input file: " + infile);
e.printStackTrace();
System.exit(1);
}
if (!(options.has("agree-direction")||options.has("agree-language")))
System.out.println("Running with " + tags + " tags " +
"for " + iterations + " iterations " +
((skip > 0) ? "skipping large phrases for first " + skip + " iterations " : "") +
"with scale " + scale_phrase + " phrase and " + scale_context + " context " +
"and " + threads + " threads");
else
System.out.println("Running agreement model with " + tags + " tags " +
"for " + iterations);
System.out.println();
PhraseCluster cluster = null;
Agree2Sides agree2sides = null;
Agree agree= null;
if (options.has("agree-language"))
agree2sides = new Agree2Sides(tags, corpus,corpus1);
else if (options.has("agree-direction"))
agree = new Agree(tags, corpus);
else
{
cluster = new PhraseCluster(tags, corpus);
if (threads > 0) cluster.useThreadPool(threads);
if (vb) cluster.initialiseVB(alphaEmit, alphaPi);
if (options.has("no-parameter-cache"))
cluster.cacheLambda = false;
if (options.has("start"))
{
try {
System.err.println("Reading starting parameters from " + options.valueOf("start"));
cluster.loadParameters(FileUtil.reader((File)options.valueOf("start")));
} catch (IOException e) {
System.err.println("Failed to open input file: " + options.valueOf("start"));
e.printStackTrace();
}
}
}
double last = 0;
for (int i=0; i < iterations; i++)
{
double o;
if (agree != null)
o = agree.EM();
else if(agree2sides!=null){
o = agree2sides.EM();
}
else
{
if (i < skip)
System.out.println("Skipping phrases of length > " + (i+1));
if (scale_phrase <= 0 && scale_context <= 0)
{
if (!vb)
o = cluster.EM((i < skip) ? i+1 : 0);
else
o = cluster.VBEM(alphaEmit, alphaPi);
}
else
o = cluster.PREM(scale_phrase, scale_context, (i < skip) ? i+1 : 0);
}
System.out.println("ITER: "+i+" objective: " + o);
// sometimes takes a few iterations to break the ties
if (i > 5 && Math.abs((o - last) / o) < threshold)
{
last = o;
break;
}
last = o;
}
if (cluster == null)
cluster = agree.model1;
double pl1lmax = cluster.phrase_l1lmax();
double cl1lmax = cluster.context_l1lmax();
System.out.println("\nFinal posterior phrase l1lmax " + pl1lmax + " context l1lmax " + cl1lmax);
if (options.has("out"))
{
File outfile = (File) options.valueOf("out");
try {
PrintStream ps = FileUtil.printstream(outfile);
List<Edge> test;
if (!options.has("test")) // just use the training
test = corpus.getEdges();
else
{ // if --test supplied, load up the file
infile = (File) options.valueOf("test");
System.out.println("Reading testing concordance from " + infile);
test = corpus.readEdges(FileUtil.reader(infile));
}
cluster.displayPosterior(ps, test);
ps.close();
} catch (IOException e) {
System.err.println("Failed to open either testing file or output file");
e.printStackTrace();
System.exit(1);
}
}
if (options.has("parameters"))
{
File outfile = (File) options.valueOf("parameters");
PrintStream ps;
try {
ps = FileUtil.printstream(outfile);
cluster.displayModelParam(ps);
ps.close();
} catch (IOException e) {
System.err.println("Failed to open output parameters file: " + outfile);
e.printStackTrace();
System.exit(1);
}
}
if (cluster.pool != null)
cluster.pool.shutdown();
}
}
|
import org.simgrid.msg.Msg;
import org.simgrid.msg.Host;
import org.simgrid.msg.NativeException;
import org.simgrid.msg.Task;
import org.simgrid.msg.HostFailureException;
import org.simgrid.msg.TaskCancelledException;
import org.simgrid.msg.TimeoutException;
import org.simgrid.msg.TransferFailureException;
public class Message extends Task {
public enum Type{
CR_INPUT,
ASK_FILE_INFO,
SEND_FILE_INFO,
REGISTER_FILE,
REGISTER_ACK,
DOWNLOAD_REQUEST,
SEND_FILE,
UPLOAD_REQUEST,
UPLOAD_ACK,
FINALIZE
};
private Type type;
private Host issuerHost;
private String logicalFileName;
private long logicalFileSize;
private String SEName;
public Type getType() {
return type;
}
public String getMailbox(){
return issuerHost.getName();
}
public void setIssuerHost(Host issuerHost) {
this.issuerHost = issuerHost;
}
public String getLogicalFileName() {
return logicalFileName;
}
public void setLogicalFileName(String logicalFileName) {
this.logicalFileName = logicalFileName;
}
public long getLogicalFileSize() {
return logicalFileSize;
}
public void setLogicalFileSize(long logicalFileSize) {
this.logicalFileSize = logicalFileSize;
}
public String getSEName() {
return SEName;
}
public void setSEName(String sEName) {
SEName = sEName;
}
/**
* Constructor, builds a new UPLOAD/DOWNLOAD_REQUEST message
*/
public Message(Type type, Host issuerHost, String logicalFileName,
long logicalFileSize) {
this(type, issuerHost, logicalFileName, logicalFileSize, null);
}
/**
* Constructor, builds a new ASK_FILE_INFO message
*/
public Message(Type type, Host issuerHost, String logicalFileName) {
this(type, issuerHost, logicalFileName, 0, null);
}
/**
* Constructor, builds a new SEND_FILE_INFO message
*/
public Message(Type type, String SEName, long logicalFileSize) {
this(type, null, null, logicalFileSize, SEName);
}
/**
* Constructor, builds a new FINALIZE/UPLOAD_ACK/REGISTER_ACK message
*/
public Message(Type type) {
super(type.toString(), 1, 100);
this.type = type;
this.setIssuerHost(null);
this.setLogicalFileName(null);
this.setLogicalFileSize(0);
this.setSEName(null);
}
/**
* Constructor, builds a new SEND_FILE message
*/
public Message(Type type, long logicalFileSize){
super(type.toString(), 0, logicalFileSize);
this.type = type;
this.setIssuerHost(null);
this.setLogicalFileName(null);
this.setLogicalFileSize(logicalFileSize);
this.setSEName(null);
}
/**
* Constructor, builds a new CR_INPUT/REGISTER_FILE message
*/
public Message(Type type, Host issuerHost, String logicalFileName,
long logicalFileSize, String SEName) {
// Assume that 1e6 flops are needed on receiving side to process a
// request
// Assume that a request corresponds to 100 Bytes
//TODO provide different computing and communication values depending
// on the type of message
super (type.toString(), 1e6, 100);
this.type = type;
this.setIssuerHost(issuerHost);
this.setLogicalFileName(logicalFileName);
this.setLogicalFileSize(logicalFileSize);
this.setSEName(SEName);
}
public void execute() throws HostFailureException,TaskCancelledException{
super.execute();
}
public static Message process (String mailbox) {
Message message = null;
try {
message = (Message) Task.receive(mailbox);
} catch (TransferFailureException | HostFailureException|
TimeoutException e) {
e.printStackTrace();
}
Msg.debug("Received a '" + message.type.toString() + "' message");
// Simulate the cost of the local processing of the request.
// Depends on the value set when the Message was created
try {
message.execute();
} catch (HostFailureException | TaskCancelledException e) {
Msg.error("Execution of a Message failed ...");
e.printStackTrace();
}
return message;
}
public void emit (String mailbox) {
try{
// TODO this might be made an asynchronous send
this.send(mailbox);
} catch (TransferFailureException | HostFailureException|
TimeoutException | NativeException e) {
Msg.error("Something went wrong when emitting a '" +
type.toString() +"' message to '" + mailbox + "'");
e.printStackTrace();
}
}
}
|
package com.rafkind.paintown.animator;
import java.util.*;
import java.io.*;
public class DrawState
{
private static boolean drawingEnabled;
private static Vector currentDirectoryList;
public static boolean isDrawEnabled()
{
return drawingEnabled;
}
public static void setDrawEnabled(boolean d)
{
drawingEnabled = d;
}
public static void setCurrentDirList(Vector l)
{
currentDirectoryList = l;
}
public static void setCurrentDirList(String dir)
{
// Directory List
File file = new File(dir);
if ( file.isDirectory() ){
currentDirectoryList = new Vector();
File[] all = file.listFiles();
//files.add( new File( ".." ) );
for ( int i = 0; i < all.length; i++ ){
if(all[i].getName().equals(".svn"))continue;
currentDirectoryList.addElement( dir.replaceAll("data/","") + all[ i ].getName().replaceAll("^./","") );
}
}
}
public static Vector getCurrentDirList()
{
return currentDirectoryList;
}
}
|
import java.util.List;
public class Pattern {
public String head;
public String headTag;
public String modifier;
public String modifierTag;
public Relation relation;
public Pattern mother;
public Pattern father;
public Pattern(String head, String modifier, Relation relation) {
this(head, null, modifier, null, relation);
}
public Pattern(String head, String headTag, String modifier, String modifierTag, Relation relation) {
this(head, headTag, modifier, modifierTag, relation, null, null);
}
public Pattern(String head, String headTag, String modifier, String modifierTag, Relation relation, Pattern mother, Pattern father) {
this.head = head;
this.headTag = headTag;
this.modifier = modifier;
this.modifierTag = modifierTag;
this.relation = relation;
this.mother = mother;
this.father = father;
}
public static Relation asRelation(String str) {
for (Relation relation : Relation.values()) {
if (relation.name().equalsIgnoreCase(str))
return relation;
}
return null;
}
public boolean equals(Object pattern) {
if (!(pattern instanceof Pattern)) {
return false;
}
return ((Pattern) pattern).head.equals(head)
&& ((Pattern) pattern).modifier.equals(modifier)
&& ((Pattern) pattern).relation.equals(relation);
}
public int hashCode() {
return (head + modifier + relation).hashCode();
}
@Override
public String toString() {
return head + " " + headTag + " " + modifier + " " + modifierTag + " " + relation;
}
public String toAspect() {
return head + " " + modifier;
}
public String toSentences() {
return head + " . " + modifier;
}
public boolean isPrimaryPattern() {
switch (relation) {
case amod:
return headTag.equals("NN") && modifierTag.startsWith("JJ");
case acomp:
return headTag.startsWith("VB") && modifierTag.startsWith("JJ");
case nsubj:
return headTag.startsWith("VB") && modifierTag.equals("NN")
|| headTag.startsWith("JJ") && modifierTag.equals("NN")
|| headTag.startsWith("VB") && modifierTag.startsWith("PR");
case cop:
return headTag.startsWith("JJ") && modifierTag.startsWith("VB");
case dobj:
return headTag.startsWith("VB") && modifierTag.equals("NN");
case conj_and:
return headTag.equals("NN") && modifierTag.equals("NN")
|| headTag.startsWith("JJ") && modifierTag.startsWith("JJ");
case neg:
return (headTag.startsWith("JJ") || headTag.startsWith("VB"));
case nn:
return headTag.equals("NN") && modifierTag.equals("NN");
}
return false;
}
public Pattern TryCombine(List<Pattern> patterns) {
switch (relation) {
case amod:
return TryCombineAmod();
case acomp:
return TryCombineAcomp(patterns);
case cop:
return TryCombineCop(patterns);
case dobj:
return TryCombineDobj(patterns);
case aspect:
for (Pattern pattern : patterns) {
Pattern newAspect = null;
switch (pattern.relation) {
case conj_and:
newAspect = TryCombineAspectWithConjAnd(pattern);
break;
case neg:
newAspect = TryCombineAspectWithNeg(pattern);
break;
case nn:
newAspect = TryCombineAspectWithNn(pattern);
break;
}
if (newAspect != null) {
return newAspect;
}
}
return null;
}
return null;
}
private Pattern TryCombineAspectWithNn(Pattern pattern) {
if (pattern.head == head && pattern.modifierTag.equals("NN")) {
return new Pattern(pattern.modifier + " " + head, headTag, modifier, modifierTag, Relation.aspect, this, pattern);
}
if (pattern.modifier == head && pattern.headTag.equals("NN")) {
return new Pattern(head + " " + pattern.head, headTag, modifier, modifierTag, Relation.aspect, this, pattern);
}
return null;
}
private Pattern TryCombineAspectWithNeg(Pattern pattern) {
if (pattern.head == modifier
&& (pattern.modifier.equals("not") || pattern.modifier.equals("n't"))) {
return new Pattern(head, headTag, pattern.modifier + " " + modifier, pattern.modifierTag, Relation.aspect, this, pattern);
}
return null;
}
private Pattern TryCombineAspectWithConjAnd(Pattern pattern) {
if (pattern.head == head && pattern.modifierTag.equals("NN")) {
return new Pattern(pattern.modifier, pattern.modifierTag, modifier, modifierTag, Relation.aspect, this, pattern);
}
if (pattern.head == modifier
&& (pattern.modifierTag.startsWith("JJ")
|| pattern.modifierTag.startsWith("VB"))) {
return new Pattern(head, headTag, pattern.modifier, pattern.modifierTag, Relation.aspect, this, pattern);
}
return null;
}
private Pattern TryCombineDobj(List<Pattern> patterns) {
for (Pattern pattern : patterns) {
if (pattern.relation == Pattern.Relation.nsubj
&& pattern.headTag.startsWith("VB")
&& pattern.modifierTag.startsWith("PR")
&& !pattern.modifier.equals(modifier)) {
return new Pattern(modifier, modifierTag, head, headTag, Relation.aspect, this, pattern);
}
}
return null;
}
private Pattern TryCombineCop(List<Pattern> patterns) {
for (Pattern pattern : patterns) {
if (pattern.relation == Pattern.Relation.nsubj
&& pattern.headTag.startsWith("JJ")
&& pattern.modifierTag.equals("NN")
&& pattern.head.equals(head)) {
return new Pattern(pattern.modifier, pattern.modifierTag, head, headTag, Relation.aspect, this, pattern);
}
}
return null;
}
private Pattern TryCombineAcomp(List<Pattern> patterns) {
for (Pattern pattern : patterns) {
if (pattern.relation == Pattern.Relation.nsubj
&& pattern.headTag.startsWith("VB")
&& pattern.modifierTag.equals("NN")
&& pattern.head.equals(head)) {
return new Pattern(pattern.modifier, pattern.modifierTag, modifier, modifierTag, Relation.aspect, this, pattern);
}
}
return null;
}
private Pattern TryCombineAmod() {
return new Pattern(head, headTag, modifier, modifierTag, Relation.aspect);
}
public enum Relation {
amod,
acomp,
nsubj,
cop,
dobj,
conj_and,
neg,
nn,
aspect
}
}
|
package nta.engine;
import com.google.common.collect.Lists;
import nta.catalog.TCatUtil;
import nta.catalog.TableMeta;
import nta.catalog.proto.CatalogProtos.StoreType;
import nta.catalog.statistics.StatisticsUtil;
import nta.catalog.statistics.TableStat;
import nta.engine.MasterInterfaceProtos.Command;
import nta.engine.MasterInterfaceProtos.CommandRequestProto;
import nta.engine.MasterInterfaceProtos.CommandType;
import nta.engine.MasterInterfaceProtos.QueryStatus;
import nta.engine.cluster.ClusterManager;
import nta.engine.cluster.QueryManager;
import nta.engine.cluster.WorkerCommunicator;
import nta.engine.ipc.protocolrecords.Fragment;
import nta.engine.ipc.protocolrecords.QueryUnitRequest;
import nta.engine.planner.global.QueryUnit;
import nta.engine.planner.global.ScheduleUnit;
import nta.engine.planner.logical.ExprType;
import nta.engine.planner.logical.ScanNode;
import nta.engine.query.GlobalPlanner;
import nta.engine.query.QueryUnitRequestImpl;
import nta.storage.StorageManager;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
/**
* @author jihoon
*
*/
public class QueryUnitScheduler extends Thread {
private final static int WAIT_PERIOD = 1000;
private Log LOG = LogFactory.getLog(QueryUnitScheduler.class);
private final StorageManager sm;
private final WorkerCommunicator wc;
private final GlobalPlanner planner;
private final ClusterManager cm;
private final QueryManager qm;
private final ScheduleUnit plan;
private BlockingQueue<QueryUnit> pendingQueue =
new LinkedBlockingQueue<QueryUnit>();
public QueryUnitScheduler(Configuration conf, StorageManager sm,
ClusterManager cm, QueryManager qm, WorkerCommunicator wc,
GlobalPlanner planner, ScheduleUnit plan) {
this.sm = sm;
this.cm = cm;
this.qm = qm;
this.wc = wc;
this.planner = planner;
this.plan = plan;
}
private void recursiveExecuteQueryUnit(ScheduleUnit plan)
throws Exception {
if (plan.hasChildQuery()) {
Iterator<ScheduleUnit> it = plan.getChildIterator();
while (it.hasNext()) {
recursiveExecuteQueryUnit(it.next());
}
}
if (plan.getStoreTableNode().getSubNode().getType() == ExprType.UNION) {
// union operators are not executed
} else {
LOG.info("Plan of " + plan.getId() + " : " + plan.getLogicalPlan());
qm.addScheduleUnit(plan);
switch (plan.getOutputType()) {
case HASH:
Path tablePath = sm.getTablePath(plan.getOutputName());
sm.getFileSystem().mkdirs(tablePath);
LOG.info("Table path " + sm.getTablePath(plan.getOutputName()).toString()
+ " is initialized for " + plan.getOutputName());
break;
case RANGE: // TODO - to be improved
default:
if (!sm.getFileSystem().exists(sm.getTablePath(plan.getOutputName()))) {
sm.initTableBase(null, plan.getOutputName());
LOG.info("Table path " + sm.getTablePath(plan.getOutputName()).toString()
+ " is initialized for " + plan.getOutputName());
}
}
QueryUnit[] units = planner.localize(plan, cm.getOnlineWorker().size());
String hostName;
for (QueryUnit q : units) {
hostName = cm.getProperHost(q);
if (hostName == null) {
hostName = cm.getRandomHost();
}
q.setHost(hostName);
pendingQueue.add(q);
qm.updateQueryAssignInfo(hostName, q);
}
requestPendingQueryUnits();
TableStat stat = waitForFinishScheduleUnit(plan);
TableMeta meta = TCatUtil.newTableMeta(plan.getOutputSchema(),
StoreType.CSV);
meta.setStat(stat);
sm.writeTableMeta(sm.getTablePath(plan.getOutputName()), meta);
qm.getSubQuery(units[0].getId().getSubQueryId()).setTableStat(stat);
}
}
private void requestPendingQueryUnits() throws Exception {
while (!pendingQueue.isEmpty()) {
QueryUnit q = pendingQueue.take();
List<Fragment> fragList = new ArrayList<Fragment>();
for (ScanNode scan : q.getScanNodes()) {
fragList.addAll(q.getFragments(scan.getTableId()));
}
QueryUnitRequest request = new QueryUnitRequestImpl(q.getId(), fragList,
q.getOutputName(), false, q.getLogicalPlan().toJSON());
if (q.getStoreTableNode().isLocal()) {
request.setInterQuery();
}
for (ScanNode scan : q.getScanNodes()) {
Collection<URI> fetches = q.getFetch(scan);
if (fetches != null) {
for (URI fetch : fetches) {
request.addFetch(scan.getTableId(), fetch);
}
}
}
wc.requestQueryUnit(q.getHost(), request.getProto());
LOG.info("=====================================================================");
LOG.info("QueryUnitRequest " + request.getId() + " is sent to " + (q.getHost()));
LOG.info("Fragments: " + request.getFragments());
LOG.info("QueryStep's output name " + q.getStoreTableNode().getTableName());
if (request.isInterQuery()) {
LOG.info("InterQuery is enabled");
} else {
LOG.info("InterQuery is disabled");
}
LOG.info("Fetches: " + request.getFetches());
LOG.info("=====================================================================");
}
}
private TableStat waitForFinishScheduleUnit(ScheduleUnit scheduleUnit)
throws Exception {
boolean wait = true;
QueryUnit[] units = scheduleUnit.getQueryUnits();
while (wait) {
Thread.sleep(WAIT_PERIOD);
wait = false;
for (QueryUnit unit : units) {
LOG.info("==== uid: " + unit.getId() +
" status: " + unit.getInProgressStatus() +
" left time: " + unit.getLeftTime());
if (unit.getInProgressStatus().
getStatus() != QueryStatus.FINISHED) {
unit.updateExpireTime(WAIT_PERIOD);
wait = true;
if (unit.getLeftTime() <= 0) {
// TODO: Aggregate commands and send together
// send stop
Command.Builder cmd = Command.newBuilder();
cmd.setId(unit.getId().getProto()).setType(CommandType.STOP);
wc.requestCommand(unit.getHost(),
CommandRequestProto.newBuilder().addCommand(cmd.build()).build());
requestBackupTask(unit);
unit.resetExpireTime();
}
// } else if (unit.getInProgressStatus().
// getStatus() == QueryStatus.FINISHED) {
// // TODO: Aggregate commands and send together
// Command.Builder cmd = Command.newBuilder();
// cmd.setId(unit.getId().getProto()).setType(CommandType.FINALIZE);
// wc.requestCommand(unit.getHost(),
// CommandRequestProto.newBuilder().addCommand(cmd.build()).build());
}
}
}
List<TableStat> stats = Lists.newArrayList();
for (QueryUnit unit : units ) {
stats.add(unit.getStats());
}
TableStat tableStat = StatisticsUtil.aggregate(stats);
return tableStat;
}
private void requestBackupTask(QueryUnit q) throws Exception {
FileSystem fs = sm.getFileSystem();
Path path = new Path(sm.getTablePath(q.getOutputName()),
q.getId().toString());
fs.delete(path, true);
String prevHost = q.getHost();
String hostName = cm.getProperHost(q);
if (hostName == null ||
hostName.equals(prevHost)) {
hostName = cm.getRandomHost();
}
q.setHost(hostName);
LOG.info("QueryUnit " + q.getId() + " is assigned to " +
q.getHost() + " as the backup task");
pendingQueue.add(q);
requestPendingQueryUnits();
}
@Override
public void run() {
try {
long before = System.currentTimeMillis();
recursiveExecuteQueryUnit(this.plan);
long after = System.currentTimeMillis();
LOG.info("executeQuery processing time: " + (after - before) + "msc");
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
package cs4295.memecreator;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import cs4295.customView.SandboxView;
public class MemeEditorActivity extends Activity {
private MemeEditorActivity selfRef;
private SharedPreferences setting;
private LinearLayout linlaHeaderProgress;
private float memeEditorLayoutWidth;
private float memeEditorLayoutHeight;
private LinearLayout tutorial;
private LinearLayout memeEditorLayout;
private SandboxView sandboxView;
private ImageView forwardButtonImageView;
private Bitmap memeBitmap;
private File cacheImage_forPassing;
private File myDir;
private String dataDir;
private boolean firsttimes;
private boolean tutorialPreference;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setProgressBarIndeterminateVisibility(true);
setContentView(R.layout.activity_meme_editor);
selfRef = this;
// Set the actioin bar style
ActionBar actionBar = getActionBar();
actionBar.setBackgroundDrawable(new ColorDrawable(getResources()
.getColor(R.color.action_bar_color)));
actionBar.setIcon(R.drawable.back_icon_black);
actionBar.setHomeButtonEnabled(true);
int titleId = Resources.getSystem().getIdentifier("action_bar_title",
"id", "android");
TextView yourTextView = (TextView) findViewById(titleId);
yourTextView.setTextColor(getResources().getColor(R.color.black));
// Transparent bar on android 4.4 or above
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Window window = getWindow();
// Translucent status bar
window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
// Translucent navigation bar
window.setFlags(
WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION,
WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
}
// Initialize progress bar
linlaHeaderProgress = (LinearLayout) findViewById(R.id.linlaHeaderProgress);
linlaHeaderProgress.bringToFront();
// Initialize tutorial
setting = PreferenceManager
.getDefaultSharedPreferences(MemeEditorActivity.this);
SharedPreferences prefre = getSharedPreferences("Meme_Pref",
Context.MODE_PRIVATE);
firsttimes = prefre.getBoolean("Meme_Pref", true);
tutorialPreference = setting.getBoolean("Tutor_Preference", false);
SharedPreferences.Editor firstTimeEditor = prefre.edit();
// See if tutorial is needed to be shown
tutorial = (LinearLayout) findViewById(R.id.meme_editor_tutorial);
tutorial.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
tutorial.setVisibility(View.GONE);
tutorial.setEnabled(false);
}
});
if (firsttimes) {
tutorial.bringToFront();
firstTimeEditor.putBoolean("Meme_Pref", false);
firstTimeEditor.commit();
} else if (tutorialPreference) {
tutorial.bringToFront();
tutorialPreference = setting.getBoolean("Tutor_Preference", false);
} else {
tutorial.setVisibility(View.GONE);
tutorial.setEnabled(false);
}
// Get the data directory for the app
PackageManager m = getPackageManager();
dataDir = getPackageName();
try {
PackageInfo p = m.getPackageInfo(dataDir, 0);
dataDir = p.applicationInfo.dataDir;
myDir = new File(dataDir + "/cache");
if (!myDir.exists())
myDir.mkdirs();
if (myDir.setWritable(true))
Log.i("meme", "myDir is writable");
else
Log.i("meme", "myDir is not writable");
} catch (NameNotFoundException e) {
Log.w("yourtag", "Error Package name not found ", e);
}
// Get the intent and get the image path to be the meme image
Intent shareIntent = getIntent();
String imagePath = shareIntent
.getStringExtra("cs4295.memcreator.imagePath");
// Create the SandboxView
setting = PreferenceManager
.getDefaultSharedPreferences(MemeEditorActivity.this);
final int memeSize = Integer.valueOf(setting.getString("image_size",
"720"));
Log.i("meme", "memeSize = " + memeSize);
memeEditorLayout = (LinearLayout) findViewById(R.id.memeEditorLayout);
memeEditorLayout.setGravity(Gravity.CENTER);
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
Log.i("path", bitmap.toString());
sandboxView = new SandboxView(this, bitmap);
sandboxView.setLayoutParams(new LayoutParams(memeSize, memeSize));
// Scale the sand box and add it into the layout
ViewTreeObserver viewTreeObserver = memeEditorLayout
.getViewTreeObserver();
// For getting the width and height of a dynamic layout during onCreate
viewTreeObserver
.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
memeEditorLayout.getViewTreeObserver()
.removeGlobalOnLayoutListener(this);
memeEditorLayoutWidth = memeEditorLayout.getHeight();
memeEditorLayoutHeight = memeEditorLayout.getWidth();
float scalingFactor = memeEditorLayoutWidth
/ (float) memeSize;
Log.i("memeEditorLayoutWidth",
Float.toString(memeEditorLayoutWidth));
Log.i("ScaleFactor", Float.toString(scalingFactor));
sandboxView.setScaleX(scalingFactor);
sandboxView.setScaleY(scalingFactor);
}
});
memeEditorLayout.addView(sandboxView);
// Set save button on click method
forwardButtonImageView = (ImageView) findViewById(R.id.forwardButtonImage);
forwardButtonImageView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
forwardButtonImageView.setEnabled(false);
Forward forward = new Forward();
forward.execute();
}
});
}
// Delete a files
private void deleteFile(File file) {
Log.i("deleteFile", file.toString()
+ ((file.exists()) ? " is Exist." : "is not exist!!!!"));
// Check if the file exist
if (file.exists())
// Clear the file inside if it is a directory
if (file.isDirectory()) {
String[] children = file.list();
for (int i = 0; i < children.length; i++) {
File f = new File(file, children[i]);
if (f.delete())
Log.i("deleteFile", f.getAbsolutePath()
+ " is deleted....");
else
Log.i("deleteFile", f.getAbsolutePath()
+ " is not deleted!!!!");
}
}
}
@Override
protected void onPause() {
// Hide the progress bar
linlaHeaderProgress.setVisibility(View.GONE);
forwardButtonImageView.setEnabled(true);
super.onPause();
}
@Override
protected void onResume() {
super.onResume();
sandboxView.setEnabled(true);
}
@Override
protected void onDestroy() {
// Try to delete cache if possible
deleteFile(myDir);
bp_release();
super.onDestroy();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.meme_editor, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case R.id.reset_sandbox:
sandboxView.reset();
return true;
case R.id.action_settings:
Intent intent = new Intent(selfRef, SettingsActivity.class);
startActivity(intent);
return true;
case android.R.id.home:
// When the action bar icon on the top right is clicked, finish this
// activity
this.finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// save image to a specific places
private void saveImage() {
// Create the file path and file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
String fname = timeStamp + ".png";
cacheImage_forPassing = new File(myDir, fname);
// Remove duplicates
if (cacheImage_forPassing.exists())
cacheImage_forPassing.delete();
// Try save the bitmap
try {
FileOutputStream out = new FileOutputStream(cacheImage_forPassing);
memeBitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
Log.i("memeCacheLocation", cacheImage_forPassing.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
// Async task for onClick
class Forward extends AsyncTask<Object, Object, Object> {
// Before forwarding
@Override
protected void onPreExecute() {
super.onPreExecute();
linlaHeaderProgress.setVisibility(View.VISIBLE);
linlaHeaderProgress.bringToFront();
}
// Forwarding
@Override
protected String doInBackground(Object... arg0) {
Intent forward = new Intent(selfRef, SaveResultImageActivity.class);
sandboxView.setDrawingCacheEnabled(true);
sandboxView.buildDrawingCache();
memeBitmap = Bitmap.createBitmap(sandboxView.getDrawingCache());
saveImage();
forward.putExtra("cs4295.memcreator.memeImageCache",
cacheImage_forPassing.getPath());
startActivity(forward);
sandboxView.setDrawingCacheEnabled(false);
return "DONE";
}
// After forwarding
@Override
protected void onPostExecute(Object result) {
linlaHeaderProgress.setVisibility(View.GONE);
super.onPostExecute(result);
}
}
// Clear the Bitmap from memory
private void bp_release() {
if (memeBitmap != null && !memeBitmap.isRecycled()) {
memeBitmap.recycle();
memeBitmap = null;
}
}
}
|
package com.google.cordova.plugin;
import java.util.Iterator;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.LinearLayoutSoftKeyboardDetect;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import com.google.ads.Ad;
import com.google.ads.AdListener;
import com.google.ads.AdRequest;
import com.google.ads.AdRequest.ErrorCode;
import com.google.ads.AdSize;
import com.google.ads.doubleclick.DfpAdView;
import com.google.ads.doubleclick.DfpInterstitialAd;
import com.google.ads.mediation.admob.AdMobAdapterExtras;
/**
* This class represents the native implementation for the AdMob Cordova plugin.
* This plugin can be used to request AdMob ads natively via the Google AdMob
* SDK. The Google AdMob SDK is a dependency for this plugin.
*/
public class AdMobPlugin extends CordovaPlugin {
/** The adView to display to the user. */
private DfpAdView adView;
private DfpInterstitialAd intertitial;
/** Whether or not the ad should be positioned at top or bottom of screen. */
private boolean positionAtTop;
/** Common tag used for logging statements. */
private static final String LOGTAG = "AdMobPlugin";
/** Cordova Actions. */
public static final String ACTION_CREATE_BANNER_VIEW = "createBannerView";
public static final String ACTION_CREATE_INTERSTITIAL_VIEW = "createInterstitialView";
public static final String ACTION_REQUEST_AD = "requestAd";
public static final String KILL_AD = "killAd";
/**
* This is the main method for the AdMob plugin. All API calls go through
* here. This method determines the action, and executes the appropriate
* call.
*
* @param action
* The action that the plugin should execute.
* @param inputs
* The input parameters for the action.
* @param callbackId
* The callback ID. This is currently unused.
* @return A PluginResult representing the result of the provided action. A
* status of INVALID_ACTION is returned if the action is not
* recognized.
*/
@Override
public boolean execute(String action, JSONArray inputs,
CallbackContext callbackContext) throws JSONException {
if (ACTION_CREATE_BANNER_VIEW.equals(action)) {
executeCreateBannerView(inputs, callbackContext);
return true;
} else if (ACTION_CREATE_INTERSTITIAL_VIEW.equals(action)) {
executeCreateInterstitialView(inputs, callbackContext);
return true;
} else if (ACTION_REQUEST_AD.equals(action)) {
executeRequestAd(inputs, callbackContext);
return true;
} else if (KILL_AD.equals(action)) {
executeKillAd(callbackContext);
return true;
} else {
Log.d(LOGTAG, String.format("Invalid action passed: %s", action));
callbackContext.error("Invalid Action");
}
return false;
}
/**
* Parses the create banner view input parameters and runs the create banner
* view action on the UI thread. If this request is successful, the
* developer should make the requestAd call to request an ad for the banner.
*
* @param inputs
* The JSONArray representing input parameters. This function
* expects the first object in the array to be a JSONObject with
* the input parameters.
* @return A PluginResult representing whether or not the banner was created
* successfully.
*/
private void executeCreateBannerView(JSONArray inputs, CallbackContext callbackContext) {
String publisherId = "";
String size = "";
// Get the input data.
try {
JSONObject data = inputs.getJSONObject(0);
publisherId = data.getString("publisherId");
size = data.getString("adSize");
this.positionAtTop = data.getBoolean("positionAtTop");
Log.w(LOGTAG, "executeCreateBannerView OK");
Log.w(LOGTAG, "size: " + size);
Log.w(LOGTAG, "publisherId: " + publisherId);
Log.w(LOGTAG, "positionAtTop: " + (this.positionAtTop ? "true" : "false"));
} catch (JSONException exception) {
Log.w(LOGTAG,
String.format("Got JSON Exception: %s",
exception.getMessage()));
callbackContext.error(exception.getMessage());
}
AdSize adSize = adSizeFromSize(size);
createBannerView(publisherId, adSize, callbackContext);
}
private synchronized void createBannerView(final String publisherId,
final AdSize adSize, final CallbackContext callbackContext) {
final CordovaInterface cordova = this.cordova;
// Create the AdView on the UI thread.
Log.w(LOGTAG, "createBannerView");
Runnable runnable = new Runnable() {
public void run() {
Log.w(LOGTAG, "run");
Log.w(LOGTAG, String.valueOf(webView));
// Log.w(LOGTAG, "adSize::" + adSize); calling adSize.toString() with SmartBanner == crash
if (adSize == null) {
callbackContext
.error("AdSize is null. Did you use an AdSize constant?");
return;
} else {
adView = new DfpAdView(cordova.getActivity(), adSize,
publisherId);
adView.setAdListener(new BannerListener());
LinearLayoutSoftKeyboardDetect parentView = (LinearLayoutSoftKeyboardDetect) webView
.getParent();
if (positionAtTop) {
parentView.addView(adView, 0);
} else {
parentView.addView(adView);
}
// Notify the plugin.
callbackContext.success();
}
}
};
this.cordova.getActivity().runOnUiThread(runnable);
}
/**
* Parses the create banner view input parameters and runs the create banner
* view action on the UI thread. If this request is successful, the
* developer should make the requestAd call to request an ad for the banner.
*
* @param inputs
* The JSONArray representing input parameters. This function
* expects the first object in the array to be a JSONObject with
* the input parameters.
* @return A PluginResult representing whether or not the banner was created
* successfully.
*/
private void executeCreateInterstitialView(JSONArray inputs, CallbackContext callbackContext) {
String publisherId = "";
// Get the input data.
try {
JSONObject data = inputs.getJSONObject(0);
publisherId = data.getString("publisherId");
Log.w(LOGTAG, "executeCreateInterstitialView OK");
} catch (JSONException exception) {
Log.w(LOGTAG, String.format("Got JSON Exception: %s", exception.getMessage()));
callbackContext.error(exception.getMessage());
}
createInterstitialView(publisherId, callbackContext);
}
private synchronized void createInterstitialView(final String publisherId, final CallbackContext callbackContext) {
final CordovaInterface cordova = this.cordova;
// Create the AdView on the UI thread.
Log.w(LOGTAG, "createInterstitialView");
Runnable runnable = new Runnable() {
public void run() {
intertitial = new DfpInterstitialAd(cordova.getActivity(), publisherId);
intertitial.setAdListener(new BannerListener());
// Notify the plugin.
callbackContext.success();
}
};
this.cordova.getActivity().runOnUiThread(runnable);
}
/**
* Parses the request ad input parameters and runs the request ad action on
* the UI thread.
*
* @param inputs
* The JSONArray representing input parameters. This function
* expects the first object in the array to be a JSONObject with
* the input parameters.
* @return A PluginResult representing whether or not an ad was requested
* succcessfully. Listen for onReceiveAd() and onFailedToReceiveAd()
* callbacks to see if an ad was successfully retrieved.
*/
private void executeRequestAd(JSONArray inputs,
CallbackContext callbackContext) {
boolean isTesting = false;
JSONObject inputExtras = null;
// Get the input data.
try {
JSONObject data = inputs.getJSONObject(0);
isTesting = data.getBoolean("isTesting");
inputExtras = data.getJSONObject("extras");
Log.w(LOGTAG, "executeRequestAd OK");
// callbackContext.success();
// return true;
} catch (JSONException exception) {
Log.w(LOGTAG,
String.format("Got JSON Exception: %s",
exception.getMessage()));
callbackContext.error(exception.getMessage());
}
// Request an ad on the UI thread.
if (adView != null) {
requestAd(isTesting, inputExtras, callbackContext);
} else if (intertitial != null) {
requestIntertitial(isTesting, inputExtras, callbackContext);
} else {
callbackContext
.error("adView && intertitial are null. Did you call createBannerView?");
return;
}
}
private synchronized void requestIntertitial(final boolean isTesting,
final JSONObject inputExtras, final CallbackContext callbackContext) {
Log.w(LOGTAG, "requestIntertitial");
// Create the AdView on the UI thread.
Runnable runnable = new Runnable() {
@SuppressWarnings("unchecked")
public void run() {
if (intertitial == null) {
callbackContext
.error("intertitial is null. Did you call createBannerView?");
return;
} else {
AdRequest request = new AdRequest();
if (isTesting) {
// This will request test ads on the emulator only. You
// can
// get your
// hashed device ID from LogCat when making a live
// request.
// Pass
// this hashed device ID to addTestDevice request test
// ads
// on your
// device.
request.addTestDevice(AdRequest.TEST_EMULATOR);
}
AdMobAdapterExtras extras = new AdMobAdapterExtras();
Iterator<String> extrasIterator = inputExtras.keys();
boolean inputValid = true;
while (extrasIterator.hasNext()) {
String key = extrasIterator.next();
try {
extras.addExtra(key, inputExtras.get(key));
} catch (JSONException exception) {
Log.w(LOGTAG, String.format(
"Caught JSON Exception: %s",
exception.getMessage()));
callbackContext.error("Error grabbing extras");
inputValid = false;
}
}
if (inputValid) {
// extras.addExtra("cordova", 1);
// request.setNetworkExtras(extras);
intertitial.loadAd(request);
// Notify the plugin.
callbackContext.success();
}
}
}
};
this.cordova.getActivity().runOnUiThread(runnable);
}
private synchronized void requestAd(final boolean isTesting,
final JSONObject inputExtras, final CallbackContext callbackContext) {
Log.w(LOGTAG, "requestAd");
// Create the AdView on the UI thread.
Runnable runnable = new Runnable() {
@SuppressWarnings("unchecked")
public void run() {
if (adView == null) {
callbackContext
.error("AdView is null. Did you call createBannerView?");
return;
} else {
AdRequest request = new AdRequest();
if (isTesting) {
// This will request test ads on the emulator only. You
// can
// get your
// hashed device ID from LogCat when making a live
// request.
// Pass
// this hashed device ID to addTestDevice request test
// ads
// on your
// device.
request.addTestDevice(AdRequest.TEST_EMULATOR);
}
AdMobAdapterExtras extras = new AdMobAdapterExtras();
Iterator<String> extrasIterator = inputExtras.keys();
boolean inputValid = true;
while (extrasIterator.hasNext()) {
String key = extrasIterator.next();
try {
extras.addExtra(key, inputExtras.get(key));
} catch (JSONException exception) {
Log.w(LOGTAG, String.format(
"Caught JSON Exception: %s",
exception.getMessage()));
callbackContext.error("Error grabbing extras");
inputValid = false;
}
}
if (inputValid) {
// extras.addExtra("cordova", 1);
// request.setNetworkExtras(extras);
adView.loadAd(request);
// Notify the plugin.
callbackContext.success();
}
}
}
};
this.cordova.getActivity().runOnUiThread(runnable);
}
private void executeKillAd(final CallbackContext callbackContext) {
final Runnable runnable = new Runnable() {
public void run() {
if (adView == null) {
// Notify the plugin.
callbackContext.error("AdView is null. Did you call createBannerView or already destroy it?");
} else {
LinearLayoutSoftKeyboardDetect parentView = (LinearLayoutSoftKeyboardDetect) webView
.getParent();
parentView.removeView(adView);
adView.removeAllViews();
adView.destroy();
adView = null;
callbackContext.success();
}
}
};
this.cordova.getActivity().runOnUiThread(runnable);
}
/**
* This class implements the AdMob ad listener events. It forwards the
* events to the JavaScript layer. To listen for these events, use:
*
* document.addEventListener('onReceiveAd', function());
* document.addEventListener('onFailedToReceiveAd', function(data));
* document.addEventListener('onPresentScreen', function());
* document.addEventListener('onDismissScreen', function());
* document.addEventListener('onLeaveApplication', function());
*/
private class BannerListener implements AdListener {
@Override
public void onReceiveAd(Ad ad) {
if (ad == intertitial) {
intertitial.show();
}
webView.loadUrl("javascript:cordova.fireDocumentEvent('onReceiveAd');");
}
@Override
public void onFailedToReceiveAd(Ad ad, ErrorCode errorCode) {
webView.loadUrl(String
.format("javascript:cordova.fireDocumentEvent('onFailedToReceiveAd', { 'error': '%s' });",
errorCode));
}
@Override
public void onPresentScreen(Ad ad) {
webView.loadUrl("javascript:cordova.fireDocumentEvent('onPresentScreen');");
}
@Override
public void onDismissScreen(Ad ad) {
webView.loadUrl("javascript:cordova.fireDocumentEvent('onDismissScreen');");
}
@Override
public void onLeaveApplication(Ad ad) {
webView.loadUrl("javascript:cordova.fireDocumentEvent('onLeaveApplication');");
}
}
@Override
public void onDestroy() {
if (adView != null) {
adView.destroy();
}
super.onDestroy();
}
/**
* Gets an AdSize object from the string size passed in from JavaScript.
* Returns null if an improper string is provided.
*
* @param size
* The string size representing an ad format constant.
* @return An AdSize object used to create a banner.
*/
public static AdSize adSizeFromSize(String size) {
if ("BANNER".equals(size)) {
return AdSize.BANNER;
} else if ("IAB_MRECT".equals(size)) {
return AdSize.IAB_MRECT;
} else if ("IAB_BANNER".equals(size)) {
return AdSize.IAB_BANNER;
} else if ("IAB_LEADERBOARD".equals(size)) {
return AdSize.IAB_LEADERBOARD;
} else if ("SMART_BANNER".equals(size)) {
return AdSize.SMART_BANNER;
} else {
return null;
}
}
}
|
package roart.util;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import roart.config.ConfigConstants;
import roart.model.MemoryItem;
import roart.model.ResultMeta;
import roart.pipeline.PipelineConstants;
import roart.service.ControlService;
public class ServiceUtil {
private static Logger log = LoggerFactory.getLogger(ServiceUtil.class);
final private static String TP = "TP";
final private static String TN = "TN";
final private static String FP = "FP";
final private static String FN = "FN";
private static String INC = "Inc";
private static String DEC = "Dec";
public static void doRecommender(String market, Integer offset, String aDate) throws Exception {
long time0 = System.currentTimeMillis();
ControlService srv = new ControlService();
srv.getConfig();
srv.conf.setMarket(market);
List<String> stocks = srv.getDates(market);
if (aDate != null) {
int index = stocks.indexOf(aDate);
if (index >= 0) {
offset = stocks.size() - index;
}
}
int futuredays = (int) srv.conf.getTestIndicatorRecommenderComplexFutureDays();
String baseDateStr = stocks.get(stocks.size() - 1 - futuredays - offset);
String futureDateStr = stocks.get(stocks.size() - 1 - offset);
//System.out.println("da " + + futuredays + " " + baseDateStr);
SimpleDateFormat dt = new SimpleDateFormat(Constants.MYDATEFORMAT);
Date baseDate = dt.parse(baseDateStr);
Date futureDate = dt.parse(futureDateStr);
srv.conf.setdate(baseDate);
srv.getTestRecommender(true);
srv.conf.configValueMap.put(ConfigConstants.PREDICTORS, Boolean.FALSE);
srv.conf.configValueMap.put(ConfigConstants.MACHINELEARNING, Boolean.FALSE);
Map<String, Map<String, Object>> maps = srv.getContent();
Map recommendMaps = maps.get(PipelineConstants.AGGREGATORRECOMMENDERINDICATOR);
//System.out.println("m3 " + recommendMaps.keySet());
if (recommendMaps == null) {
return;
}
Integer category = (Integer) recommendMaps.get(PipelineConstants.CATEGORY);
String categoryTitle = (String) recommendMaps.get(PipelineConstants.CATEGORYTITLE);
Map<String, Map<String, List<Double>>> resultMap = (Map<String, Map<String, List<Double>>>) recommendMaps.get(PipelineConstants.RESULT);
//System.out.println("m4 " + resultMap.keySet());
if (resultMap == null) {
return;
}
Map<String, List<Double>> recommendBuySell = resultMap.get("complex");
//System.out.println("m5 " + recommendBuySell.keySet());
Set<Double> buyset = new HashSet<>();
Set<Double> sellset = new HashSet<>();
for (String key : recommendBuySell.keySet()) {
List<Double> vals = recommendBuySell.get(key);
if (vals.get(0) != null) {
buyset.add(vals.get(0));
}
if (vals.get(1) != null) {
sellset.add(vals.get(1));
}
}
double buyMedian = median(buyset);
double sellMedian = median(sellset);
srv.conf.setdate(futureDate);
Map<String, Map<String, Object>> result = srv.getContent();
Map<String, List<List<Double>>> categoryValueMap = (Map<String, List<List<Double>>>) result.get("" + category).get(PipelineConstants.LIST);
//System.out.println("k2 " + categoryValueMap.keySet());
int usedsec = (int) ((System.currentTimeMillis() - time0) / 1000);
calculateRecommender(market, futuredays, baseDate, futureDate, categoryTitle, recommendBuySell, buyMedian,
sellMedian, result, categoryValueMap, usedsec);
try {
//result.config = MyPropertyConfig.instance();
} catch (Exception e) {
log.error(roart.util.Constants.EXCEPTION, e);
}
}
private static void calculateRecommender(String market, int futuredays, Date baseDate, Date futureDate,
String categoryTitle, Map<String, List<Double>> recommendBuySell, double buyMedian, double sellMedian,
Map<String, Map<String, Object>> result, Map<String, List<List<Double>>> categoryValueMap, Integer usedsec) throws Exception {
Set<Double> changeSet = new HashSet<>();
for (String key : categoryValueMap.keySet()) {
List<List<Double>> resultList = categoryValueMap.get(key);
List<Double> mainList = resultList.get(0);
if (mainList != null) {
Double valFuture = mainList.get(mainList.size() - 1);
Double valNow = mainList.get(mainList.size() -1 - futuredays);
if (valFuture != null && valNow != null) {
Double change = valFuture / valNow;
changeSet.add(change);
}
}
}
Double medianChange = median(changeSet);
long goodBuy = 0;
long goodSell = 0;
long totalBuy = 0;
long totalSell = 0;
for (String key : categoryValueMap.keySet()) {
List<List<Double>> resultList = categoryValueMap.get(key);
List<Double> mainList = resultList.get(0);
Double change = null;
if (mainList != null) {
Double valFuture = mainList.get(mainList.size() - 1);
Double valNow = mainList.get(mainList.size() -1 - futuredays);
if (valFuture != null && valNow != null) {
change = valFuture / valNow;
}
}
if (change == null) {
continue;
}
List<Double> vals = recommendBuySell.get(key);
if (vals == null) {
continue;
}
Double buy = vals.get(0);
Double sell = vals.get(1);
if (buy != null) {
totalBuy++;
if (buy > buyMedian && change > medianChange) {
goodBuy++;
}
}
if (sell != null) {
totalSell++;
if (sell > sellMedian && change < medianChange) {
goodSell++;
}
}
}
MemoryItem buyMemory = new MemoryItem();
buyMemory.setMarket(market);
buyMemory.setRecord(new Date());
buyMemory.setDate(baseDate);
buyMemory.setUsedsec(usedsec);
buyMemory.setFuturedays(futuredays);
buyMemory.setFuturedate(futureDate);
buyMemory.setComponent(PipelineConstants.AGGREGATORRECOMMENDERINDICATOR);
buyMemory.setSubcomponent("buy");
buyMemory.setCategory(categoryTitle);
buyMemory.setPositives(goodBuy);
buyMemory.setSize(totalBuy);
buyMemory.setConfidence((double) goodBuy / totalBuy);
buyMemory.save();
MemoryItem sellMemory = new MemoryItem();
sellMemory.setMarket(market);
sellMemory.setRecord(new Date());
sellMemory.setDate(baseDate);
sellMemory.setUsedsec(usedsec);
sellMemory.setFuturedays(futuredays);
sellMemory.setFuturedate(futureDate);
sellMemory.setComponent(PipelineConstants.AGGREGATORRECOMMENDERINDICATOR);
sellMemory.setSubcomponent("sell");
sellMemory.setCategory(categoryTitle);
sellMemory.setPositives(goodSell);
sellMemory.setSize(totalSell);
sellMemory.setConfidence((double) goodSell / totalSell);
sellMemory.save();
//System.out.println("testing buy " + goodBuy + " " + totalBuy + " sell " + goodSell + " " + totalSell);
//System.out.println("k3 " + categoryValueMap.get("VIX"));
//System.out.println(result.get("Index").keySet());
System.out.println(buyMemory);
System.out.println(sellMemory);
}
public static void doPredict(String market, Integer offset, String aDate) throws Exception {
long time0 = System.currentTimeMillis();
ControlService srv = new ControlService();
srv.getConfig();
srv.conf.setMarket(market);
List<String> stocks = srv.getDates(market);
if (aDate != null) {
int index = stocks.indexOf(aDate);
if (index >= 0) {
offset = stocks.size() - index;
}
}
int futuredays = (int) srv.conf.getPredictorLSTMHorizon();
String baseDateStr = stocks.get(stocks.size() - 1 - futuredays - offset);
String futureDateStr = stocks.get(stocks.size() - 1 - offset);
//System.out.println("da " + + futuredays + " " + baseDateStr);
SimpleDateFormat dt = new SimpleDateFormat(Constants.MYDATEFORMAT);
Date baseDate = dt.parse(baseDateStr);
Date futureDate = dt.parse(futureDateStr);
srv.conf.setdate(baseDate);
srv.conf.configValueMap.put(ConfigConstants.AGGREGATORSINDICATOR, Boolean.FALSE);
srv.conf.configValueMap.put(ConfigConstants.AGGREGATORSINDICATOREXTRAS, "");
srv.conf.configValueMap.put(ConfigConstants.AGGREGATORSINDICATORRECOMMENDER, Boolean.FALSE);
srv.conf.configValueMap.put(ConfigConstants.PREDICTORS, Boolean.TRUE);
srv.conf.configValueMap.put(ConfigConstants.MACHINELEARNING, Boolean.TRUE);
srv.conf.configValueMap.put(ConfigConstants.INDICATORSMACD, Boolean.FALSE);
Map<String, Map<String, Object>> result0 = srv.getContent();
Map<String, Map<String, Object>> maps = result0;
if (maps == null) {
return;
}
//System.out.println("mapkey " + maps.keySet());
//System.out.println(maps.get("-1").keySet());
//System.out.println(maps.get("-2").keySet());
//System.out.println(maps.get("Index").keySet());
String wantedCat = getWantedCategory(maps, PipelineConstants.LSTM);
if (wantedCat == null) {
return;
}
Map map = (Map) maps.get(wantedCat).get(PipelineConstants.LSTM);
//System.out.println("lstm " + map.keySet());
Integer category = (Integer) map.get(PipelineConstants.CATEGORY);
String categoryTitle = (String) map.get(PipelineConstants.CATEGORYTITLE);
Map<String, List<Double>> resultMap = (Map<String, List<Double>>) map.get(PipelineConstants.RESULT);
srv.conf.setdate(futureDate);
srv.conf.configValueMap.put(ConfigConstants.PREDICTORS, Boolean.FALSE);
srv.conf.configValueMap.put(ConfigConstants.MACHINELEARNING, Boolean.FALSE);
Map<String, Map<String, Object>> result = srv.getContent();
Map<String, List<List<Double>>> categoryValueMap = (Map<String, List<List<Double>>>) result.get("" + category).get(PipelineConstants.LIST);
//System.out.println("k2 " + categoryValueMap.keySet());
int usedsec = (int) ((System.currentTimeMillis() - time0) / 1000);
calculatePredictor(market, futuredays, baseDate, futureDate, categoryTitle, resultMap, categoryValueMap, usedsec);
try {
//result.config = MyPropertyConfig.instance();
} catch (Exception e) {
log.error(roart.util.Constants.EXCEPTION, e);
}
}
private static void calculatePredictor(String market, int futuredays, Date baseDate, Date futureDate,
String categoryTitle, Map<String, List<Double>> resultMap,
Map<String, List<List<Double>>> categoryValueMap, Integer usedsec) throws Exception {
long total = 0;
long goodInc = 0;
long goodDec = 0;
for (String key : categoryValueMap.keySet()) {
List<List<Double>> resultList = categoryValueMap.get(key);
List<Double> mainList = resultList.get(0);
if (mainList != null) {
Double valFuture = mainList.get(mainList.size() - 1);
Double valNow = mainList.get(mainList.size() -1 - futuredays);
List<Double> predFutureList = resultMap.get(key);
if (predFutureList == null) {
continue;
}
Double predFuture = predFutureList.get(0);
if (valFuture != null && valNow != null && predFuture != null) {
total++;
if (valFuture > valNow && predFuture > valNow) {
goodInc++;
}
if (valFuture < valNow && predFuture < valNow) {
goodDec++;
}
}
}
}
//System.out.println("tot " + total + " " + goodInc + " " + goodDec);
MemoryItem incMemory = new MemoryItem();
incMemory.setMarket(market);
incMemory.setRecord(new Date());
incMemory.setDate(baseDate);
incMemory.setUsedsec(usedsec);
incMemory.setFuturedays(futuredays);
incMemory.setFuturedate(futureDate);
incMemory.setComponent(ConfigConstants.PREDICTORS);
incMemory.setSubcomponent("inc");
incMemory.setCategory(categoryTitle);
incMemory.setPositives(goodInc);
incMemory.setSize(total);
incMemory.setConfidence((double) goodInc / total);
incMemory.save();
MemoryItem decMemory = new MemoryItem();
decMemory.setMarket(market);
decMemory.setRecord(new Date());
decMemory.setDate(baseDate);
decMemory.setUsedsec(usedsec);
decMemory.setFuturedays(futuredays);
decMemory.setFuturedate(futureDate);
decMemory.setComponent(ConfigConstants.PREDICTORS);
decMemory.setSubcomponent("dec");
decMemory.setCategory(categoryTitle);
decMemory.setPositives(goodDec);
decMemory.setSize(total);
decMemory.setConfidence((double) goodDec / total);
decMemory.save();
System.out.println(incMemory);
System.out.println(decMemory);
}
public static void doMLMACD(String market, Integer offset, String aDate) throws ParseException {
long time0 = System.currentTimeMillis();
ControlService srv = new ControlService();
srv.getConfig();
srv.conf.setMarket(market);
List<String> stocks = srv.getDates(market);
if (aDate != null) {
int index = stocks.indexOf(aDate);
if (index >= 0) {
offset = stocks.size() - index;
}
}
int daysafterzero = (int) srv.conf.getMACDDaysAfterZero();
String baseDateStr = stocks.get(stocks.size() - 1 - 1 * daysafterzero - offset);
String futureDateStr = stocks.get(stocks.size() - 1 - 0 * daysafterzero - offset);
//System.out.println("da " + + daysafterzero + " " + baseDateStr);
SimpleDateFormat dt = new SimpleDateFormat(Constants.MYDATEFORMAT);
Date baseDate = dt.parse(baseDateStr);
Date futureDate = dt.parse(futureDateStr);
srv.conf.setdate(baseDate);
srv.conf.configValueMap.put(ConfigConstants.AGGREGATORSINDICATOR, Boolean.FALSE);
srv.conf.configValueMap.put(ConfigConstants.AGGREGATORSINDICATOREXTRAS, "");
srv.conf.configValueMap.put(ConfigConstants.AGGREGATORSINDICATORRECOMMENDER, Boolean.FALSE);
srv.conf.configValueMap.put(ConfigConstants.PREDICTORS, Boolean.FALSE);
srv.conf.configValueMap.put(ConfigConstants.MACHINELEARNING, Boolean.TRUE);
srv.conf.configValueMap.put(ConfigConstants.AGGREGATORSMLMACD, Boolean.TRUE);
Map<String, Map<String, Object>> result0 = srv.getContent();
Map<String, Map<String, Object>> maps = result0;
//System.out.println("mapkey " + maps.keySet());
//System.out.println(maps.get("-1").keySet());
//System.out.println(maps.get("-2").keySet());
//System.out.println(maps.get("Index").keySet());
Map mlMACDMaps = (Map) maps.get(PipelineConstants.MLMACD);
//System.out.println("mlm " + mlMACDMaps.keySet());
Integer category = (Integer) mlMACDMaps.get(PipelineConstants.CATEGORY);
String categoryTitle = (String) mlMACDMaps.get(PipelineConstants.CATEGORYTITLE);
Map<String, List<Object>> resultMap = (Map<String, List<Object>>) mlMACDMaps.get(PipelineConstants.RESULT);
if (resultMap == null) {
return;
}
Map<String, List<Double>> probabilityMap = (Map<String, List<Double>>) mlMACDMaps.get(PipelineConstants.PROBABILITY);
List<List> resultMetaArray = (List<List>) mlMACDMaps.get(PipelineConstants.RESULTMETAARRAY);
//List<ResultMeta> resultMeta = (List<ResultMeta>) mlMACDMaps.get(PipelineConstants.RESULTMETA);
List<Object> objectList = (List<Object>) mlMACDMaps.get(PipelineConstants.RESULTMETA);
List<ResultMeta> resultMeta = new ObjectMapper().convertValue(objectList, new TypeReference<List<ResultMeta>>() { });
//System.out.println("m4 " + resultMetaArray);
//System.out.println("m4 " + resultMap.keySet());
//System.out.println("m4 " + probabilityMap.keySet());
srv.conf.setdate(futureDate);
srv.conf.configValueMap.put(ConfigConstants.PREDICTORS, Boolean.FALSE);
srv.conf.configValueMap.put(ConfigConstants.MACHINELEARNING, Boolean.FALSE);
Map<String, Map<String, Object>> result = srv.getContent();
Map<String, List<List<Double>>> categoryValueMap = (Map<String, List<List<Double>>>) result.get("" + category).get(PipelineConstants.LIST);
//System.out.println("k2 " + categoryValueMap.keySet());
try {
// TODO add more offset
// TODO verify dates and offsets
int usedsec = (int) ((System.currentTimeMillis() - time0) / 1000);
calculateMLMACD(market, daysafterzero, baseDate, futureDate, categoryTitle, resultMap, resultMetaArray,
categoryValueMap, resultMeta, offset, usedsec);
//result.config = MyPropertyConfig.instance();
} catch (Exception e) {
log.error(roart.util.Constants.EXCEPTION, e);
}
}
private static void calculateMLMACD(String market, int daysafterzero, Date baseDate, Date futureDate,
String categoryTitle, Map<String, List<Object>> resultMap, List<List> resultMetaArray,
Map<String, List<List<Double>>> categoryValueMap, List<ResultMeta> resultMeta, int offset, Integer usedsec) throws Exception {
int resultIndex = 0;
int count = 0;
for (List meta : resultMetaArray) {
MemoryItem memory = new MemoryItem();
int returnSize = (int) meta.get(2);
Double testaccuracy = (Double) meta.get(6);
Map<String, List<Double>> offsetMap = (Map<String, List<Double>>) meta.get(8);
/*
Map<String, Integer> countMapLearn = (Map<String, Integer>) meta.get(5);
Map<String, Integer> countMapClass = (Map<String, Integer>) meta.get(7);
*/
Map<String, Integer> countMapLearn = (Map<String, Integer>) resultMeta.get(count).getLearnMap();
Map<String, Integer> countMapClass = (Map<String, Integer>) resultMeta.get(count).getClassifyMap();
long total = 0;
long goodTP = 0;
long goodFP = 0;
long goodTN = 0;
long goodFN = 0;
long tpSize = 0;
long fpSize = 0;
long tnSize = 0;
long fnSize = 0;
double goodTPprob = 0;
double goodFPprob = 0;
double goodTNprob = 0;
double goodFNprob = 0;
int size = resultMap.values().iterator().next().size();
for (String key : categoryValueMap.keySet()) {
if (key.equals("VIX")) {
int jj = 0;
}
List<List<Double>> resultList = categoryValueMap.get(key);
List<Double> mainList = resultList.get(0);
if (mainList == null) {
continue;
}
List<Object> list = resultMap.get(key);
if (list == null) {
continue;
}
String tfpn = (String) list.get(resultIndex);
if (tfpn == null) {
continue;
}
List<Double> off = offsetMap.get(key);
if (off == null) {
log.error("The offset should not be null for " + key);
continue;
}
int offsetZero = (int) Math.round(off.get(0));
Double valFuture = mainList.get(mainList.size() - 1 - offset - offsetZero);
Double valNow = mainList.get(mainList.size() - 1 - daysafterzero - offset - offsetZero);
Double tfpnProb = null;
if (returnSize > 1) {
tfpnProb = (Double) list.get(resultIndex + 1);
}
if (valFuture != null && valNow != null) {
//System.out.println("vals " + key + " " + valNow + " " + valFuture);
total++;
if (tfpn.equals(TP)) {
tpSize++;
if (valFuture > valNow ) {
goodTP++;
if (returnSize > 1) {
goodTPprob += tfpnProb;
}
}
}
if (tfpn.equals(FP)) {
fpSize++;
if (valFuture < valNow) {
goodFP++;
if (returnSize > 1) {
goodFPprob += tfpnProb;
}
}
}
if (tfpn.equals(TN)) {
tnSize++;
if (valFuture < valNow) {
goodTN++;
if (returnSize > 1) {
goodTNprob += tfpnProb;
}
}
}
if (tfpn.equals(FN)) {
fnSize++;
if (valFuture > valNow) {
goodFN++;
if (returnSize > 1) {
goodFNprob += tfpnProb;
}
}
}
}
}
//System.out.println("tot " + total + " " + goodTP + " " + goodFP + " " + goodTN + " " + goodFN);
memory.setMarket(market);
memory.setRecord(new Date());
memory.setDate(baseDate);
memory.setUsedsec(usedsec);
memory.setFuturedays(daysafterzero);
memory.setFuturedate(futureDate);
memory.setComponent(PipelineConstants.MLMACD);
memory.setCategory(categoryTitle);
memory.setSubcomponent(meta.get(0) + ", " + meta.get(1) + ", " + meta.get(3) + ", " + meta.get(4));
memory.setTestaccuracy(testaccuracy);
//memory.setPositives(goodInc);
memory.setTp(goodTP);
memory.setFp(goodFP);
memory.setTn(goodTN);
memory.setFn(goodFN);
if (returnSize > 1) {
memory.setTpProb(goodTPprob);
memory.setFpProb(goodFPprob);
memory.setTnProb(goodTNprob);
memory.setFnProb(goodFNprob);
Double goodTPprobConf = goodTP != 0 ? goodTPprob / goodTP : null;
Double goodFPprobConf = goodFP != 0 ? goodFPprob / goodFP : null;
Double goodTNprobConf = goodTN != 0 ? goodTNprob / goodTN : null;
Double goodFNprobConf = goodFN != 0 ? goodFNprob / goodFN : null;
memory.setTpProbConf(goodTPprobConf);
memory.setFpProbConf(goodFPprobConf);
memory.setTnProbConf(goodTNprobConf);
memory.setFnProbConf(goodFNprobConf);
}
Integer tpClassOrig = countMapClass.containsKey(TP) ? countMapClass.get(TP) : 0;
Integer tnClassOrig = countMapClass.containsKey(TN) ? countMapClass.get(TN) : 0;
Integer fpClassOrig = countMapClass.containsKey(FP) ? countMapClass.get(FP) : 0;
Integer fnClassOrig = countMapClass.containsKey(FN) ? countMapClass.get(FN) : 0;
Integer tpSizeOrig = countMapLearn.containsKey(TP) ? countMapLearn.get(TP) : 0;
Integer tnSizeOrig = countMapLearn.containsKey(TN) ? countMapLearn.get(TN) : 0;
Integer fpSizeOrig = countMapLearn.containsKey(FP) ? countMapLearn.get(FP) : 0;
Integer fnSizeOrig = countMapLearn.containsKey(FN) ? countMapLearn.get(FN) : 0;
boolean doTP = countMapLearn.containsKey(TP);
boolean doFP = countMapLearn.containsKey(FP);
boolean doTN = countMapLearn.containsKey(TN);
boolean doFN = countMapLearn.containsKey(FN);
int keys = 0;
if (doTP) {
keys++;
}
if (doFP) {
keys++;
}
if (doTN) {
keys++;
}
if (doFN) {
keys++;
}
Integer totalClass = tpClassOrig + tnClassOrig + fpClassOrig + fnClassOrig;
Integer totalSize = tpSizeOrig + tnSizeOrig + fpSizeOrig + fnSizeOrig;
Double learnConfidence = 0.0;
learnConfidence = keys != 0 && totalClass != 0 && totalSize != 0 ? (double) (
( doTP ? Math.abs((double) tpClassOrig / totalClass - (double) tpSizeOrig / totalSize) : 0) +
( doFP ? Math.abs((double) fpClassOrig / totalClass - (double) fpSizeOrig / totalSize) : 0) +
( doTN ? Math.abs((double) tnClassOrig / totalClass - (double) tnSizeOrig / totalSize) : 0) +
( doFN ? Math.abs((double) fnClassOrig / totalClass - (double) fnSizeOrig / totalSize) : 0)
) / keys : null;
String info = null;
if (tpSizeOrig != null) {
info = "Classified / learned: ";
info += "TP " + tpClassOrig + " / " + tpSizeOrig + ", ";
info += "TN " + tnClassOrig + " / " + tnSizeOrig + ", ";
info += "FP " + fpClassOrig + " / " + fpSizeOrig + ", ";
info += "FN " + fnClassOrig + " / " + fnSizeOrig + " ";
}
memory.setInfo(info);
memory.setTpSize(tpSize);
memory.setTnSize(tnSize);
memory.setFpSize(fpSize);
memory.setFnSize(fnSize);
Double tpConf = (tpSize != 0 ? ((double) goodTP / tpSize) : null);
Double tnConf = (tnSize != 0 ? ((double) goodTN / tnSize) : null);
Double fpConf = (fpSize != 0 ? ((double) goodFP / fpSize) : null);
Double fnConf = (fnSize != 0 ? ((double) goodFN / fnSize) : null);
memory.setTpConf(tpConf);
memory.setTnConf(tnConf);
memory.setFpConf(fpConf);
memory.setFnConf(fnConf);
memory.setSize(total);
Double conf = total != 0 ? ((double) goodTP + goodTN + goodFP + goodFN) / total : null;
memory.setPositives(goodTP + goodTN + goodFP + goodFN);
memory.setConfidence(conf);
memory.setLearnConfidence(learnConfidence);
memory.setPosition(count);
memory.save();
System.out.println(memory);
resultIndex += returnSize;
count++;
}
}
public static void doMLIndicator(String market, Integer offset, String aDate) throws ParseException {
long time0 = System.currentTimeMillis();
ControlService srv = new ControlService();
srv.getConfig();
srv.conf.setMarket(market);
List<String> stocks = srv.getDates(market);
if (aDate != null) {
int index = stocks.indexOf(aDate);
if (index >= 0) {
offset = stocks.size() - index;
}
}
int futuredays = (int) srv.conf.getAggregatorsIndicatorFuturedays();
double threshold = srv.conf.getAggregatorsIndicatorThreshold();
String baseDateStr = stocks.get(stocks.size() - 1 - futuredays - offset);
String futureDateStr = stocks.get(stocks.size() - 1 - offset);
//System.out.println("da " + + futuredays + " " + baseDateStr);
SimpleDateFormat dt = new SimpleDateFormat(Constants.MYDATEFORMAT);
Date baseDate = dt.parse(baseDateStr);
Date futureDate = dt.parse(futureDateStr);
srv.conf.setdate(baseDate);
//srv.getTestRecommender(true);
srv.conf.configValueMap.put(ConfigConstants.AGGREGATORSINDICATOR, Boolean.TRUE);
srv.conf.configValueMap.put(ConfigConstants.AGGREGATORSINDICATOREXTRAS, "");
srv.conf.configValueMap.put(ConfigConstants.AGGREGATORSINDICATORRECOMMENDER, Boolean.FALSE);
srv.conf.configValueMap.put(ConfigConstants.PREDICTORS, Boolean.FALSE);
srv.conf.configValueMap.put(ConfigConstants.MACHINELEARNING, Boolean.TRUE);
Map<String, Map<String, Object>> result0 = srv.getContent();
Map<String, Map<String, Object>> maps = result0;
//System.out.println("mapkey " + maps.keySet());
//System.out.println(maps.get("-1").keySet());
//System.out.println(maps.get("-2").keySet());
//System.out.println(maps.get("Index").keySet());
Map mlIndicatorMaps = (Map) maps.get(PipelineConstants.MLINDICATOR);
//System.out.println("mli " + mlIndicatorMaps.keySet());
Integer category = (Integer) mlIndicatorMaps.get(PipelineConstants.CATEGORY);
String categoryTitle = (String) mlIndicatorMaps.get(PipelineConstants.CATEGORYTITLE);
Map<String, List<Object>> resultMap = (Map<String, List<Object>>) mlIndicatorMaps.get(PipelineConstants.RESULT);
Map<String, List<Double>> probabilityMap = (Map<String, List<Double>>) mlIndicatorMaps.get(PipelineConstants.PROBABILITY);
List<Object[]> resultMetaArray = (List<Object[]>) mlIndicatorMaps.get(PipelineConstants.RESULTMETAARRAY);
List<Object> objectList = (List<Object>) mlIndicatorMaps.get(PipelineConstants.RESULTMETA);
List<ResultMeta> resultMeta = new ObjectMapper().convertValue(objectList, new TypeReference<List<ResultMeta>>() { });
//System.out.println("m4 " + resultMap.keySet());
//System.out.println("m4 " + probabilityMap.keySet());
if (resultMap == null) {
return;
}
int size = resultMap.values().iterator().next().size();
Map<String, Object>[] aMap = new HashMap[size];
for (int i = 0; i < size; i++) {
aMap[i] = new HashMap<>();
}
for (String key : resultMap.keySet()) {
List<Object> list = resultMap.get(key);
for (int i = 0; i < size; i++) {
if (list.get(i) != null) {
aMap[i].put(key, list.get(i));
}
}
}
srv.conf.setdate(futureDate);
srv.conf.configValueMap.put(ConfigConstants.PREDICTORS, Boolean.FALSE);
srv.conf.configValueMap.put(ConfigConstants.MACHINELEARNING, Boolean.FALSE);
Map<String, Map<String, Object>> result = srv.getContent();
Map<String, List<List<Double>>> categoryValueMap = (Map<String, List<List<Double>>>) result.get("" + category).get(PipelineConstants.LIST);
//System.out.println("k2 " + categoryValueMap.keySet());
try {
int usedsec = (int) ((System.currentTimeMillis() - time0) / 1000);
calculateMLindicator(market, futuredays, baseDate, futureDate, threshold, resultMap, size, categoryValueMap, resultMeta, categoryTitle, usedsec);
//result.config = MyPropertyConfig.instance();
} catch (Exception e) {
log.error(roart.util.Constants.EXCEPTION, e);
}
}
private static void calculateMLindicator(String market, int futuredays, Date baseDate, Date futureDate, double threshold,
Map<String, List<Object>> resultMap, int size0, Map<String, List<List<Double>>> categoryValueMap, List<ResultMeta> resultMeta, String categoryTitle, Integer usedsec) throws Exception {
int resultIndex = 0;
int count = 0;
for (ResultMeta meta : resultMeta) {
MemoryItem memory = new MemoryItem();
int returnSize = (int) meta.getReturnSize();
Double testaccuracy = (Double) meta.getTestAccuracy();
//Map<String, double[]> offsetMap = (Map<String, double[]>) meta.get(8);
/*
Map<String, Integer> countMapLearn = (Map<String, Integer>) meta.get(5);
Map<String, Integer> countMapClass = (Map<String, Integer>) meta.get(7);
*/
Map<String, Integer> countMapLearn = (Map<String, Integer>) resultMeta.get(count).getLearnMap();
Map<String, Integer> countMapClass = (Map<String, Integer>) resultMeta.get(count).getClassifyMap();
long total = 0;
long goodTP = 0;
long goodFP = 0;
long goodTN = 0;
long goodFN = 0;
long incSize = 0;
//long fpSize = 0;
long decSize = 0;
//long fnSize = 0;
double goodTPprob = 0;
double goodFPprob = 0;
double goodTNprob = 0;
double goodFNprob = 0;
int size = resultMap.values().iterator().next().size();
for (String key : categoryValueMap.keySet()) {
List<List<Double>> resultList = categoryValueMap.get(key);
List<Double> mainList = resultList.get(0);
if (mainList == null) {
continue;
}
//int offset = (int) offsetMap.get(key)[0];
Double valFuture = mainList.get(mainList.size() - 1);
Double valNow = mainList.get(mainList.size() - 1 - futuredays);
if (valFuture == null || valNow == null) {
continue;
}
boolean incThreshold = (valFuture / valNow - 1) >= threshold;
List<Object> list = resultMap.get(key);
if (list == null) {
continue;
}
String incdec = (String) list.get(resultIndex);
if (incdec == null) {
continue;
}
Double incdecProb = null;
if (returnSize > 1) {
incdecProb = (Double) list.get(resultIndex + 1);
}
total++;
if (incdec.equals(INC)) {
incSize++;
if (incThreshold) {
goodTP++;
if (returnSize > 1) {
goodTPprob += incdecProb;
}
} else {
goodFP++;
if (returnSize > 1) {
goodFPprob += (1 - incdecProb); }
}
}
if (incdec.equals(DEC)) {
decSize++;
if (!incThreshold) {
goodTN++;
if (returnSize > 1) {
goodTNprob += incdecProb;
}
} else {
goodFN++;
if (returnSize > 1) {
goodFNprob += (1 - incdecProb);
}
}
}
}
//System.out.println("tot " + total + " " + goodTP + " " + goodFP + " " + goodTN + " " + goodFN);
memory.setMarket(market);
memory.setRecord(new Date());
memory.setDate(baseDate);
memory.setUsedsec(usedsec);
memory.setFuturedays(futuredays);
memory.setFuturedate(futureDate);
memory.setComponent(PipelineConstants.MLINDICATOR);
memory.setCategory(categoryTitle);
memory.setSubcomponent(meta.getMlName() + ", " + meta.getModelName() + ", " + meta.getSubType() + ", " + meta.getSubSubType());
memory.setTestaccuracy(testaccuracy);
//memory.setPositives(goodInc);
memory.setTp(goodTP);
memory.setFp(goodFP);
memory.setTn(goodTN);
memory.setFn(goodFN);
if (returnSize > 1) {
memory.setTpProb(goodTPprob);
memory.setFpProb(goodFPprob);
memory.setTnProb(goodTNprob);
memory.setFnProb(goodFNprob);
Double goodTPprobConf = goodTPprob / goodTP;
Double goodFPprobConf = goodFPprob / goodFP;
Double goodTNprobConf = goodTNprob / goodTN;
Double goodFNprobConf = goodFNprob / goodFN;
memory.setTpProbConf(goodTPprobConf);
memory.setFpProbConf(goodFPprobConf);
memory.setTnProbConf(goodTNprobConf);
memory.setFnProbConf(goodFNprobConf);
}
Integer tpClassOrig = countMapClass.containsKey(INC) ? countMapClass.get(INC) : 0;
Integer tnClassOrig = countMapClass.containsKey(DEC) ? countMapClass.get(DEC) : 0;
//Integer fpClassOrig = goodTP - ;
//Integer fnClassOrig = countMapClass.containsKey(FN) ? countMapClass.get(FN) : 0;
Integer tpSizeOrig = countMapLearn.containsKey(INC) ? countMapLearn.get(INC) : 0;
Integer tnSizeOrig = countMapLearn.containsKey(DEC) ? countMapLearn.get(DEC) : 0;
//Integer fpSizeOrig = countMapLearn.containsKey(FP) ? countMapLearn.get(FP) : 0;
//Integer fnSizeOrig = countMapLearn.containsKey(FN) ? countMapLearn.get(FN) : 0;
int keys = 2;
Integer totalClass = tpClassOrig + tnClassOrig;
Integer totalSize = tpSizeOrig + tnSizeOrig;
Double learnConfidence = 0.0;
learnConfidence = (double) (
( true ? Math.abs((double) tpClassOrig / totalClass - (double) tpSizeOrig / totalSize) : 0) +
//( true ? Math.abs((double) fpClassOrig / totalClass - (double) fpSizeOrig / totalSize) : 0) +
( true ? Math.abs((double) tnClassOrig / totalClass - (double) tnSizeOrig / totalSize) : 0)
//( true ? Math.abs((double) fnClassOrig / totalClass - (double) fnSizeOrig / totalSize) : 0)
) / keys;
String info = null;
if (tpSizeOrig != null) {
info = "Classified / learned: ";
info += "TP " + tpClassOrig + " / " + tpSizeOrig + ", ";
info += "TN " + tnClassOrig + " / " + tnSizeOrig + ", ";
info += "FP " + (tpSizeOrig - tpClassOrig) + " / " + tpSizeOrig + ", ";
info += "FN " + (tnSizeOrig - tnClassOrig) + " / " + tnSizeOrig + " ";
}
memory.setInfo(info);
memory.setTpSize(incSize);
memory.setTnSize(decSize);
memory.setFpSize(incSize);
memory.setFnSize(decSize);
Double tpConf = (incSize != 0 ? ((double) goodTP / incSize) : null);
Double tnConf = (decSize != 0 ? ((double) goodTN / decSize) : null);
Double fpConf = (incSize != 0 ? ((double) goodFP / incSize) : null);
Double fnConf = (decSize != 0 ? ((double) goodFN / decSize) : null);
memory.setTpConf(tpConf);
memory.setTnConf(tnConf);
memory.setFpConf(fpConf);
memory.setFnConf(fnConf);
memory.setSize(total);
Double conf = ((double) goodTP + goodTN) / total;
memory.setPositives(goodTP + goodTN);
memory.setConfidence(conf);
memory.setLearnConfidence(learnConfidence);
memory.setPosition(count);
memory.save();
System.out.println(memory);
resultIndex += returnSize;
count++;
}
/*
int total = 0;
int goodInc = 0;
int goodDec = 0;
for (String key : categoryValueMap.keySet()) {
List<List<Double>> resultList = categoryValueMap.get(key);
List<Double> mainList = resultList.get(0);
if (mainList != null) {
Double valFuture = mainList.get(mainList.size() - 1);
Double valNow = mainList.get(mainList.size() -1 - futuredays);
List<Object> list = resultMap.get(key);
if (list == null) {
continue;
}
for (int i = 0; i < size; i++) {
String incDec = (String) list.get(i);
if (incDec == null) {
continue;
}
if (valFuture != null && valNow != null) {
double change = valFuture / valNow;
total++;
if (change >= threshold && incDec.equals("Inc")) {
goodInc++;
}
if (change < threshold && incDec.equals("Dec")) {
goodDec++;
}
}
}
}
}
*/
//System.out.println("tot " + total + " " + goodInc + " " + goodDec);
}
private static double median(Set<Double> set) {
Double[] scores = set.toArray(new Double[set.size()]);
Arrays.sort(scores);
//System.out.print("Sorted Scores: ");
for (double x : scores) {
//System.out.print(x + " ");
}
//System.out.println("");
// Calculate median (middle number)
double median = 0;
double pos1 = Math.floor((scores.length - 1.0) / 2.0);
double pos2 = Math.ceil((scores.length - 1.0) / 2.0);
if (pos1 == pos2 ) {
median = scores[(int)pos1];
} else {
median = (scores[(int)pos1] + scores[(int)pos2]) / 2.0 ;
}
return median;
}
private static double median2(Set<Double> set) {
Double[] numArray = set.toArray(new Double[set.size()]);
Arrays.sort(numArray);
Arrays.sort(numArray);
int middle = numArray.length/2;
double medianValue = 0; //declare variable
if (numArray.length%2 == 1) {
medianValue = numArray[middle];
} else {
medianValue = (numArray[middle-1] + numArray[middle]) / 2;
}
return medianValue;
}
public static String getWantedCategory(Map<String, Map<String, Object>> maps, String type) throws Exception {
List<String> wantedList = new ArrayList<>();
wantedList.add(Constants.PRICE);
wantedList.add(Constants.INDEX);
wantedList.add("cy");
String cat = null;
for (String wanted : wantedList) {
Map<String, Object> map = maps.get(wanted);
if (map != null) {
if (map.containsKey(type)) {
LinkedHashMap<String, Object> tmpMap = (LinkedHashMap<String, Object>) map.get(type);
if (tmpMap.get(PipelineConstants.RESULT) != null) {
return wanted;
}
}
}
}
return cat;
}
}
|
package com.dwarfartisan.parsec;
import org.junit.Assert;
import org.junit.Test;
import org.junit.Before;
import org.junit.After;
import java.io.EOFException;
/**
* BasicState Tester.
*
* @author <Authors name>
* @since <pre> 2, 2016</pre>
* @version 1.0
*/
public class BasicStateTest0 {
private State<Character> newState(String data) {
Character[] buffer = new Character[data.length()];
for (int i=0; i < data.length(); i++) {
buffer[i] = data.charAt(i);
}
return new BasicState<Character>(buffer);
}
@Before
public void before() throws Exception {
}
@After
public void after() throws Exception {
}
/**
*
* Method: Index()
*
*/
@Test
public void testIndex() throws Exception {
String data = "It is a \"string\" for this unit test";
State<Character> state = newState(data);
while (state.index()< data.length()){
int index = state.index();
Character c = state.next();
Character chr = data.charAt(index);
Assert.assertEquals(c, chr);
}
try{
Character failed = state.next();
Assert.fail("The state next at preview line should failed.");
} catch (EOFException e) {
Assert.assertTrue("the error is Eof", EOFException.class==e.getClass());
}
}
/**
*
* Method: Begin()
*
*/
@Test
public void testBegin() throws Exception {
State<Character> state = newState("hello");
Character c = state.next();
Assert.assertEquals(c,new Character('h'));
int a = state.begin();
c = state.next();
c = state.next();
c = state.next();
state.rollback(a);
Character d = state.next();
Assert.assertEquals(d,new Character('e'));
}
/**
*
* Method: Commit(int tran)
*
*/
@Test
public void testCommit() throws Exception {
State<Character> state = newState("hello");
int a = state.begin();
Character c = state.next();
Assert.assertEquals(c,new Character('h'));
c = state.next();
state.commit(a);
Character d = state.next();
Assert.assertEquals(d,new Character('l'));
}
/**
*
* Method: Rollback(int tran)
*
*/
@Test
public void testRollback() throws Exception {
State<Character> state = newState("hello");
int a = state.begin();
Character c = state.next();
Assert.assertEquals(c,new Character('h'));
state.rollback(a);
Character d = state.next();
Assert.assertEquals(d,new Character('h'));
}
/**
*
* Method: Next()
*
*/
@Test
public void testNext() throws Exception {
State<Character> state = newState("hello");
Character c = state.next();
Assert.assertEquals(c,new Character('h'));
Character d = state.next();
Assert.assertEquals(d,new Character('e'));
Character e = state.next();
Assert.assertEquals(e,new Character('l'));
Character f = state.next();
Assert.assertEquals(f,new Character('l'));
Character g = state.next();
Assert.assertEquals(g,new Character('o'));
}
}
|
package alien4cloud.it;
import java.beans.IntrospectionException;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import lombok.Getter;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.node.NodeBuilder;
import org.jclouds.openstack.nova.v2_0.domain.Server;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.util.PropertyPlaceholderHelper;
import alien4cloud.exception.NotFoundException;
import alien4cloud.it.exception.ITException;
import alien4cloud.it.provider.util.OpenStackClient;
import alien4cloud.json.deserializer.PropertyConstraintDeserializer;
import alien4cloud.json.deserializer.PropertyValueDeserializer;
import alien4cloud.model.application.Application;
import alien4cloud.model.common.MetaPropConfiguration;
import alien4cloud.model.components.AbstractPropertyValue;
import alien4cloud.model.components.PropertyConstraint;
import alien4cloud.model.templates.TopologyTemplate;
import alien4cloud.rest.utils.RestClient;
import alien4cloud.rest.utils.RestMapper;
import alien4cloud.utils.MapUtil;
import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import cucumber.runtime.io.ClasspathResourceLoader;
/**
* In order to communicate between different step definitions
*
* @author mkv
*
*/
@Slf4j
public class Context {
public static final String GIT_URL_SUFFIX = ".git";
public static final Path GIT_ARTIFACT_TARGET_PATH = Paths.get("target/gits");
public static final Path CSAR_TARGET_PATH = Paths.get("target/csars");
public static final String FASTCONNECT_NEXUS = "http://fastconnect.org/maven/service/local/artifact/maven/redirect?";
public static final Path LOCAL_TEST_DATA_PATH = Paths.get("src/test/resources");
public static final int SCP_PORT = 22;
public static final String HOST = "localhost";
public static final int PORT = 8088;
public static final String CONTEXT_PATH = "";
public static final String WEB_SOCKET_END_POINT = "/rest/alienEndPoint";
/** Alien's current version. */
public static final String VERSION;
private static final Context INSTANCE = new Context();
private static Client ES_CLIENT_INSTANCE;
private static RestClient REST_CLIENT_INSTANCE;
private static ObjectMapper JSON_MAPPER;
static {
YamlPropertiesFactoryBean propertiesFactoryBean = new YamlPropertiesFactoryBean();
propertiesFactoryBean.setResources(new Resource[] { new ClassPathResource("version.yml") });
Properties properties = propertiesFactoryBean.getObject();
VERSION = properties.getProperty("version");
}
public static Client getEsClientInstance() {
if (ES_CLIENT_INSTANCE == null) {
Settings settings = ImmutableSettings.settingsBuilder().put("discovery.zen.ping.multicast.enabled", false)
.put("discovery.zen.ping.unicast.hosts", "localhost").put("discovery.zen.ping.unicast.enabled", true).build();
ES_CLIENT_INSTANCE = NodeBuilder.nodeBuilder().client(true).clusterName("escluster").local(false).settings(settings).node().client();
}
return ES_CLIENT_INSTANCE;
}
public static RestClient getRestClientInstance() {
if (REST_CLIENT_INSTANCE == null) {
REST_CLIENT_INSTANCE = new RestClient("http://" + HOST + ":" + PORT + CONTEXT_PATH);
}
return REST_CLIENT_INSTANCE;
}
public static Context getInstance() {
return INSTANCE;
}
public static ObjectMapper getJsonMapper() {
if (JSON_MAPPER == null) {
JSON_MAPPER = new RestMapper();
SimpleModule module = new SimpleModule("PropDeser", new Version(1, 0, 0, null, null, null));
module.addDeserializer(AbstractPropertyValue.class, new PropertyValueDeserializer());
try {
module.addDeserializer(PropertyConstraint.class, new PropertyConstraintDeserializer());
} catch (ClassNotFoundException | IOException | IntrospectionException e) {
log.error("Unable to initialize test context.");
}
JSON_MAPPER.registerModule(module);
}
return JSON_MAPPER;
}
private final TestPropertyPlaceholderConfigurer appProps;
private String restResponseLocal;
private String csarLocal;
private Set<String> componentsIdsLocal;
private String topologyIdLocal;
private String csarIdLocal;
private TopologyTemplate topologyTemplate;
private String topologyTemplateVersionId;
private EvaluationContext spelEvaluationContext;
private Application applicationLocal;
private Map<String, String> applicationInfos;
private Map<String, String> csarGitInfos;
private Map<String, String> cloudInfos;
private String topologyCloudInfos;
private Map<String, String> deployApplicationProperties;
private Map<String, MetaPropConfiguration> configurationTags;
private String topologyDeploymentId;
private Map<String, String> groupIdToGroupNameMapping = Maps.newHashMap();
private Map<String, String> cloudImageNameToCloudImageIdMapping = Maps.newHashMap();
private Map<String, String> applicationVersionNameToApplicationVersionIdMapping = Maps.newHashMap();
private Map<String, Map<String, String>> environmentInfos;
@Getter
private OpenStackClient openStackClient;
private Context() {
ClasspathResourceLoader classpathResourceLoader = new ClasspathResourceLoader(Thread.currentThread().getContextClassLoader());
Iterable<cucumber.runtime.io.Resource> properties = classpathResourceLoader.resources("", "alien4cloud-config.yml");
List<Resource> resources = Lists.newArrayList();
for (cucumber.runtime.io.Resource property : properties) {
try {
resources.add(new InputStreamResource(property.getInputStream()));
} catch (IOException e) {
throw new ITException("Could not load properties file at [" + property.getPath() + "]", e);
}
}
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
if (resources.isEmpty()) {
resources = Lists.<Resource> newArrayList(new ClassPathResource("alien4cloud-config.yml"));
}
factory.setResources(resources.toArray(new Resource[resources.size()]));
this.appProps = new TestPropertyPlaceholderConfigurer();
this.appProps.setProperties(factory.getObject());
this.openStackClient = new OpenStackClient(this.appProps.getProperty("openstack.user"), this.appProps.getProperty("openstack.password"),
this.appProps.getProperty("openstack.tenant"), this.appProps.getProperty("openstack.url"), this.appProps.getProperty("openstack.region"));
}
private static class TestPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {
private PropertyPlaceholderHelper.PlaceholderResolver resolver;
private Properties properties;
private final PropertyPlaceholderHelper helper = new PropertyPlaceholderHelper(placeholderPrefix, placeholderSuffix, valueSeparator,
ignoreUnresolvablePlaceholders);
@SneakyThrows
public String getProperty(String key) {
if (resolver == null) {
properties = mergeProperties();
convertProperties(properties);
resolver = new PropertyPlaceholderConfigurerResolver(properties);
}
String value = this.helper.replacePlaceholders(resolvePlaceholder(key, properties, SYSTEM_PROPERTIES_MODE_FALLBACK), this.resolver);
return (value.equals(nullValue) ? null : value);
}
private class PropertyPlaceholderConfigurerResolver implements PropertyPlaceholderHelper.PlaceholderResolver {
private final Properties props;
private PropertyPlaceholderConfigurerResolver(Properties props) {
this.props = props;
}
@Override
public String resolvePlaceholder(String placeholderName) {
return TestPropertyPlaceholderConfigurer.this.resolvePlaceholder(placeholderName, props, SYSTEM_PROPERTIES_MODE_FALLBACK);
}
}
}
public void registerGroupId(String groupName, String groupId) {
groupIdToGroupNameMapping.put(groupName, groupId);
}
public String getGroupId(String groupName) {
return groupIdToGroupNameMapping.get(groupName);
}
public void registerCloudImageId(String cloudImageName, String cloudImageId) {
cloudImageNameToCloudImageIdMapping.put(cloudImageName, cloudImageId);
}
public String getCloudImageId(String cloudImageName) {
return cloudImageNameToCloudImageIdMapping.get(cloudImageName);
}
public Map<String, String> getCsarGitInfos() {
return csarGitInfos;
}
public void registerApplicationVersionId(String applicationVersionName, String applicationVersionId) {
applicationVersionNameToApplicationVersionIdMapping.put(applicationVersionName, applicationVersionId);
}
public String getApplicationVersionId(String applicationVersionName) {
return applicationVersionNameToApplicationVersionIdMapping.get(applicationVersionName);
}
public void registerRestResponse(String restResponse) {
log.debug("Registering [" + restResponse + "] in the context");
restResponseLocal = restResponse;
}
public String getRestResponse() {
return restResponseLocal;
}
public String takeRestResponse() {
String response = restResponseLocal;
restResponseLocal = null;
return response;
}
public void registerCSAR(String csarPath) {
log.debug("Registering csar [" + csarPath + "] in the context");
csarLocal = csarPath;
}
public String getCSAR() {
String csar = csarLocal;
csarLocal = null;
return csar;
}
public String getAppProperty(String key) {
return appProps.getProperty(key);
}
public Path getAlienPath() {
return Paths.get(getAppProperty("directories.alien"));
}
public Path getRepositoryDirPath() {
return Paths.get(getAlienPath() + "/" + getAppProperty("directories.csar_repository"));
}
public Path getUploadTempDirPath() {
return Paths.get(getAlienPath() + "/" + getAppProperty("directories.upload_temp"));
}
public Path getPluginDirPath() {
return Paths.get(getAlienPath() + "/" + getAppProperty("directories.plugins"));
}
public Path getArtifactDirPath() {
return Paths.get(getAlienPath() + "/" + getAppProperty("directories.artifact_repository"));
}
public Path getTmpDirectory() {
return Paths.get("target/tmp/");
}
public String getElasticSearchClusterName() {
return getAppProperty("elasticSearch.clusterName");
}
public void clearComponentsIds() {
componentsIdsLocal = null;
}
public Set<String> getComponentsIds() {
return componentsIdsLocal;
}
public Set<String> takeComponentsIds() {
Set<String> componentsIds = componentsIdsLocal;
clearComponentsIds();
return componentsIds;
}
public void registerComponentId(String componentid) {
if (componentsIdsLocal == null) {
componentsIdsLocal = new HashSet<String>();
}
log.debug("Registering componentID [" + componentid + "] in the context");
componentsIdsLocal.add(componentid);
}
public String getComponentId(String componentid) {
if (componentsIdsLocal != null && componentsIdsLocal.contains(componentid)) {
return componentid;
}
return null;
}
public String takeComponentId(String componentid) {
if (componentsIdsLocal != null && componentsIdsLocal.contains(componentid)) {
componentsIdsLocal.remove(componentid);
return componentid;
}
return null;
}
public String getComponentId(int position) {
if (componentsIdsLocal != null && componentsIdsLocal.size() >= (position - 1)) {
int index = 0;
for (String componentID : componentsIdsLocal) {
if (index == position) {
return componentID;
}
index++;
}
}
return null;
}
public String takeComponentId(int position) {
if (componentsIdsLocal != null && componentsIdsLocal.size() >= (position - 1)) {
int index = 0;
for (String componentID : componentsIdsLocal) {
if (index == position) {
componentsIdsLocal.remove(componentID);
return componentID;
}
index++;
}
}
return null;
}
public void registerTopologyId(String topologyId) {
log.debug("Registering topology Id [" + topologyId + "] in the context");
topologyIdLocal = topologyId;
}
public String getTopologyId() {
return topologyIdLocal;
}
public String takeTopologyId() {
String topoId = topologyIdLocal;
topologyIdLocal = null;
return topoId;
}
public void registerCsarId(String csarId) {
log.debug("Registering csarId Id [" + csarId + "] in the context");
csarIdLocal = csarId;
}
public String getCsarId() {
return csarIdLocal;
}
public String takeCsarId() {
String csarId = csarIdLocal;
csarIdLocal = null;
return csarId;
}
public void registerApplication(Application application) {
log.debug("Registering application [" + application.getId() + "] in the context");
applicationLocal = application;
}
public Application getApplication() {
return applicationLocal;
}
public Application takeApplication() {
Application app = applicationLocal;
applicationLocal = null;
return app;
}
public TopologyTemplate getTopologyTemplate() {
return topologyTemplate;
}
public TopologyTemplate takeTopologyTemplate() {
TopologyTemplate ttId = topologyTemplate;
topologyTemplate = null;
return ttId;
}
public void registerTopologyTemplate(TopologyTemplate topologTemplate) {
log.debug("Registering topology template [" + topologTemplate + "] in the context");
topologyTemplate = topologTemplate;
}
public EvaluationContext getSpelEvaluationContext() {
return spelEvaluationContext;
}
public void buildEvaluationContext(Object object) {
log.debug("Building evaluation context with object of class [" + object.getClass() + "] and keep it in the context");
spelEvaluationContext = new StandardEvaluationContext(object);
}
public void registerCloud(String cloudId, String cloudName) {
if (cloudInfos != null) {
cloudInfos.put(cloudName, cloudId);
return;
}
cloudInfos = MapUtil.newHashMap(new String[] { cloudName }, new String[] { cloudId });
}
public void unregisterCloud(String cloudName) {
cloudInfos.remove(cloudName);
}
public String getCloudId(String cloudName) {
return cloudInfos.get(cloudName);
}
public Collection<String> getCloudsIds() {
if (cloudInfos != null) {
return cloudInfos.values();
} else {
return Lists.newArrayList();
}
}
public void registerCloudForTopology(String cloudId) {
topologyCloudInfos = cloudId;
}
public void saveCsarGitInfos(String id, String url) {
if (this.csarGitInfos != null) {
this.csarGitInfos.put(id, url);
return;
}
this.csarGitInfos = MapUtil.newHashMap(new String[] { id }, new String[] { url });
csarGitInfos.put(id, url);
}
public String getCloudForTopology() {
return topologyCloudInfos;
}
public void registerDeployApplicationProperties(Map<String, String> deployApplicationProperties) {
this.deployApplicationProperties = deployApplicationProperties;
}
public Map<String, String> getDeployApplicationProperties() {
return deployApplicationProperties;
}
public Map<String, String> takeDeployApplicationProperties() {
Map<String, String> tmp = deployApplicationProperties;
deployApplicationProperties = null;
return tmp;
}
public void registerConfigurationTag(String configurationTagName, MetaPropConfiguration tagConfiguration) {
if (configurationTags != null) {
configurationTags.put(configurationTagName, tagConfiguration);
return;
}
configurationTags = MapUtil.newHashMap(new String[] { configurationTagName }, new MetaPropConfiguration[] { tagConfiguration });
}
public MetaPropConfiguration getConfigurationTag(String configurationTagName) {
return configurationTags.get(configurationTagName);
}
public MetaPropConfiguration takeConfigurationTag(String configurationTagName) {
return configurationTags.get(configurationTagName);
}
public Map<String, MetaPropConfiguration> getConfigurationTags() {
return configurationTags;
}
public void registerTopologyDeploymentId(String topoDeploymentId) {
topologyDeploymentId = topoDeploymentId;
}
public String getTopologyDeploymentId() {
return topologyDeploymentId;
}
public void registerApplicationEnvironmentId(String applicationName, String applicationEnvironmentName, String applicationEnvironmentId) {
Map<String, Map<String, String>> envsInfoMap = this.environmentInfos;
if (envsInfoMap != null) {
Map<String, String> envs = envsInfoMap.get(applicationName);
if (envs == null) {
envs = Maps.newHashMap();
}
envs.put(applicationEnvironmentName, applicationEnvironmentId);
envsInfoMap.put(applicationName, envs);
this.environmentInfos = envsInfoMap;
return;
}
envsInfoMap = Maps.newHashMap();
envsInfoMap.put(applicationName, MapUtil.newHashMap(new String[] { applicationEnvironmentName }, new String[] { applicationEnvironmentId }));
this.environmentInfos = envsInfoMap;
}
public String getApplicationEnvironmentId(String applicationName, String applicationEnvironmentName) {
return this.environmentInfos.get(applicationName).get(applicationEnvironmentName);
}
public Map<String, String> getAllEnvironmentForApplication(String applicationName) {
return this.environmentInfos.get(applicationName);
}
public String getDefaultApplicationEnvironmentId(String applicationName) {
return getApplicationEnvironmentId(applicationName, "Environment");
}
public void registerApplicationId(String applicationName, String applicationId) {
if (this.applicationInfos != null) {
this.applicationInfos.put(applicationName, applicationId);
return;
}
this.applicationInfos = MapUtil.newHashMap(new String[] { applicationName }, new String[] { applicationId });
}
public String getApplicationId(String applicationName) {
return this.applicationInfos.get(applicationName);
}
public void registerTopologyTemplateVersionId(String versionId) {
topologyTemplateVersionId = versionId;
}
public String getTopologyTemplateVersionId() {
return topologyTemplateVersionId;
}
private String getManagementServerPublicIp(String managerPropertyName) {
String managementServerName = getAppProperty(managerPropertyName);
Server managementServer = this.openStackClient.findServerByName(managementServerName);
if (managementServer == null) {
throw new NotFoundException("Management server is not found for cloudify 3 with name " + managementServerName);
}
String publicIp = this.openStackClient.getServerFloatingIP(managementServer).getFloatingIpAddress();
return publicIp;
}
public String getCloudify3ManagerUrl() {
return "http://" + getManagementServerPublicIp("openstack.cfy3.manager_name") + ":8100";
}
public String getCloudify2ManagerUrl() {
return "https://" + getManagementServerPublicIp("openstack.cfy2.manager_name") + ":8100";
}
}
|
import java.util.Hashtable;
import java.util.Arrays;
/**
* Every person has a profile, containing a list of cities
* containing the attractions they have rated or will be suggested
*
* @author Siena - Aidan
* @version May
*/
public class Profile
{
protected int[][] ratings = new int[100][2];
//saves the ratings of each profile example attraction
protected Hashtable<Integer, Integer> attr_ratings = new Hashtable<Integer, Integer>();
//saves the categories of those attractions and the matching rating
protected Hashtable<String, Integer> cat_ratings = new Hashtable<String, Integer>();
protected int user_id;
public Profile(int id)
{
this.user_id = id;
for (int[] p : ratings)
{
Arrays.fill(p, -1);
}
}
public Integer getCatRating(String cat) {
return cat_ratings.get(cat);
}
public Integer getAttrRating(Integer id) {
return attr_ratings.get(id);
}
}
|
package beast.evolution.substitutionmodel;
import java.util.Arrays;
import beast.core.CalculationNode;
import beast.core.Description;
import beast.core.Input;
import beast.core.Input.Validate;
import beast.core.parameter.RealParameter;
import beast.evolution.alignment.Alignment;
import beast.evolution.datatype.DataType;
// RRB: TODO: make this an interface?
@Description("Represents character frequencies typically used as distribution of the root of the tree. " +
"Calculates empirical frequencies of characters in sequence data, or simply assumes a uniform " +
"distribution if the estimate flag is set to false.")
public class Frequencies extends CalculationNode {
public Input<Alignment> dataInput = new Input<Alignment>("data", "Sequence data for which frequencies are calculated");
public Input<Boolean> estimateInput = new Input<Boolean>("estimate", "Whether to estimate the frequencies from data (true=default) or assume a uniform distribution over characters (false)", true);
public Input<RealParameter> frequenciesInput = new Input<RealParameter>("frequencies", "A set of frequencies specified as space separated values summing to 1", Validate.XOR, dataInput);
/**
* contains frequency distribution *
*/
protected double[] freqs;
/**
* flag to indicate m_fFreqs is up to date *
*/
boolean needsUpdate;
@Override
public void initAndValidate() throws Exception {
update();
double fSum = getSumOfFrequencies(getFreqs());
// sanity check
if (Math.abs(fSum - 1.0) > 1e-6) {
throw new Exception("Frequencies do not add up to 1");
}
}
/**
* return up to date frequencies *
*/
public double[] getFreqs() {
if (needsUpdate) {
update();
}
return freqs;
}
/**
* recalculate frequencies, unless it is fixed *
*/
void update() {
if (frequenciesInput.get() != null) {
// if user specified, parse frequencies from space delimited string
freqs = new double[frequenciesInput.get().getDimension()];
for (int i = 0; i < freqs.length; i++) {
freqs[i] = frequenciesInput.get().getValue(i);
}
} else if (estimateInput.get()) { // if not user specified, either estimate from data or set as fixed
// estimate
estimateFrequencies();
checkFrequencies();
} else {
// uniformly distributed
int nStates = dataInput.get().getMaxStateCount();
freqs = new double[nStates];
for (int i = 0; i < nStates; i++) {
freqs[i] = 1.0 / nStates;
}
}
needsUpdate = false;
} // update
/**
* Estimate from sequence alignment.
* This version matches the implementation in Beast 1 & PAUP *
*/
void estimateFrequencies() {
Alignment alignment = dataInput.get();
DataType dataType = alignment.getDataType();
int stateCount = alignment.getMaxStateCount();
freqs = new double[stateCount];
Arrays.fill(freqs, 1.0 / stateCount);
int nAttempts = 0;
double fDifference;
do {
double[] fTmpFreq = new double[stateCount];
double fTotal = 0.0;
for (int i = 0; i < alignment.getPatternCount(); i++) {
int[] nPattern = alignment.getPattern(i);
double fWeight = alignment.getPatternWeight(i);
for (int iValue : nPattern) {
int[] codes = dataType.getStatesForCode(iValue);
double sum = 0.0;
for (int iCode : codes) {
sum += freqs[iCode];
}
for (int iCode : codes) {
double fTmp = (freqs[iCode] * fWeight) / sum;
fTmpFreq[iCode] += fTmp;
fTotal += fTmp;
}
}
}
fDifference = 0.0;
for (int i = 0; i < stateCount; i++) {
fDifference += Math.abs((fTmpFreq[i] / fTotal) - freqs[i]);
freqs[i] = fTmpFreq[i] / fTotal;
}
nAttempts++;
} while (fDifference > 1E-8 && nAttempts < 1000);
// Alignment alignment = m_data.get();
// m_fFreqs = new double[alignment.getMaxStateCount()];
// for (int i = 0; i < alignment.getPatternCount(); i++) {
// int[] nPattern = alignment.getPattern(i);
// double fWeight = alignment.getPatternWeight(i);
// DataType dataType = alignment.getDataType();
// for (int iValue : nPattern) {
// if (iValue < 4) {
// int [] codes = dataType.getStatesForCode(iValue);
// for (int iCode : codes) {
// m_fFreqs[iCode] += fWeight / codes.length;
//// if (iValue < m_fFreqs.length) { // ignore unknowns
//// m_fFreqs[iValue] += nWeight;
// // normalize
// double fSum = 0;
// for (double f : m_fFreqs) {
// fSum += f;
// for (int i = 0; i < m_fFreqs.length; i++) {
// m_fFreqs[i] /= fSum;
System.err.println("Starting frequencies: " + Arrays.toString(freqs));
} // calcFrequencies
/**
* Ensures that frequencies are not smaller than MINFREQ and
* that two frequencies differ by at least 2*MINFDIFF.
* This avoids potential problems later when eigenvalues
* are computed.
*/
private void checkFrequencies() {
// required frequency difference
double MINFDIFF = 1.0E-10;
// lower limit on frequency
double MINFREQ = 1.0E-10;
int maxi = 0;
double sum = 0.0;
double maxfreq = 0.0;
for (int i = 0; i < freqs.length; i++) {
double freq = freqs[i];
if (freq < MINFREQ) freqs[i] = MINFREQ;
if (freq > maxfreq) {
maxfreq = freq;
maxi = i;
}
sum += freqs[i];
}
double diff = 1.0 - sum;
freqs[maxi] += diff;
for (int i = 0; i < freqs.length - 1; i++) {
for (int j = i + 1; j < freqs.length; j++) {
if (freqs[i] == freqs[j]) {
freqs[i] += MINFDIFF;
freqs[j] -= MINFDIFF;
}
}
}
} // checkFrequencies
/**
* CalculationNode implementation *
*/
@Override
protected boolean requiresRecalculation() {
boolean recalculates = false;
if (frequenciesInput.get().somethingIsDirty()) {
needsUpdate = true;
recalculates = true;
}
return recalculates;
}
/**
* @param frequencies the frequencies
* @return return the sum of frequencies
*/
private double getSumOfFrequencies(double[] frequencies) {
double total = 0.0;
for (int i = 0; i < frequencies.length; i++) {
total += frequencies[i];
}
return total;
}
public void restore() {
needsUpdate = true;
super.restore();
}
} // class Frequencies
|
package ca.eandb.jmist.framework.color;
import ca.eandb.jmist.framework.Raster;
/**
* Default implementations for <code>Raster</code>.
* @author Brad Kimmel
*/
public abstract class AbstractRaster implements Raster {
/** Serialization version ID. */
private static final long serialVersionUID = -3717804516623958287L;
/* (non-Javadoc)
* @see ca.eandb.jmist.framework.Raster#addPixel(int, int, ca.eandb.jmist.framework.color.Color)
*/
public void addPixel(int x, int y, Color pixel) {
setPixel(x, y, getPixel(x, y).plus(pixel));
}
}
|
package de.haw.rnp.client.model;
import de.haw.rnp.util.AddressType;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class User {
private StringProperty name;
private StringProperty hostname;
private IntegerProperty port;
private AddressType address;
public User(String hostname, int port, String name) {
this.name = new SimpleStringProperty(name);
this.hostname = new SimpleStringProperty(hostname);
this.port = new SimpleIntegerProperty(port);
updateAddress();
}
public User(String hostname, int port){
this.name = new SimpleStringProperty("");
this.hostname = new SimpleStringProperty(hostname);
this.port = new SimpleIntegerProperty(port);
updateAddress();
}
public User(String username, AddressType address){
this.name = new SimpleStringProperty(username);
this.hostname = new SimpleStringProperty(address.getIp().getHostAddress());
this.port = new SimpleIntegerProperty(address.getPort());
this.address = address;
}
public String getName() {
return name.get();
}
public StringProperty nameProperty() {
return name;
}
public void setName(String name) {
this.name.set(name);
}
public String getHostName() {
return hostname.get();
}
public StringProperty hostNameProperty() {
return hostname;
}
public void setHostName(String hostName) {
this.hostname.set(hostName);
}
public int getPort() {
return port.get();
}
public IntegerProperty portProperty() {
return port;
}
public void setPort(int port) {
this.port.set(port);
}
public AddressType getAddress() {
return address;
}
public void setAddress(AddressType address) {
this.address = address;
}
@Override
public String toString() {
return name + " (" + address.getIp().getHostAddress() + ":" + address.getPort() + ")";
}
private void updateAddress(){
try {
address = new AddressType(InetAddress.getByName(hostname.get()), port.get());
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
|
import java.io.*;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collector;
import static java.util.stream.Stream.of;
import static java.util.stream.Collectors.joining;
class Referee extends MultiReferee {
public static int GAME_VERSION = 3;
static final Pattern PLAYER_PATTERN = Pattern.compile(
"^(?<action>MOVE\\&BUILD|PUSH\\&BUILD)\\s+(?<index>\\d)\\s+(?<move>N|S|W|E|NW|NE|SW|SE)\\s+(?<place>N|S|W|E|NW|NE|SW|SE)(?:\\s+)?(?:\\s+(?<message>.+))?",
Pattern.CASE_INSENSITIVE);
static final Pattern ACCEPT_DEFEAT_PATTERN = Pattern.compile(
"^ACCEPT-DEFEAT(?:\\s+)?(?:\\s+(?<message>.+))?",
Pattern.CASE_INSENSITIVE);
public static final int GOT_PUSHED = 2;
public static final int DID_PUSH = 1;
public static final int NO_PUSH = 0;
public static final int FINAL_HEIGHT = 4;
public static final int VIEW_DISTANCE = 1;
public static final int GENERATED_MAP_SIZE = 6;
public static boolean WIN_ON_MAX_HEIGHT = true;
public static boolean FOG_OF_WAR = false;
public static boolean CAN_PUSH = false;
public static int UNITS_PER_PLAYER = 1;
public static void main(String... args) throws IOException {
new Referee(System.in, System.out, System.err);
}
static class Point {
final int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return "Point [x=" + x + ", y=" + y + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + y;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
Point other = (Point) obj;
return x == other.x && y == other.y;
}
int distance(Point other) {
return Math.max(Math.abs(x - other.x), Math.abs(y - other.y));
}
}
static class Unit {
int index;
Player player;
Point position;
boolean gotPushed;
ActionResult did;
public Unit(Player player, int index) {
this.player = player;
this.index = index;
}
public void reset() {
gotPushed = false;
did = null;
}
public boolean pushed() {
return did != null && did.type == Action.PUSH;
}
public boolean moved() {
return did != null && did.type == Action.MOVE;
}
}
static class ActionResult {
public Point moveTarget;
public Point placeTarget;
public boolean placeValid;
public boolean moveValid;
public boolean scorePoint;
public String type;
public Unit unit;
public ActionResult(String type) {
this.type = type;
}
}
static class Action {
public static String MOVE = "MOVE&BUILD";
public static String PUSH = "PUSH&BUILD";
int index;
Direction move;
Direction place;
String command;
public Action(String command, int index, Direction move, Direction place) {
this.index = index;
this.move = move;
this.place = place;
this.command = command;
}
public String toPlayerString() {
return command + " " + index + " " + move + " " + place;
}
}
static class Grid {
private Map<Point, Integer> map;
int size;
public Grid() {
this.map = new HashMap<>();
}
public Integer get(int x, int y) {
return get(new Point(x, y));
}
public Integer get(Point p) {
Integer level = map.get(p);
return level;
}
public void create(Point point) {
map.put(point, 0);
int necessarySize = Math.max(point.x, point.y) + 1;
if (necessarySize > size) {
size = necessarySize;
}
}
public void place(Point placeAt) {
map.put(placeAt, map.get(placeAt) + 1);
}
}
static class Player {
int index, score;
boolean dead, won;
List<Unit> units;
private String message;
public Player(int index) {
this.index = index;
units = new ArrayList<>();
score = 0;
}
public void win() {
won = true;
}
public void die(int round) {
dead = true;
}
public void reset() {
message = null;
units.stream().forEach(Unit::reset);
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
if (message != null && message.length() > 48) {
this.message = message.substring(0, 46) + "...";
}
}
}
private boolean symmetric;
private long seed;
private Random random;
private Grid grid;
private List<Player> players;
private List<Unit> units;
private int mapIndex;
private String expected;
public Referee(InputStream is, PrintStream out, PrintStream err) throws IOException {
super(is, out, err);
}
@Override
protected boolean isTurnBasedGame() {
return true;
}
@Override
protected boolean gameIsOver() {
if (WIN_ON_MAX_HEIGHT) {
return super.gameIsOver() || players.stream().anyMatch(p -> p.won || p.dead);
}
boolean oneDead = players.get(0).dead;
boolean twoDead = players.get(1).dead;
if (oneDead && twoDead) {
return true;
} else if (oneDead && !twoDead) {
return players.get(1).score > players.get(0).score;
} else if (!oneDead && twoDead) {
return players.get(0).score > players.get(1).score;
} else {
return false;
}
}
@Override
protected void initReferee(int playerCount, Properties prop) throws InvalidFormatException {
String seed = prop.getProperty("seed", String.valueOf(new Random(System.currentTimeMillis()).nextLong()));
String mapIndex = prop.getProperty("mapIndex", "-1");
String symmetric = prop.getProperty("symmetric", "false");
if (GAME_VERSION >= 1) {
WIN_ON_MAX_HEIGHT = false;
}
if (GAME_VERSION >= 2) {
UNITS_PER_PLAYER = 2;
CAN_PUSH = true;
}
if (GAME_VERSION >= 3) {
FOG_OF_WAR = true;
}
expected = "MOVE&BUILD";
if (CAN_PUSH) {
expected += " | PUSH&BUILD";
}
expected += " <index> <direction> <direction>";
try {
this.mapIndex = Integer.valueOf(mapIndex);
} catch (NumberFormatException e) {
this.mapIndex = -1;
}
this.seed = new Random(System.currentTimeMillis()).nextLong();
try {
this.seed = Long.valueOf(seed);
} catch (NumberFormatException e) {
}
try {
this.symmetric = Boolean.valueOf(symmetric);
} catch (NumberFormatException e) {
this.symmetric = false;
}
random = new Random(this.seed);
grid = initGrid();
players = new ArrayList<Player>(playerCount);
units = new ArrayList<Unit>(playerCount * UNITS_PER_PLAYER);
for (int idx = 0; idx < playerCount; ++idx) {
Player player = new Player(idx);
for (int i = 0; i < UNITS_PER_PLAYER; ++i) {
Unit u = new Unit(player, i);
player.units.add(u);
units.add(u);
}
players.add(player);
}
LinkedList<Point> points = new LinkedList<>(grid.map.keySet());
// Remove random from unordered set
Collections.sort(points, (a, b) -> (a.x == b.x) ? a.y - b.y : a.x - b.x);
// Introduce random from seed
Collections.shuffle(points, random);
if (this.symmetric) {
Player one = players.get(0);
Player two = players.get(1);
Queue<Point> queue = (Queue<Point>) points;
for (Unit u : one.units) {
boolean okay = false;
while (!okay) {
Point a = queue.poll();
Point b = new Point(grid.size - 1 - a.x, a.y);
boolean removed = queue.remove(b);
if (removed) {
okay = true;
u.position = a;
two.units.get(u.index).position = b;
}
}
}
} else {
for (Unit u : units) {
u.position = ((Queue<Point>) points).poll();
}
}
}
/**
* There is no good reason to create a custom Collector just for instantiating a Point. I just wanted to try it out.
*
* @author julien
*/
static class PointCollector implements Collector<Integer, List<Integer>, Point> {
@Override
public Set<java.util.stream.Collector.Characteristics> characteristics() {
return new HashSet<>();
}
@Override
public Supplier<List<Integer>> supplier() {
return LinkedList<Integer>::new;
}
@Override
public BiConsumer<List<Integer>, Integer> accumulator() {
return (list, value) -> list.add(value);
}
@Override
public BinaryOperator<List<Integer>> combiner() {
return (a, b) -> {
a.addAll(b);
return a;
};
}
@Override
public Function<List<Integer>, Point> finisher() {
return list -> new Point(list.get(0), list.get(1));
}
}
private PointCollector toPoint() {
return new PointCollector();
}
private Grid initGrid() {
Grid grid = new Grid();
List<String> maps = new ArrayList<>();
maps.add("0 0;1 0;2 0;3 0;4 0;0 1;1 1;2 1;3 1;4 1;0 2;1 2;2 2;3 2;4 2;0 3;1 3;2 3;3 3;4 3;0 4;1 4;2 4;3 4;4 4"); // Square
maps.add("3 0;2 1;3 1;4 1;1 2;2 2;3 2;4 2;5 2;0 3;1 3;2 3;3 3;4 3;5 3;6 3;1 4;2 4;3 4;4 4;5 4;2 5;3 5;4 5;3 6"); // Diamond
maps.add(generateRandomMap());
int randomMapIndex = random.nextInt(maps.size());
if (mapIndex < 0 || mapIndex >= maps.size()) {
mapIndex = randomMapIndex;
}
String[] coords = maps.get(mapIndex).split(";");
of(coords)
.map(coord -> of(coord.split(" "))
.map(Integer::valueOf)
.collect(toPoint()))
.forEach(point -> grid.create(point));
return grid;
}
private String generateRandomMap() {
Set<String> coords = new HashSet<>();
int size = GENERATED_MAP_SIZE;
int iterations = 0;
int cells = 25 + random.nextInt(10);
int islands = 0;
Grid g = new Grid();
while ((coords.size() < cells || islands > 1) && iterations < 1_000) {
int x = random.nextInt(size);
int y = random.nextInt(size);
Point point = new Point(x, y);
Point mirror = new Point((size - 1 - x), y);
coords.add(point.x + " " + point.y);
coords.add(mirror.x + " " + mirror.y);
g.create(point);
g.create(mirror);
islands = countIslands(g, size);
iterations++;
}
return coords.stream().collect(joining(";"));
}
private int countIslands(Grid grid, int size) {
Set<Point> computed = new HashSet<>();
int total = 0;
for (Point p : grid.map.keySet()) {
if (!computed.contains(p)) {
total++;
Queue<Point> fifo = new LinkedList<>();
fifo.add(p);
while (!fifo.isEmpty()) {
Point e = fifo.poll();
for (Direction d : Direction.values()) {
Point n = getNeighbor(d.name(), e, size);
if (!computed.contains(n) && grid.get(n) != null) {
fifo.add(n);
}
}
computed.add(e);
}
}
}
return total;
}
static enum Direction {
NW, N, NE, W, E, SW, S, SE
}
@Override
protected Properties getConfiguration() {
Properties p = new Properties();
p.put("seed", seed);
p.put("mapIndex", mapIndex);
if (symmetric) {
p.put("symmetric", true);
}
return p;
}
@Override
protected String[] getInitInputForPlayer(int playerIdx) {
List<String> lines = new ArrayList<>();
lines.add(String.valueOf(grid.size));
lines.add(String.valueOf(UNITS_PER_PLAYER));
return lines.toArray(new String[lines.size()]);
}
@Override
protected String[] getInputForPlayer(int round, int playerIdx) {
List<String> lines = new ArrayList<>();
Player self = players.get(playerIdx);
Player other = players.get((playerIdx + 1) % 2);
for (int y = 0; y < grid.size; ++y) {
StringBuilder row = new StringBuilder();
for (int x = 0; x < grid.size; ++x) {
Integer height = grid.get(x, y);
if (height == null) {
row.append(".");
} else {
row.append(height);
}
}
lines.add(row.toString());
}
of(self, other).forEach(p -> {
for (Unit u : p.units) {
if (p == other && !unitVisibleToPlayer(u, self)) {
lines.add("-1 -1");
} else {
lines.add(u.position.x + " " + u.position.y);
}
}
});
List<Action> legalActions = getLegalActions(self);
lines.add(String.valueOf(legalActions.size()));
for (Action action : legalActions) {
lines.add(action.toPlayerString());
}
return lines.toArray(new String[lines.size()]);
}
private boolean unitVisibleToPlayer(Unit unit, Player player) {
if (!FOG_OF_WAR)
return true;
for (Unit u : player.units) {
if (u.position.distance(unit.position) <= VIEW_DISTANCE) {
return true;
}
}
return false;
}
private ActionResult computeMove(Unit unit, String dir1, String dir2) throws LostException {
Point target = getNeighbor(dir1, unit.position);
Integer targetHeight = grid.get(target);
if (targetHeight == null) {
throw new LostException("BadCoords", target.x, target.y);
}
int currentHeight = grid.get(unit.position);
if (targetHeight > currentHeight + 1) {
throw new LostException("InvalidMove", currentHeight, targetHeight);
}
if (targetHeight >= FINAL_HEIGHT) {
throw new LostException("MoveTooHigh", target.x, target.y);
}
if (getUnitOnPoint(target).isPresent()) {
throw new LostException("MoveOnUnit", target.x, target.y);
}
Point placeTarget = getNeighbor(dir2, target);
Integer placeTargetHeight = grid.get(placeTarget);
if (placeTargetHeight == null) {
throw new LostException("InvalidPlace", placeTarget.x, placeTarget.y);
}
if (placeTargetHeight >= FINAL_HEIGHT) {
throw new LostException("PlaceTooHigh", targetHeight);
}
ActionResult result = new ActionResult(Action.MOVE);
result.moveTarget = target;
result.placeTarget = placeTarget;
Optional<Unit> possibleUnit = getUnitOnPoint(placeTarget).filter(u -> !u.equals(unit));
if (!possibleUnit.isPresent()) {
result.placeValid = true;
result.moveValid = true;
} else if (FOG_OF_WAR && !unitVisibleToPlayer(possibleUnit.get(), unit.player)) {
result.placeValid = false;
result.moveValid = true;
} else {
throw new LostException("PlaceOnUnit", placeTarget.x, placeTarget.y);
}
if (targetHeight == FINAL_HEIGHT - 1) {
result.scorePoint = true;
}
result.unit = unit;
return result;
}
private Optional<Unit> getUnitOnPoint(Point target) {
Optional<Unit> potentialUnit = units.stream().filter(u -> u.position.equals(target)).findFirst();
return potentialUnit;
}
private ActionResult computePush(Unit unit, String dir1, String dir2) throws LostException {
if (!validPushDirection(dir1, dir2)) {
throw new LostException("PushInvalid", dir1, dir2);
}
Point target = getNeighbor(dir1, unit.position);
Optional<Unit> maybePushed = getUnitOnPoint(target);
if (!maybePushed.isPresent()) {
throw new LostException("PushVoid", target.x, target.y);
}
Unit pushed = maybePushed.get();
if (pushed.player == unit.player) {
throw new LostException("FriendlyFire", unit.index, pushed.index);
}
Point pushTo = getNeighbor(dir2, pushed.position);
Integer toHeight = grid.get(pushTo);
int fromHeight = grid.get(target);
if (toHeight == null || toHeight >= FINAL_HEIGHT || toHeight > fromHeight + 1) {
throw new LostException("PushInvalid", dir1, dir2);
}
ActionResult result = new ActionResult(Action.PUSH);
result.moveTarget = pushTo;
result.placeTarget = target;
Optional<Unit> possibleUnit = getUnitOnPoint(pushTo);
if (!possibleUnit.isPresent()) {
result.placeValid = true;
result.moveValid = true;
} else if (FOG_OF_WAR && !unitVisibleToPlayer(possibleUnit.get(), unit.player)) {
result.placeValid = false;
result.moveValid = false;
} else {
throw new LostException("PushOnUnit", dir1, dir2);
}
result.unit = pushed;
return result;
}
private ActionResult computeAction(String command, Unit unit, String dir1, String dir2) throws LostException {
if (command.equalsIgnoreCase(Action.MOVE)) {
return computeMove(unit, dir1, dir2);
} else if (CAN_PUSH && command.equals(Action.PUSH)) {
return computePush(unit, dir1, dir2);
} else {
throw new LostException("InvalidCommand", command);
}
}
private List<Action> getLegalActions(Player player) {
List<Action> actions = new LinkedList<>();
for (Unit unit : player.units) {
for (Direction dir1 : Direction.values()) {
for (Direction dir2 : Direction.values()) {
try {
computeAction(Action.MOVE, unit, dir1.name(), dir2.name());
actions.add(new Action(Action.MOVE, unit.index, dir1, dir2));
} catch (LostException eMove) {
}
if (CAN_PUSH) {
try {
computeAction(Action.PUSH, unit, dir1.name(), dir2.name());
actions.add(new Action(Action.PUSH, unit.index, dir1, dir2));
} catch (LostException ePush) {
}
}
}
}
}
actions.sort((a, b) -> a.toPlayerString().compareTo(b.toPlayerString()));
return actions;
}
@Override
protected void prepare(int round) {
players.stream().forEach(Player::reset);
}
@Override
protected int getExpectedOutputLineCountForPlayer(int playerIdx) {
return 1;
}
private void matchMessage(Player player, Matcher match) {
player.setMessage(match.group("message"));
}
private Point getNeighbor(String direction, Point position) {
return getNeighbor(direction, position, grid.size);
}
private Point getNeighbor(String direction, Point position, int size) {
int x = position.x;
int y = position.y;
if (direction.contains("E")) {
x++;
} else if (direction.contains("W")) {
x
}
if (direction.contains("S")) {
y++;
} else if (direction.contains("N")) {
y
}
return new Point(x, y);
}
@Override
protected void handlePlayerOutput(int frame, int round, int playerIdx, String[] outputs)
throws WinException, LostException, InvalidInputException {
String line = outputs[0];
Player player = players.get(playerIdx);
try {
Matcher match = ACCEPT_DEFEAT_PATTERN.matcher(line);
if (match.matches()) {
player.die(round);
//Message
matchMessage(player, match);
throw new LostException("selfDestruct", player.index);
}
match = PLAYER_PATTERN.matcher(line);
if (match.matches()) {
String action = match.group("action");
String indexString = match.group("index");
String dir1 = match.group("move").toUpperCase();
String dir2 = match.group("place").toUpperCase();
int index = Integer.valueOf(indexString);
Unit unit = player.units.get(index);
ActionResult ar = computeAction(action, unit, dir1, dir2);
unit.did = ar;
if (ar.moveValid) {
ar.unit.position = ar.moveTarget;
}
if (ar.placeValid) {
grid.place(ar.placeTarget);
}
if (ar.scorePoint) {
player.score++;
}
if (ar.type.equals(Action.PUSH)) {
ar.unit.gotPushed = true;
}
//Message
matchMessage(player, match);
return;
}
throw new InvalidInputException(expected, line);
} catch (LostException | InvalidInputException e) {
player.die(round);
throw e;
} catch (Exception e) {
StringWriter errors = new StringWriter();
e.printStackTrace(new PrintWriter(errors));
printError(e.getMessage() + "\n" + errors.toString());
player.die(round);
throw new InvalidInputException(expected, line);
}
}
private boolean validPushDirection(String target, String push) {
if (target.length() == 2) {
return push.equals(target) || push.equals(target.substring(0, 1)) || push.equals(target.substring(1, 2));
} else {
return push.contains(target);
}
}
@Override
protected void updateGame(int round) throws GameOverException {
for (Unit unit : units) {
if (WIN_ON_MAX_HEIGHT && grid.get(unit.position).equals(FINAL_HEIGHT - 1)) {
unit.player.win();
}
}
}
@Override
protected void populateMessages(Properties p) {
//Error messages
p.put("PlaceOnUnit", "Trying to build on a unit at position (%d,%d).");
p.put("PushVoid", "Nobody to push at position (%d, %d).");
p.put("PlaceTooHigh", "Cannot build at height %d.");
p.put("InvalidMove", "Cannot move from height %d to %d.");
p.put("MoveOnUnit", "Trying to move onto an occupied cell at (%d,%d).");
p.put("BadCoords", "Cannot move to position (%d,%d).");
p.put("MoveTooHigh", "Cannot move to position (%d,%d).");
p.put("InvalidPlace", "Cannot build on position (%d,%d).");
p.put("PushInvalid", "Not a valid push: %s + %s.");
p.put("FriendlyFire", "Unit %d is tried to push friendly unit %d.");
p.put("PushOnUnit", "Trying to push onto another unit: %s + %s.");
p.put("selfDestruct", "$%d accepts defeat!");
//Tooltip error messages
p.put("PlaceOnUnitTooltip", "Invalid build (%d,%d)");
p.put("PushVoidTooltip", "Invalid push (%d, %d)");
p.put("PlaceTooHighTooltip", "Invalid build (%d,%d)");
p.put("InvalidMoveTooltip", "Invalid move (%d to %d)");
p.put("MoveOnUnitTooltip", "Invalid move (%d,%d)");
p.put("BadCoordsTooltip", "Invalid move (%d,%d)");
p.put("MoveTooHighTooltip", "Invalid move (%d,%d)");
p.put("InvalidPlaceTooltip", "Invalid build (%d,%d)");
p.put("PushInvalidTooltip", "Invalid push (%s + %s)");
p.put("FriendlyFireTooltip", "Friendly fire!");
p.put("PushOnUnitTooltip", "Invalid push (%s + %s)");
p.put("selfDestructTooltip", "accepted defeat!");
//Status messages
p.put("MoveValid", "$%d moved unit %d to (%d,%d).");
p.put("PlaceValid", "...and builds on (%d,%d).");
p.put("CancelledPlace", "...and cannot build on (%d,%d)!");
p.put("PushToPlaceOn", "$%d made unit %d push a unit to (%d,%d) and builds on (%d,%d).");
p.put("CancelledPush", "$%d attempted to make unit %d push the unit on (%d, %d), but could not.");
p.put("Wins", "...and wins the game!");
p.put("Scores", "...and scores a point!");
}
@Override
protected String[] getInitDataForView() {
List<String> lines = new ArrayList<>();
lines.add(String.valueOf(grid.size));
lines.add(String.valueOf(GAME_VERSION));
lines.add(String.valueOf(UNITS_PER_PLAYER));
lines.add(0, String.valueOf(lines.size() + 1));
return lines.toArray(new String[lines.size()]);
}
@Override
protected String[] getFrameDataForView(int round, int frame, boolean keyFrame) {
List<String> lines = new ArrayList<>();
units.stream().forEach(u -> {
int pushCode = NO_PUSH;
if (u.pushed()) {
pushCode = DID_PUSH;
} else if (u.gotPushed) {
pushCode = GOT_PUSHED;
}
lines.add(u.position.x + " " + u.position.y + " " + pushCode);
});
for (int y = 0; y < grid.size; ++y) {
StringBuilder row = new StringBuilder();
for (int x = 0; x < grid.size; ++x) {
Integer height = grid.get(x, y);
if (height == null) {
row.append(".");
} else {
row.append(height);
}
}
lines.add(row.toString());
}
for (Player p : players) {
lines.add(String.valueOf(getScore(p.index)) + " " + (p.dead ? 0 : 1) + ";" + (p.message == null ? "" : p.message));
}
lines.add(String.valueOf(whoJustPlayed()));
return lines.toArray(new String[lines.size()]);
}
private int whoJustPlayed() {
Optional<Player> opt = units.stream().filter(u -> u.did != null).map(u -> u.player).findFirst();
Player p = opt.orElse(players.get(0));
return p.index;
}
@Override
protected String getGameName() {
return "WondevWoman";
}
@Override
protected String getHeadlineAtGameStartForConsole() {
return null;
}
@Override
protected int getMinimumPlayerCount() {
return 2;
}
@Override
protected boolean showTooltips() {
return true;
}
@Override
protected String[] getPlayerActions(int playerIdx, int round) {
return new String[0];
}
@Override
protected boolean isPlayerDead(int playerIdx) {
if (GAME_VERSION == 0) {
return players.get(playerIdx).dead;
}
return false;
}
@Override
protected String getDeathReason(int playerIdx) {
return "$" + playerIdx + ": Eliminated!";
}
@Override
protected int getScore(int playerIdx) {
Player p = players.get(playerIdx);
if (WIN_ON_MAX_HEIGHT) {
if (p.dead)
return -1;
if (p.won)
return 1;
return 0;
}
return p.score;
}
@Override
protected String[] getGameSummary(int round) {
List<String> lines = new ArrayList<>();
for (Unit u : units) {
if (u.moved()) {
if (u.did.moveValid) {
lines.add(translate("MoveValid", u.player.index, u.index, u.did.moveTarget.x, u.did.moveTarget.y));
} else {
printError("impossible");
}
if (u.did.placeValid) {
lines.add(translate("PlaceValid", u.did.placeTarget.x, u.did.placeTarget.y));
} else {
lines.add(translate("CancelledPlace", u.did.placeTarget.x, u.did.placeTarget.y));
}
if (u.did.scorePoint) {
if (WIN_ON_MAX_HEIGHT) {
lines.add(translate("Wins"));
} else {
lines.add(translate("Scores"));
}
}
} else if (u.pushed()) {
if (u.did.moveValid && u.did.placeValid) {
lines.add(translate("PushToPlaceOn", u.player.index, u.index, u.did.moveTarget.x, u.did.moveTarget.y, u.did.placeTarget.x,
u.did.placeTarget.y));
} else if (!u.did.moveValid && !u.did.placeValid) {
lines.add(translate("CancelledPush", u.player.index, u.index, u.did.placeTarget.x, u.did.placeTarget.y));
} else {
printError("also impossible");
}
}
}
return lines.toArray(new String[lines.size()]);
}
@Override
protected void setPlayerTimeout(int frame, int round, int playerIdx) {
players.get(playerIdx).die(round);
}
@Override
protected int getMaxRoundCount(int playerCount) {
return 200;
}
}
abstract class MultiReferee extends AbstractReferee {
private Properties properties;
public MultiReferee(InputStream is, PrintStream out, PrintStream err) throws IOException {
super(is, out, err);
}
@Override
protected final void handleInitInputForReferee(int playerCount, String[] init) throws InvalidFormatException {
properties = new Properties();
try {
for (String s : init) {
properties.load(new StringReader(s));
}
} catch (IOException e) {
}
initReferee(playerCount, properties);
properties = getConfiguration();
}
abstract protected void initReferee(int playerCount, Properties prop) throws InvalidFormatException;
abstract protected Properties getConfiguration();
protected void appendDataToEnd(PrintStream stream) throws IOException {
stream.println(OutputCommand.UINPUT.format(properties.size()));
for (Map.Entry<Object, Object> t : properties.entrySet()) {
stream.println(t.getKey() + "=" + t.getValue());
}
}
}
abstract class AbstractReferee {
private static final Pattern HEADER_PATTERN = Pattern.compile("\\[\\[(?<cmd>.+)\\] ?(?<lineCount>[0-9]+)\\]");
private static final String LOST_PARSING_REASON_CODE = "INPUT";
private static final String LOST_PARSING_REASON = "Failure: invalid input";
protected static class PlayerStatus {
private int id;
private int score;
private boolean lost, win;
private String info;
private String reasonCode;
private String[] nextInput;
public PlayerStatus(int id) {
this.id = id;
lost = false;
info = null;
}
public int getScore() {
return score;
}
public boolean isLost() {
return lost;
}
public String getInfo() {
return info;
}
public int getId() {
return id;
}
public String getReasonCode() {
return reasonCode;
}
public String[] getNextInput() {
return nextInput;
}
}
private Properties messages = new Properties();
@SuppressWarnings("serial")
final class InvalidFormatException extends Exception {
public InvalidFormatException(String message) {
super(message);
}
}
@SuppressWarnings("serial")
abstract class GameException extends Exception {
private String reasonCode, tooltipCode;
private Object[] values;
public GameException(String reasonCode, Object... values) {
this.reasonCode = reasonCode;
this.values = values;
}
public void setTooltipCode(String tooltipCode) {
this.tooltipCode = tooltipCode;
}
public String getReason() {
if (reasonCode != null) {
return translate(reasonCode, values);
} else {
return null;
}
}
public String getReasonCode() {
return reasonCode;
}
public String getTooltipCode() {
if (tooltipCode != null) {
return tooltipCode;
}
return getReasonCode();
}
}
@SuppressWarnings("serial")
class LostException extends GameException {
public LostException(String reasonCode, Object... values) {
super(reasonCode, values);
}
}
@SuppressWarnings("serial")
class WinException extends GameException {
public WinException(String reasonCode, Object... values) {
super(reasonCode, values);
}
}
@SuppressWarnings("serial")
class InvalidInputException extends GameException {
public InvalidInputException(String expected, String found) {
super("InvalidInput", expected, found);
}
}
@SuppressWarnings("serial")
class GameOverException extends GameException {
public GameOverException(String reasonCode, Object... values) {
super(reasonCode, values);
}
}
@SuppressWarnings("serial")
class GameErrorException extends Exception {
public GameErrorException(Throwable cause) {
super(cause);
}
}
public static enum InputCommand {
INIT, GET_GAME_INFO, SET_PLAYER_OUTPUT, SET_PLAYER_TIMEOUT
}
public static enum OutputCommand {
VIEW, INFOS, NEXT_PLAYER_INPUT, NEXT_PLAYER_INFO, SCORES, UINPUT, TOOLTIP, SUMMARY;
public String format(int lineCount) {
return String.format("[[%s] %d]", this.name(), lineCount);
}
}
@SuppressWarnings("serial")
public static class OutputData extends LinkedList<String> {
private OutputCommand command;
public OutputData(OutputCommand command) {
this.command = command;
}
public boolean add(String s) {
if (s != null)
return super.add(s);
return false;
}
public void addAll(String[] data) {
if (data != null)
super.addAll(Arrays.asList(data));
}
@Override
public String toString() {
StringWriter writer = new StringWriter();
PrintWriter out = new PrintWriter(writer);
out.println(this.command.format(this.size()));
for (String line : this) {
out.println(line);
}
return writer.toString().trim();
}
}
private static class Tooltip {
int player;
String message;
public Tooltip(int player, String message) {
this.player = player;
this.message = message;
}
}
private Set<Tooltip> tooltips;
private int playerCount, alivePlayerCount;
private int currentPlayer, nextPlayer;
private PlayerStatus lastPlayer, playerStatus;
private int frame, round;
private PlayerStatus[] players;
private String[] initLines;
private boolean newRound;
private String reasonCode, reason;
private InputStream is;
private PrintStream out;
private PrintStream err;
public AbstractReferee(InputStream is, PrintStream out, PrintStream err) throws IOException {
tooltips = new HashSet<>();
this.is = is;
this.out = out;
this.err = err;
start();
}
@SuppressWarnings("resource")
public void start() throws IOException {
Scanner s = new Scanner(is);
String firstLine = s.nextLine();
try {
if (firstLine.startsWith("###Seed")) {
String seed = firstLine.substring(8);
handleInitInputForReferee(2, new String[] { "seed=" + seed });
s.nextLine(); // Read ##Start
} else {
// First line is ##Start
handleInitInputForReferee(2, new String[0]);
}
} catch (InvalidFormatException e) {
return;
}
try {
playerCount = alivePlayerCount = 2;
players = new PlayerStatus[2];
players[0] = new PlayerStatus(0);
players[1] = new PlayerStatus(1);
playerStatus = players[0];
currentPlayer = nextPlayer = 1;
round = -1;
newRound = true;
while (true) {
lastPlayer = playerStatus;
playerStatus = nextPlayer();
if (this.round >= getMaxRoundCount(this.playerCount)) {
throw new GameOverException("maxRoundsCountReached");
}
if (newRound) {
prepare(round);
if (!this.isTurnBasedGame()) {
for (PlayerStatus player : this.players) {
if (!player.lost) {
player.nextInput = getInputForPlayer(round, player.id);
} else {
player.nextInput = null;
}
}
}
}
out.println("###Input " + nextPlayer);
if (this.round == 0) {
for (String line : getInitInputForPlayer(nextPlayer)) {
out.println(line);
}
}
if (this.isTurnBasedGame()) {
for (String line : getInputForPlayer(round, nextPlayer)) {
out.println(line);
}
} else {
for (String line : this.players[nextPlayer].nextInput) {
out.println(line);
}
}
int expectedOutputLineCount = getExpectedOutputLineCountForPlayer(nextPlayer);
out.println("###Output " + nextPlayer + " " + expectedOutputLineCount);
try {
String[] outputs = new String[expectedOutputLineCount];
for (int i = 0; i < expectedOutputLineCount; i++) {
outputs[i] = s.nextLine();
}
handlePlayerOutput(0, round, nextPlayer, outputs);
} catch (WinException e) {
playerStatus.score = getScore(nextPlayer);
playerStatus.win = true;
playerStatus.info = e.getReason();
playerStatus.reasonCode = e.getReasonCode();
lastPlayer = playerStatus;
throw new GameOverException(null);
} catch (LostException | InvalidInputException e) {
playerStatus.score = getScore(nextPlayer);
playerStatus.lost = true;
playerStatus.info = e.getReason();
playerStatus.reasonCode = e.getReasonCode();
boolean otherPlayerIsDead = lastPlayer.lost;
lastPlayer = playerStatus;
//only end the game, if both players are dead
if (otherPlayerIsDead)
throw new GameOverException(null);
}
}
} catch (GameOverException e) {
newRound = true;
reasonCode = e.getReasonCode();
reason = e.getReason();
err.println(reason);
prepare(round);
updateScores();
if (players[0].score > players[1].score) {
out.println("###End 0 1");
} else if (players[0].score < players[1].score) {
out.println("###End 1 0");
} else {
out.println("###End 01");
}
} finally {
s.close();
}
}
private PlayerStatus nextPlayer() throws GameOverException {
currentPlayer = nextPlayer;
newRound = false;
do {
++nextPlayer;
if (nextPlayer >= playerCount) {
nextRound();
nextPlayer = 0;
}
} while (this.players[nextPlayer].lost || this.players[nextPlayer].win);
return players[nextPlayer];
}
protected String getColoredReason(boolean error, String reason) {
if (error) {
return String.format("¤RED¤%s§RED§", reason);
} else {
return String.format("¤GREEN¤%s§GREEN§", reason);
}
}
private void dumpView() {
OutputData data = new OutputData(OutputCommand.VIEW);
String reasonCode = this.reasonCode;
if (reasonCode == null && playerStatus != null)
reasonCode = playerStatus.reasonCode;
if (newRound) {
if (reasonCode != null) {
data.add(String.format("KEY_FRAME %d %s", this.frame, reasonCode));
} else {
data.add(String.format("KEY_FRAME %d", this.frame));
}
if (frame == 0) {
data.add(getGameName());
data.addAll(getInitDataForView());
}
} else {
if (reasonCode != null) {
data.add(String.format("INTERMEDIATE_FRAME %d %s", this.frame, reasonCode));
} else {
data.add(String.format("INTERMEDIATE_FRAME %d", frame));
}
}
if (newRound || isTurnBasedGame()) {
data.addAll(getFrameDataForView(round, frame, newRound));
}
out.println(data);
}
private void dumpInfos() {
OutputData data = new OutputData(OutputCommand.INFOS);
if (reason != null && isTurnBasedGame()) {
data.add(getColoredReason(true, reason));
} else {
if (lastPlayer != null) {
String head = lastPlayer.info;
if (head != null) {
data.add(getColoredReason(lastPlayer.lost, head));
} else {
if (frame > 0) {
data.addAll(getPlayerActions(this.currentPlayer, newRound ? this.round - 1 : this.round));
}
}
}
}
out.println(data);
if (newRound && round >= -1 && playerCount > 1) {
OutputData summary = new OutputData(OutputCommand.SUMMARY);
if (frame == 0) {
String head = getHeadlineAtGameStartForConsole();
if (head != null) {
summary.add(head);
}
}
if (round >= 0) {
summary.addAll(getGameSummary(round));
}
if (!isTurnBasedGame() && reason != null) {
summary.add(getColoredReason(true, reason));
}
out.println(summary);
}
if (!tooltips.isEmpty() && (newRound || isTurnBasedGame())) {
data = new OutputData(OutputCommand.TOOLTIP);
for (Tooltip t : tooltips) {
data.add(t.message);
data.add(String.valueOf(t.player));
}
tooltips.clear();
out.println(data);
}
}
private void dumpNextPlayerInfos() {
OutputData data = new OutputData(OutputCommand.NEXT_PLAYER_INFO);
data.add(String.valueOf(nextPlayer));
data.add(String.valueOf(getExpectedOutputLineCountForPlayer(nextPlayer)));
if (this.round == 0) {
data.add(String.valueOf(getMillisTimeForFirstRound()));
} else {
data.add(String.valueOf(getMillisTimeForRound()));
}
out.println(data);
}
private void dumpNextPlayerInput() {
OutputData data = new OutputData(OutputCommand.NEXT_PLAYER_INPUT);
if (this.round == 0) {
data.addAll(getInitInputForPlayer(nextPlayer));
}
if (this.isTurnBasedGame()) {
this.players[nextPlayer].nextInput = getInputForPlayer(round, nextPlayer);
}
data.addAll(this.players[nextPlayer].nextInput);
out.println(data);
}
protected final String translate(String code, Object... values) {
try {
return String.format((String) messages.get(code), values);
} catch (NullPointerException e) {
return code;
}
}
protected final void printError(Object message) {
err.println(message);
}
protected int getMillisTimeForFirstRound() {
return 1000;
}
protected int getMillisTimeForRound() {
return 150;
}
protected int getMaxRoundCount(int playerCount) {
return 400;
}
private void nextRound() throws GameOverException {
newRound = true;
if (++round > 0) {
updateGame(round);
}
if (gameOver()) {
throw new GameOverException(null);
}
}
protected boolean gameIsOver() {
return this.gameOver();
}
protected boolean gameOver() {
return alivePlayerCount < getMinimumPlayerCount();
}
private void updateScores() {
for (int i = 0; i < playerCount; ++i) {
if (!players[i].lost && isPlayerDead(i)) {
alivePlayerCount
players[i].lost = true;
players[i].info = getDeathReason(i);
addToolTip(i, players[i].info);
}
players[i].score = getScore(i);
}
}
protected void addToolTip(int player, String message) {
if (showTooltips())
tooltips.add(new Tooltip(player, message));
}
/**
* Add message (key = reasonCode, value = reason)
*
* @param p
*/
protected abstract void populateMessages(Properties p);
protected boolean isTurnBasedGame() {
return false;
}
protected abstract void handleInitInputForReferee(int playerCount, String[] init) throws InvalidFormatException;
protected abstract String[] getInitDataForView();
protected abstract String[] getFrameDataForView(int round, int frame, boolean keyFrame);
protected abstract int getExpectedOutputLineCountForPlayer(int playerIdx);
protected abstract String getGameName();
protected abstract void appendDataToEnd(PrintStream stream) throws IOException;
protected abstract void handlePlayerOutput(int frame, int round, int playerIdx, String[] output) throws WinException, LostException, InvalidInputException;
protected abstract String[] getInitInputForPlayer(int playerIdx);
protected abstract String[] getInputForPlayer(int round, int playerIdx);
protected abstract String getHeadlineAtGameStartForConsole();
protected abstract int getMinimumPlayerCount();
protected abstract boolean showTooltips();
/**
* @param round
* @return scores of all players
* @throws GameOverException
*/
protected abstract void updateGame(int round) throws GameOverException;
protected abstract void prepare(int round);
protected abstract boolean isPlayerDead(int playerIdx);
protected abstract String getDeathReason(int playerIdx);
protected abstract int getScore(int playerIdx);
protected abstract String[] getGameSummary(int round);
protected abstract String[] getPlayerActions(int playerIdx, int round);
protected abstract void setPlayerTimeout(int frame, int round, int playerIdx);
}
|
package scalac.util;
public class Names {
public static final Name ERROR = Name.ERROR;
public static final Name EMPTY = Name.fromString("");
public static final Name WILDCARD = Name.fromString("_");
public static final Name COMPOUND_NAME = Name.fromString("<ct>");
public static final Name ANON_CLASS_NAME = Name.fromString("$anon");
public static final Name OUTER_PREFIX = Name.fromString("outer");
public static final Name CONSTRUCTOR = Name.fromString("<init>");
public static final Name _EQ = encode("_=");
public static final Name MINUS = encode("-");
public static final Name PLUS = encode("+");
public static final Name TILDE = encode("~");
public static final Name EQEQ = encode("==");
public static final Name BANG = encode("!");
public static final Name BANGEQ = encode("!=");
public static final Name BARBAR = encode("||");
public static final Name AMPAMP = encode("&&");
public static final Name COLONCOLON = encode("::");
public static final Name All = Name.fromString("All");
public static final Name AllRef = Name.fromString("AllRef");
public static final Name Any = Name.fromString("Any");
public static final Name AnyVal = Name.fromString("AnyVal");
public static final Name AnyRef = Name.fromString("AnyRef");
public static final Name Array = Name.fromString("Array");
public static final Name Byte = Name.fromString("Byte");
public static final Name Char = Name.fromString("Char");
public static final Name Boolean = Name.fromString("Boolean");
public static final Name Double = Name.fromString("Double");
public static final Name Float = Name.fromString("Float");
public static final Name Function = Name.fromString("Function");
public static final Name Int = Name.fromString("Int");
public static final Name Labelled = Name.fromString("Labelled");
public static final Name List = Name.fromString("List");
public static final Name Long = Name.fromString("Long");
public static final Name Nil = Name.fromString("Nil");
public static final Name Object = Name.fromString("Object");
public static final Name PartialFunction = Name.fromString("PartialFunction");
public static final Name Predef = Name.fromString("Predef");
public static final Name Seq = Name.fromString("Seq");
public static final Name Short = Name.fromString("Short");
public static final Name String = Name.fromString("String");
public static final Name Symbol = Name.fromString("Symbol");
public static final Name Throwable = Name.fromString("Throwable");
public static final Name Tuple = Name.fromString("Tuple");
public static final Name Unit = Name.fromString("Unit");
public static final Name apply = Name.fromString("apply");
public static final Name as = Name.fromString("as");
public static final Name box = Name.fromString("box");
public static final Name elem = Name.fromString("elem");
public static final Name elements = Name.fromString("elements");
public static final Name false_ = Name.fromString("false");
public static final Name filter = Name.fromString("filter");
public static final Name flatmap = Name.fromString("flatMap");
public static final Name foreach = Name.fromString("foreach");
public static final Name getClass = Name.fromString("getClass");
public static final Name hashCode = Name.fromString("hashCode");
public static final Name hasNext = Name.fromString("hasNext");
public static final Name is = Name.fromString("is");
public static final Name isDefinedAt = Name.fromString("isDefinedAt");
public static final Name java = Name.fromString("java");
public static final Name java_lang = Name.fromString("java.lang");
public static final Name java_lang_Object = Name.fromString("java.lang.Object");
public static final Name java_lang_String = Name.fromString("java.lang.String");
public static final Name java_lang_Throwable = Name.fromString("java.lang.Throwable");
public static final Name lang = Name.fromString("lang");
public static final Name length = Name.fromString("length");
public static final Name match = Name.fromString("match");
public static final Name map = Name.fromString("map");
public static final Name next = Name.fromString("next");
public static final Name null_ = Name.fromString("null");
public static final Name predef = Name.fromString("predef");
public static final Name runtime = Name.fromString("runtime");
public static final Name scala = Name.fromString("scala");
public static final Name scala_COLONCOLON = Name.fromString("scala." + COLONCOLON);
public static final Name scala_All = Name.fromString("scala.All");
public static final Name scala_AllRef = Name.fromString("scala.AllRef");
public static final Name scala_Any = Name.fromString("scala.Any");
public static final Name scala_AnyRef = Name.fromString("scala.AnyRef");
public static final Name scala_AnyVal = Name.fromString("scala.AnyVal");
public static final Name scala_Array = Name.fromString("scala.Array");
public static final Name scala_Boolean = Name.fromString("scala.Boolean");
public static final Name scala_Byte = Name.fromString("scala.Byte");
public static final Name scala_Case = Name.fromString("scala.Case");
public static final Name scala_Char = Name.fromString("scala.Char");
public static final Name scala_Double = Name.fromString("scala.Double");
public static final Name scala_Float = Name.fromString("scala.Float");
public static final Name scala_Function = Name.fromString("scala.Function");
public static final Name scala_Int = Name.fromString("scala.Int");
public static final Name scala_Iterable = Name.fromString("scala.Iterable");
public static final Name scala_Iterator = Name.fromString("scala.Iterator");
public static final Name scala_Long = Name.fromString("scala.Long");
public static final Name scala_Nil = Name.fromString("scala.Nil");
public static final Name scala_Object = Name.fromString("scala.Object");
public static final Name scala_PartialFunction = Name.fromString("scala.PartialFunction");
public static final Name scala_Predef = Name.fromString("scala.Predef");
public static final Name scala_Ref = Name.fromString("scala.Ref");
public static final Name scala_Seq = Name.fromString("scala.Seq");
public static final Name scala_Short = Name.fromString("scala.Short");
public static final Name scala_Symbol = Name.fromString("scala.Symbol");
public static final Name scala_Tuple = Name.fromString("scala.Tuple");
public static final Name scala_Unit = Name.fromString("scala.Unit");
public static final Name scala_runtime = Name.fromString("scala.runtime");
public static final Name scala_runtime_RunTime = Name.fromString("scala.runtime.RunTime");
public static final Name equals = Name.fromString("equals");
public static final Name toString = Name.fromString("toString");
public static final Name that = Name.fromString("that");
public static final Name that1 = Name.fromString("that1");
public static final Name this_ = Name.fromString("this");
public static final Name throw_ = Name.fromString("throw");
public static final Name true_ = Name.fromString("true");
public static final Name update = Name.fromString("update");
public static final Name
ZNOT = encode("!"),
ZAND = encode("&&"),
ZOR = encode("||"),
NOT = encode("~"),
ADD = encode("+"),
SUB = encode("-"),
MUL = encode("*"),
DIV = encode("/"),
MOD = encode("%"),
EQ = encode("=="),
NE = encode("!="),
LT = encode("<"),
LE = encode("<="),
GT = encode(">"),
GE = encode(">="),
OR = encode("|"),
XOR = encode("^"),
AND = encode("&"),
LSL = encode("<<"),
LSR = encode(">>>"),
ASR = encode(">>");
private static Name encode(String string) {
return NameTransformer.encode(Name.fromString(string));
}
}
|
import java.util.*;
/* Computes Ext_A^{s,t} (M, Z/2) through a minimal resolution of M. */
/* This seems to work effectively through about t=75, and then becomes prohibitively slow. */
public class ResMain
{
/* upper bound on total degree to compute */
static final int T_CAP = 100;
static final boolean DEBUG = false;
static final boolean MATRIX_DEBUG = false;
static HashMap<String,CellData> output = new HashMap<String,CellData>();
static String keystr(int s, int t) {
return "("+s+","+t+","+Math.P+")";
}
/* convenience methods for cell data lookup */
static int ngens(int s, int t) {
CellData dat = output.get(keystr(s,t));
if(dat == null) return -1;
return dat.gimg.length;
}
static DModSet[] kbasis(int s, int t) {
CellData dat = output.get(keystr(s,t));
die_if(dat == null, "Data null in ("+s+","+t+")");
return dat.kbasis;
}
static DModSet[] gimg(int s, int t) {
CellData dat = output.get(keystr(s,t));
die_if(dat == null, "Data null in ("+s+","+t+")");
return dat.gimg;
}
/* Main minimal-resolution procedure. */
static void resolve(AMod a)
{
for(int t = 0; t <= T_CAP; t++) {
/* first handle the s=0 case: process the input */
/* XXX TMP just using the sphere as input */
CellData dat0 = new CellData();
dat0.gimg = new DModSet[] {};
if(t == 0) {
dat0.kbasis = new DModSet[] {};
} else {
List<DModSet> kbasis0 = new ArrayList<DModSet>();
for(Sq q : Sq.steenrod(t)) {
DModSet ms = new DModSet();
ms.add(new Dot(q,0,0), 1);
kbasis0.add(ms);
}
dat0.kbasis = kbasis0.toArray(new DModSet[] {});
}
System.out.printf("(%2d,%2d): %2d gen, %2d ker\n", 0, t, 0, dat0.kbasis.length);
output.put(keystr(0,t), dat0);
/* now the typical s>0 case */
for(int s = 1; s <= t; s++) {
/* compute the basis for this resolution bidegree */
ArrayList<Dot> basis_l = new ArrayList<Dot>();
for(int gt = s; gt < t; gt++) {
for(int i = 0; i < ngens(s,gt); i++) {
for(Sq q : Sq.steenrod(t - gt)) {
basis_l.add(new Dot(q,gt,i));
}
}
}
Dot[] basis = basis_l.toArray(new Dot[]{});
DModSet[] okbasis = kbasis(s-1,t);
/* compute what the map does in this basis */
DotMatrix mat = new DotMatrix();
if(DEBUG) System.out.printf("(%d,%d) Map:\n",s,t);
for(int i = 0; i < basis.length; i++) {
/* compute the image of this basis vector */
DModSet image = new DModSet();
for(Map.Entry<Dot,Integer> d : gimg(s,basis[i].t)[basis[i].idx].entrySet()) {
ModSet<Sq> c = basis[i].sq.times(d.getKey().sq);
for(Map.Entry<Sq,Integer> q : c.entrySet())
image.add(new Dot(q.getKey(), d.getKey().t, d.getKey().idx), d.getValue() * q.getValue());
}
if(DEBUG) System.out.println("Image of "+basis[i]+" is "+image);
mat.put(basis[i], image);
}
/* the kernel of mat is kbasis */
DModSet[] kbasis = mat.ker();
/* from mat and okbasis, produce gimg */
if(DEBUG) System.out.printf("\ngimg at (%d,%d)\n", s,t);
DModSet[] gimg = calc_gimg(mat, okbasis);
if(DEBUG) System.out.println();
output.put(keystr(s,t), new CellData(gimg, kbasis));
if(DEBUG && gimg.length > 0) {
System.out.println("Generators:");
for(DModSet g : gimg) System.out.println(g);
}
print_result(t);
System.out.printf("(%2d,%2d): %2d gen, %2d ker\n", s, t, gimg.length, kbasis.length);
System.out.println();
}
}
}
/* Computes a basis complement to the image of mat inside the span of okbasis */
static DModSet[] calc_gimg(DotMatrix mat, DModSet[] okbasis)
{
/* sketch idea:
* do RREF on okbasis.
* apply the same row ops (matrix mult) to mat.
* (should find that the zero lines of okbasis are zero in mat)
* finish RREFing mat from this form
* find the overall complement of mat, excluding these zero lines
* transform back
*
* To do this more efficiently, we basically rref a huge augmentation: bokbasis | mat | id.
*/
/* choose an ordering on all keys and values */
Dot[] keys = mat.keySet().toArray(new Dot[] {});
DModSet val_set = new DModSet();
for(DModSet ms : okbasis)
val_set.union(ms);
if(DEBUG) System.out.println("val_set: "+val_set);
Dot[] values = val_set.toArray();
/* construct our huge augmented behemoth */
int[][] aug = new int[values.length][okbasis.length + keys.length + values.length];
for(int i = 0; i < values.length; i++) {
for(int j = 0; j < okbasis.length; j++)
aug[i][j] = Math.dmod(okbasis[j].getsafe(values[i]));
for(int j = 0; j < keys.length; j++)
aug[i][j + okbasis.length] = Math.dmod(mat.get(keys[j]).getsafe(values[i]));
for(int j = 0; j < values.length; j++)
aug[i][j + okbasis.length + keys.length] = (i == j ? 1 : 0);
}
Matrices.printMatrix("aug", aug);
/* rref it */
int l1 = Matrices.rref(aug, keys.length + values.length).length;
Matrices.printMatrix("rref(aug)", aug);
/* extract mat | id */
int[][] bmatrr = new int[values.length][keys.length + values.length];
for(int i = 0; i < values.length; i++)
for(int j = 0; j < keys.length + values.length; j++)
bmatrr[i][j] = aug[i][j + okbasis.length];
Matrices.printMatrix("bmatrr", bmatrr);
/* rref it some more */
int l2 = Matrices.rref(bmatrr, values.length).length;
Matrices.printMatrix("rref(bmatrr)", bmatrr);
if(DEBUG) System.out.printf("l1: %2d l2: %2d\n", l1, l2);
/* now we're back to the old code path */
/* extract and invert (via rref) the row transform matrix */
int[][] transf = new int[values.length][2 * values.length];
for(int i = 0; i < values.length; i++) {
for(int j = 0; j < values.length; j++)
transf[i][j] = bmatrr[i][j + keys.length];
for(int j = 0; j < values.length; j++)
transf[i][j + values.length] = (i == j ? 1 : 0);
}
Matrices.printMatrix("transf", transf);
Matrices.rref(transf, values.length);
Matrices.printMatrix("rref(transf)", transf);
/* read off the output */
DModSet[] ret = new DModSet[l1 - l2];
for(int j = l2; j < l1; j++) {
DModSet out = new DModSet();
for(int i = 0; i < values.length; i++) {
out.add(values[i], transf[i][j + values.length]);
}
ret[j - l2] = out;
}
return ret;
}
static void print_result(int s_max)
{
for(int s = s_max; s >= 0; s
for(int t = s; ; t++) {
int n = ngens(s,t);
if(n > 0)
System.out.printf("%2d ", ngens(s,t));
else if(n == 0)
System.out.print(" ");
else break;
}
System.out.println("
}
}
static void die_if(boolean test, String fail)
{
if(test) {
System.err.println(fail);
Thread.dumpStack();
System.err.println("Failing.");
System.exit(1);
}
}
public static void main(String[] args)
{
/* tests */
/* init */
/* make the sphere A-module */
/* resolve */
resolve(null); /* TMP */
/* print */
System.out.println("Conclusion:");
print_result(T_CAP);
}
}
class CellData
{
DModSet[] gimg; /* images of generators as dot-sums in bidegree s-1,t*/
DModSet[] kbasis; /* kernel basis dot-sums in bidegree s,t */
CellData() { }
CellData(DModSet[] g, DModSet[] k) {
gimg = g;
kbasis = k;
}
}
class Dot
{
/* kernel basis vector */
Sq sq;
int t;
int idx;
String id_cache = null;
Dot(Sq _sq, int _t, int _idx) {
sq = _sq; t = _t; idx = _idx;
}
public int hashCode()
{
return toString().hashCode();
}
public String toString()
{
if(id_cache == null)
id_cache = sq.toString() + "(" + t + ";" + idx + ")";
return id_cache;
}
public boolean equals(Object o)
{
return o.hashCode() == hashCode();
}
}
class Math
{
// static final int P = 3;
static final int P = 2;
// static final int[] inverse = { 0, 1, 3, 2, 4 }; /* multiplicative inverses mod P */
static final int[] inverse = { 0, 1, 2 }; /* multiplicative inverses mod P */
static boolean binom_2(int a, int b)
{
return ((~a) & b) == 0;
}
static Map<String,Integer> binom_cache = new HashMap<String,Integer>();
static String binom_cache_str(int a, int b) { return "("+a+"///"+b+"///"+Math.P+")"; }
static int binom_p(int a, int b)
{
String s = binom_cache_str(a,b);
Integer i = binom_cache.get(s);
if(i != null) return i;
int ret;
if(a < 0 || b < 0 || b > a)
ret = 0;
else if(a == 0)
ret = 1;
else ret = dmod(binom_p(a-1,b) + binom_p(a-1,b-1));
binom_cache.put(s,ret);
return ret;
}
static int dmod(int n)
{
return (n + (P << 8)) % P;
}
}
class Sq
{
int[] q; /* Indices of the power operations.
Mod 2, i indicates Sq^i.
Mod p>2, 2k(p-1) indicates P^i, 2k(p-1)+1 indicates B P^i. */
Sq(int[] qq) { q = qq; }
ModSet<Sq> times(Sq o)
{
int[] ret = new int[q.length + o.q.length];
for(int i = 0; i < q.length; i++)
ret[i] = q[i];
for(int i = 0; i < o.q.length; i++)
ret[q.length + i] = o.q[i];
if(Math.P == 2)
return new Sq(ret).resolve_2();
else
return new Sq(ret).resolve_p();
}
ModSet<Sq> resolve_2()
{
ModSet<Sq> ret = new ModSet<Sq>();
for(int i = q.length - 2; i >= 0; i
int a = q[i];
int b = q[i+1];
if(a >= 2 * b)
continue;
/* apply Adem relation */
for(int c = 0; c <= a/2; c++) {
if(! Math.binom_2(b - c - 1, a - 2*c))
continue;
int[] t;
if(c == 0) {
t = Arrays.copyOf(q, q.length - 1);
for(int k = i+2; k < q.length; k++)
t[k-1] = q[k];
t[i] = a+b-c;
} else {
t = Arrays.copyOf(q, q.length);
t[i] = a+b-c;
t[i+1] = c;
}
/* recurse */
for(Map.Entry<Sq,Integer> sub : new Sq(t).resolve_2().entrySet())
ret.add(sub.getKey(), sub.getValue());
}
return ret;
}
/* all clear */
ret.add(this, 1);
return ret;
}
ModSet<Sq> resolve_p()
{
ModSet<Sq> ret = new ModSet<Sq>();
int Q = 2 * (Math.P - 1); /* convenience */
for(int i = q.length - 2; i >= 0; i
int x = q[i];
int y = q[i+1];
if(x >= Math.P * y)
continue;
/* apply Adem relation */
int a = x / Q;
int b = y / Q;
int rx = x % Q;
int ry = y % Q;
for(int c = 0; c <= a/Math.P; c++) {
int sign = 1 - 2 * ((a+c) % 2);
// System.out.printf("adem: x=%d y=%d a=%d b=%d sign=%d\n", x, y, a, b, sign);
if(rx == 0 && ry == 0)
resolve_p_add_term(sign*Math.binom_p((Math.P-1)*(b-c)-1,a-c*Math.P), (a+b-c)*Q, c*Q, i, ret);
else if(rx == 1 && ry == 0)
resolve_p_add_term(sign*Math.binom_p((Math.P-1)*(b-c)-1,a-c*Math.P), (a+b-c)*Q+1, c*Q, i, ret);
else if(rx == 0 && ry == 1) {
resolve_p_add_term(sign*Math.binom_p((Math.P-1)*(b-c),a-c*Math.P), (a+b-c)*Q+1, c*Q, i, ret);
resolve_p_add_term(-sign*Math.binom_p((Math.P-1)*(b-c)-1,a-c*Math.P-1), (a+b-c)*Q, c*Q+1, i, ret);
}
else if(rx == 1 && ry == 1) {
resolve_p_add_term(-sign*Math.binom_p((Math.P-1)*(b-c)-1,a-c*Math.P-1), (a+b-c)*Q+1, c*Q+1, i, ret);
} else ResMain.die_if(true, "Bad Adem case.");
}
return ret;
}
/* all clear */
ret.add(this, 1);
return ret;
}
private void resolve_p_add_term(int coeff, int a, int b, int i, ModSet<Sq> ret)
{
// System.out.printf("adem_term: coeff=%d a=%d b=%d\n", coeff, a, b);
coeff = Math.dmod(coeff);
if(coeff == 0) return; /* save some work... */
int[] t;
if(b == 0) {
t = Arrays.copyOf(q, q.length - 1);
for(int k = i+2; k < q.length; k++)
t[k-1] = q[k];
t[i] = a;
} else {
t = Arrays.copyOf(q, q.length);
t[i] = a;
t[i+1] = b;
}
/* recurse */
for(Map.Entry<Sq,Integer> sub : new Sq(t).resolve_p().entrySet())
ret.add(sub.getKey(), sub.getValue() * coeff);
}
public String toString()
{
if(q.length == 0) return "1";
String s = "";
for(int i : q) s += "Sq"+i;
return s;
}
public int hashCode()
{
return toString().hashCode();
}
public boolean equals(Object o)
{
return toString().equals(o.toString());
}
/* The Steenrod algebra. */
static Iterable<Sq> steenrod(int n)
{
Iterable<int[]> p;
if(Math.P == 2) p = part_2(n,n);
else p = part_p(n,n);
Collection<Sq> ret = new ArrayList<Sq>();
for(int[] q : p)
ret.add(new Sq(q));
return ret;
}
static Map<String,Iterable<int[]>> part_cache = new HashMap<String,Iterable<int[]>>();
static String part_cache_keystr(int n, int max) {
return "("+n+"/"+max+"/"+Math.P+")";
}
static Iterable<int[]> part_2(int n, int max)
{
if(n == 0) { /* the trivial solution */
Collection<int[]> ret = new ArrayList<int[]>();
ret.add(new int[] {});
return ret;
}
if(max == 0) return new ArrayList<int[]>(); /* no solutions */
Iterable<int[]> ret0 = part_cache.get(part_cache_keystr(n,max));
if(ret0 != null) return ret0;
Collection<int[]> ret = new ArrayList<int[]>();
for(int i = (n+1)/2; i <= max; i++) {
for(int[] q0 : part_2(n-i, i/2)) {
int[] q1 = new int[q0.length + 1];
q1[0] = i;
for(int j = 0; j < q0.length; j++)
q1[j+1] = q0[j];
ret.add(q1);
}
}
part_cache.put(part_cache_keystr(n,max), ret);
return ret;
}
static Iterable<int[]> part_p(int n, int max)
{
if(n == 0) { /* the trivial solution */
Collection<int[]> ret = new ArrayList<int[]>();
ret.add(new int[] {});
return ret;
}
if(max == 0) return new ArrayList<int[]>(); /* no solutions */
Iterable<int[]> ret0 = part_cache.get(part_cache_keystr(n,max));
if(ret0 != null) return ret0;
Collection<int[]> ret = new ArrayList<int[]>();
for(int i = 0; i <= max; i += 2 * (Math.P - 1)) { /* XXX i could start higher? */
/* try P^i */
for(int[] q0 : part_p(n-i, i/Math.P)) {
int[] q1 = new int[q0.length + 1];
q1[0] = i;
for(int j = 0; j < q0.length; j++)
q1[j+1] = q0[j];
ret.add(q1);
}
/* try BP^i */
if(i+1 > max) break;
for(int[] q0 : part_p(n-(i+1), (i+1)/Math.P)) {
int[] q1 = new int[q0.length + 1];
q1[0] = i+1;
for(int j = 0; j < q0.length; j++)
q1[j+1] = q0[j];
ret.add(q1);
}
}
part_cache.put(part_cache_keystr(n,max), ret);
return ret;
}
}
class ModSet<T> extends HashMap<T,Integer>
{
public void add(T d, int mult)
{
int c;
if(containsKey(d)) c = get(d);
else c = 0;
c = Math.dmod(c + mult);
if(c == 0)
remove(d);
else
put(d, c);
}
public int getsafe(T d)
{
Integer i = get(d);
if(i == null)
return 0;
return i;
}
public boolean contains(T d)
{
return (getsafe(d) % Math.P != 0);
}
public void union(ModSet<T> s)
{
for(T d : s.keySet()) {
if(!containsKey(d))
put(d,1);
}
}
public String toString()
{
if(isEmpty())
return "0";
String s = "";
for(Map.Entry<T,Integer> e : entrySet()) {
if(s.length() != 0)
s += " + ";
s += e.getValue();
s += e.getKey().toString();
}
return s;
}
}
class DModSet extends ModSet<Dot> { /* to work around generic array restrictions */
public Dot[] toArray() {
return keySet().toArray(new Dot[] {});
}
}
class Matrices
{
/* Static matrix operation methods.
* It should be noted that matrices are assumed to be reduced to lowest
* positive residues (mod p), and these operations respect that. */
/* row-reduces a matrix (in place).
* returns an array giving the column position of the leading 1 in each row */
static int[] rref(int[][] mat, int preserve_right)
{
if(mat.length == 0)
return new int[] {};
int good_rows = 0;
int[] leading_cols = new int[mat.length];
for(int j = 0; j < mat[0].length - preserve_right; j++) {
int i;
for(i = good_rows; i < mat.length; i++) {
if(mat[i][j] != 0) break;
}
if(i == mat.length) continue;
//Matrices.printMatrix("rref 0", mat);
/* swap the rows */
int[] row = mat[good_rows];
mat[good_rows] = mat[i];
mat[i] = row;
i = good_rows++;
leading_cols[i] = j;
//Matrices.printMatrix("rref 1", mat);
/* normalize the row */
int inv = Math.inverse[mat[i][j]];
for(int k = 0; k < mat[0].length; k++)
mat[i][k] = (mat[i][k] * inv) % Math.P;
//Matrices.printMatrix("rref 2", mat);
/* clear the rest of the column */
for(int k = 0; k < mat.length; k++) {
if(k == i) continue;
int mul = Math.P - mat[k][j];
if(mul == Math.P) continue;
for(int l = 0; l < mat[0].length; l++)
mat[k][l] = (mat[k][l] + mat[i][l] * mul) % Math.P;
}
//Matrices.printMatrix("rref 3", mat);
}
return Arrays.copyOf(leading_cols, good_rows);
}
static void printMatrix(String name, int[][] mat)
{
if(!ResMain.MATRIX_DEBUG) return;
System.out.print(name + ":");
if(mat.length == 0) {
System.out.println(" <zero lines>");
return;
}
for(int i = 0; i < mat.length; i++) {
System.out.println();
for(int j = 0; j < mat[0].length; j++)
System.out.printf("%2d ", mat[i][j]);
}
System.out.println();
}
}
class DotMatrix extends HashMap<Dot,DModSet>
{
DModSet[] ker()
{
/* choose an ordering on all keys and values */
Dot[] keys = keySet().toArray(new Dot[]{});
DModSet val_set = new DModSet();
for(DModSet ms : values())
val_set.union(ms);
Dot[] values = val_set.toArray();
if(ResMain.DEBUG) System.out.printf("ker(): %d x %d\n", values.length, keys.length);
/* convert to a matrix of ints */
int[][] mat = new int[values.length][keys.length];
for(int i = 0; i < values.length; i++)
for(int j = 0; j < keys.length; j++)
mat[i][j] = Math.dmod(get(keys[j]).getsafe(values[i]));
Matrices.printMatrix("mat", mat);
/* convert to row-reduced echelon form */
int[] leading_cols = Matrices.rref(mat, 0);
Matrices.printMatrix("rref(mat)", mat);
/* read out the kernel */
int idx = 0;
List<DModSet> ker = new ArrayList<DModSet>();
for(int j = 0; j < keys.length; j++) {
/* keep an eye out for leading ones and skip them */
if(idx < leading_cols.length && leading_cols[idx] == j) {
idx++;
continue;
}
/* not a leading column, so we obtain a kernel element */
DModSet ms = new DModSet();
ms.add(keys[j], 1);
for(int i = 0; i < values.length; i++) {
if(mat[i][j] != 0) {
ResMain.die_if(i >= leading_cols.length, "bad rref: no leading one");
ms.add(keys[leading_cols[i]], -mat[i][j]);
}
}
ker.add(ms);
}
if(ResMain.DEBUG && ker.size() != 0) {
System.out.println("Kernel:");
for(DModSet dm : ker)
System.out.println(dm);
}
return ker.toArray(new DModSet[]{});
}
}
class AMod
{
/* TODO encode a general A-module and be able to resolve it */
}
|
package tv.rocketbeans.supermafiosi.screens;
import aurelienribon.tweenengine.BaseTween;
import aurelienribon.tweenengine.Tween;
import aurelienribon.tweenengine.TweenCallback;
import aurelienribon.tweenengine.TweenEquations;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import de.bitbrain.braingdx.assets.SharedAssetManager;
import de.bitbrain.braingdx.audio.AudioManager;
import de.bitbrain.braingdx.graphics.renderer.SpriteRenderer;
import de.bitbrain.braingdx.screens.AbstractScreen;
import de.bitbrain.braingdx.tweens.ActorTween;
import de.bitbrain.braingdx.tweens.GameObjectTween;
import de.bitbrain.braingdx.world.GameObject;
import tv.rocketbeans.supermafiosi.SuperMafiosiGame;
import tv.rocketbeans.supermafiosi.assets.Asset;
import tv.rocketbeans.supermafiosi.core.DialogManager;
import tv.rocketbeans.supermafiosi.graphics.BitmapFontBaker;
import tv.rocketbeans.supermafiosi.i18n.Bundle;
import tv.rocketbeans.supermafiosi.i18n.Message;
import tv.rocketbeans.supermafiosi.ui.DialogBox;
public class IntroScreen extends AbstractScreen<SuperMafiosiGame>
{
public static final int IMAGE_OLD_DON = 1;
public static final int IMAGE_LOGO = 2;
public IntroScreen(SuperMafiosiGame game)
{
super(game);
}
@Override
protected void onCreateStage(final Stage stage, int width, int height)
{
getLightingManager().setAmbientLight(new Color(0.1f, 0.1f, 0.2f, 0.2f));
getLightingManager().addPointLight("left", new Vector2(350f, Gdx.graphics.getHeight() - 50f), 1000f, new Color(1f, 0.6f, 0.4f, 1f));
getLightingManager().addPointLight("right", new Vector2(Gdx.graphics.getWidth() - 350f, Gdx.graphics.getHeight() - 50f), 1000f, new Color(1f, 0.6f, 0.4f, 1f));
Music dying_don_music = SharedAssetManager.getInstance().get(Asset.Music.DYING_DON, Music.class);
dying_don_music.setLooping(true);
AudioManager.getInstance().fadeInMusic(dying_don_music, 1f);
//bounceTitle(stage);
//showIntoText3(stage);
//showDonImage(stage);
Tween.call(new TweenCallback()
{
private int tick = 1;
private Label introlabel1 = null;
private Label introlabel2 = null;
private Label introlabel3 = null;
private Label introlabel4 = null;
private Label introlabel5 = null;
private DialogManager dialogManager = new DialogManager();
private GameObject donImageObject = null;
@Override
public void onEvent(int i, BaseTween<?> bt)
{
if (tick == 1)
{
introlabel1 = showIntroText(stage, Bundle.translations.get(Message.INTRO_SPEAKER_1));
}
if (tick == 10)
{
textFadeOut(introlabel1);
introlabel2 = showIntroText(stage, Bundle.translations.get(Message.INTRO_SPEAKER_2));
}
if (tick == 20)
{
textFadeOut(introlabel2);
dialogManager.addDialog("Don", Message.INTRO_DON_1, Asset.Textures.OLDDON);
dialogManager.addDialog("Don", Message.INTRO_DON_2, Asset.Textures.OLDDON);
dialogManager.addDialog("Don", Message.INTRO_DON_3, Asset.Textures.OLDDON);
dialogManager.addDialog("Don", Message.INTRO_DON_4, Asset.Textures.OLDDON);
dialogManager.addDialog("Don", Message.INTRO_DON_5, Asset.Textures.OLDDON);
dialogManager.addDialog("Don", Message.INTRO_DON_6, Asset.Textures.OLDDON);
dialogManager.addDialog("Don", Message.INTRO_DON_7, Asset.Textures.OLDDON);
dialogManager.addDialog("Don", Message.INTRO_DON_8, Asset.Textures.OLDDON);
dialogManager.addDialog("Don", Message.INTRO_DON_9, Asset.Textures.OLDDON);
dialogManager.addDialog("Cappo", Message.INTRO_KAPPO_1, Asset.Textures.KAPPO);
dialogManager.addDialog("Cappo", Message.INTRO_KAPPO_2, Asset.Textures.KAPPO);
donImageObject = showDonImage(stage, dialogManager);
}
if (tick == 20)
{
dialogManager.nextDialog();
}
if (tick == 25)
{
dialogManager.nextDialog();
}
if (tick == 30)
{
dialogManager.nextDialog();
}
if (tick == 35)
{
dialogManager.nextDialog();
}
if (tick == 40)
{
dialogManager.nextDialog();
}
if (tick == 45)
{
dialogManager.nextDialog();
}
if (tick == 50)
{
dialogManager.nextDialog();
}
if (tick == 55)
{
dialogManager.nextDialog();
}
if (tick == 60)
{
dialogManager.nextDialog();
}
if (tick == 65)
{
ImageFadeOut(donImageObject);
dialogManager.nextDialog();
}
if (tick == 70)
{
dialogManager.nextDialog();
}
if (tick == 75)
{
dialogManager.nextDialog();
introlabel3 = showIntroText(stage, Bundle.translations.get(Message.INTRO_SPEAKER_3));
}
if (tick == 85)
{
Music dying_don_music = SharedAssetManager.getInstance().get(Asset.Music.DYING_DON, Music.class);
AudioManager.getInstance().fadeOutMusic(dying_don_music, 5f);
textFadeOut(introlabel3);
introlabel4 = showIntroText(stage, Bundle.translations.get(Message.INTRO_SPEAKER_4));
Music menu_music = SharedAssetManager.getInstance().get(Asset.Music.MENU_CHAR_SELECT_INTRO, Music.class);
menu_music.setLooping(true);
AudioManager.getInstance().fadeInMusic(menu_music, 1f);
}
if (tick == 95)
{
textFadeOut(introlabel4);
introlabel5 = showIntroText(stage, Bundle.translations.get(Message.INTRO_SPEAKER_5));
}
if(tick == 105)
{
textFadeOut(introlabel5);
bounceTitle(stage);
}
tick++;
}
}).repeat(Tween.INFINITY, 1f).start(getTweenManager());
/**
* Skip Intro by mr. anykey
*/
stage.addListener(new InputListener()
{
public boolean keyDown(InputEvent event, int keycode)
{
changeToMenue();
return false;
}
});
}
private void changeToMenue()
{
Music menu_music_main = SharedAssetManager.getInstance().get(Asset.Music.MENU_CHAR_SELECT_MAIN, Music.class);
menu_music_main.setLooping(true);
if (!menu_music_main.isPlaying())
{
AudioManager.getInstance().stopMusic(Asset.Music.DYING_DON);
AudioManager.getInstance().fadeInMusic(Asset.Music.MENU_CHAR_SELECT_MAIN);
}
getScreenTransitions().out(new MenuScreen(getGame()), 1);
}
private Label showIntroText(final Stage stage, String text)
{
final Label introLabel1 = createLabel(text);
setLabelToCenter(introLabel1);
stage.addActor(introLabel1);
textFadeIn(introLabel1);
return introLabel1;
}
private void setLabelToCenter(Label label)
{
label.setPosition(Gdx.graphics.getWidth() / 2 - label.getWidth() / 2, Gdx.graphics.getHeight() / 2);
}
private void bounceTitle(final Stage stage)
{
final GameObject logoGameObject = getGameWorld().addObject();
logoGameObject.setType(IMAGE_LOGO);
Texture logotexture = SharedAssetManager.getInstance().get(Asset.Textures.LOGO);
logoGameObject.setDimensions(logotexture.getWidth(), logotexture.getHeight());
logoGameObject.setPosition(Gdx.graphics.getWidth() / 2 - logoGameObject.getWidth() / 2, Gdx.graphics.getWidth());
getRenderManager().register(IMAGE_LOGO, new SpriteRenderer(Asset.Textures.LOGO));
Tween.to(logoGameObject, GameObjectTween.POS_Y, 5f).target(Gdx.graphics.getHeight() / 2 - logotexture.getHeight() / 2).ease(TweenEquations.easeOutBounce).start(getTweenManager());
}
private GameObject showDonImage(final Stage stage, DialogManager dialogManager)
{
final GameObject donImageObject = getGameWorld().addObject();
donImageObject.setType(IMAGE_OLD_DON);
donImageObject.setDimensions(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
donImageObject.setPosition(0, 0);
donImageObject.getColor().a = 0f;
getRenderManager().register(IMAGE_OLD_DON, new SpriteRenderer(Asset.Textures.KRANKENBETT));
ImageFadeIn(donImageObject);
DialogBox dialogBox = new DialogBox(dialogManager);
dialogBox.setHeight(150f);
dialogBox.setWidth(Gdx.graphics.getWidth());
stage.addActor(dialogBox);
return donImageObject;
}
private Label createLabel(String text)
{
Label.LabelStyle defaultlabelstyle = new Label.LabelStyle();
defaultlabelstyle.font = BitmapFontBaker.bake(Asset.Fonts.UPHEAVTT, 22);
defaultlabelstyle.fontColor = Color.WHITE;
defaultlabelstyle.fontColor.a = 1f;
final Label introLabel1 = new Label(text, defaultlabelstyle);
introLabel1.setPosition(20, Gdx.graphics.getHeight() / 2);
return introLabel1;
}
private void ImageFadeIn(GameObject gameobject)
{
Tween.to(gameobject, GameObjectTween.ALPHA, 5f).target(1f).ease(TweenEquations.easeNone)
.start(getTweenManager());
}
private void ImageFadeOut(GameObject gameobject)
{
Tween.to(gameobject, GameObjectTween.ALPHA, 5f).target(0f).ease(TweenEquations.easeNone)
.start(getTweenManager());
}
private void textFadeIn(Label label)
{
label.getColor().a = 0f;
Tween.to(label, ActorTween.ALPHA, 5f).target(1f).ease(TweenEquations.easeNone)
.start(getTweenManager());
}
private void textFadeOut(Label label)
{
Tween.to(label, ActorTween.ALPHA, 5f).target(0f).ease(TweenEquations.easeNone)
.start(getTweenManager());
}
}
|
package imagej.updater.ui;
import imagej.updater.core.Conflicts;
import imagej.updater.core.Conflicts.Conflict;
import imagej.updater.core.Conflicts.Resolution;
import imagej.updater.core.Diff;
import imagej.updater.core.Diff.Mode;
import imagej.updater.core.FileObject;
import imagej.updater.core.FileObject.Action;
import imagej.updater.core.FileObject.Status;
import imagej.updater.core.FilesCollection;
import imagej.updater.core.FilesCollection.Filter;
import imagej.updater.core.Dependency;
import imagej.updater.core.FilesUploader;
import imagej.updater.core.Installer;
import imagej.updater.core.UpdateSite;
import imagej.updater.util.Downloadable;
import imagej.updater.util.Downloader;
import imagej.updater.util.Progress;
import imagej.updater.util.StderrProgress;
import imagej.updater.util.UpdaterUserInterface;
import imagej.updater.util.Util;
import imagej.util.AppUtils;
import java.awt.Frame;
import java.io.Console;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.scijava.log.LogService;
import org.scijava.util.FileUtils;
/**
* This is the command-line interface into the ImageJ Updater.
*
* @author Johannes Schindelin
*/
public class CommandLine {
protected static LogService log = Util.getLogService();
protected FilesCollection files;
protected Progress progress;
private FilesCollection.DependencyMap dependencyMap;
private boolean checksummed = false;
/**
* Determines whether die() should exit or throw a RuntimeException.
*/
private boolean standalone;
@Deprecated
public CommandLine() {
this(AppUtils.getBaseDirectory(), 80);
}
public CommandLine(final File ijDir, final int columnCount) {
this(ijDir, columnCount, null);
}
public CommandLine(final File ijDir, final int columnCount,
final Progress progress) {
this.progress = progress == null ? new StderrProgress(columnCount)
: progress;
files = new FilesCollection(log, ijDir);
}
private void ensureChecksummed() {
if (checksummed) {
return;
}
String warnings;
try {
warnings = files.downloadIndexAndChecksum(progress);
} catch (final Exception e) {
throw die("Received exception: " + e.getMessage());
}
if (!warnings.equals("")) {
log.warn(warnings);
}
checksummed = true;
}
protected class FileFilter implements Filter {
protected Set<String> fileNames;
public FileFilter(final List<String> files) {
if (files != null && files.size() > 0) {
fileNames = new HashSet<String>();
for (final String file : files)
fileNames.add(FileObject.getFilename(file, true));
}
}
@Override
public boolean matches(final FileObject file) {
if (!file.isUpdateablePlatform(files)) {
return false;
}
if (fileNames != null
&& !fileNames.contains(file.getFilename(true))) {
return false;
}
return file.getStatus() != Status.OBSOLETE_UNINSTALLED;
}
}
public void diff(final List<String> list) {
ensureChecksummed();
final Diff diff = new Diff(System.out, files.util);
Mode mode = Mode.CLASS_FILE_DIFF;
while (list.size() > 0 && list.get(0).startsWith("
final String option = list.remove(0);
mode = Mode.valueOf(option.substring(2).replace('-', '_')
.toUpperCase());
}
for (final FileObject file : files.filter(new FileFilter(list)))
try {
final String filename = file.getLocalFilename(false);
final URL remote = new URL(files.getURL(file));
final URL local = files.prefix(filename).toURI().toURL();
diff.showDiff(filename, remote, local, mode);
} catch (final IOException e) {
log.error(e);
}
}
public void listCurrent(final List<String> list) {
ensureChecksummed();
for (final FileObject file : files.filter(new FileFilter(list)))
System.out.println(file.filename + "-" + file.getTimestamp());
}
public void list(final List<String> list, Filter filter) {
ensureChecksummed();
if (filter == null) {
filter = new FileFilter(list);
} else {
filter = files.and(new FileFilter(list), filter);
}
files.sort();
for (final FileObject file : files.filter(filter)) {
System.out.println(file.filename + "\t(" + file.getStatus() + ")\t"
+ file.getTimestamp());
}
}
public void list(final List<String> list) {
list(list, null);
}
public void listUptodate(final List<String> list) {
list(list, files.is(Status.INSTALLED));
}
public void listNotUptodate(final List<String> list) {
list(list,
files.not(files.oneOf(new Status[] { Status.OBSOLETE,
Status.INSTALLED, Status.LOCAL_ONLY })));
}
public void listUpdateable(final List<String> list) {
list(list, files.is(Status.UPDATEABLE));
}
public void listModified(final List<String> list) {
list(list, files.is(Status.MODIFIED));
}
public void listLocalOnly(final List<String> list) {
list(list, files.is(Status.LOCAL_ONLY));
}
public void listFromSite(final List<String> sites) {
if (sites.size() != 1)
throw die("Usage: list-from-site <name>");
list(null, files.isUpdateSite(sites.get(0)));
}
public void show(final List<String> list) {
for (final String filename : list) {
show(filename);
}
}
public void show(final String filename) {
ensureChecksummed();
final FileObject file = files.get(filename);
if (file == null) {
log.error("File not found: " + filename);
} else {
show(file);
}
}
public void show(final FileObject file) {
ensureChecksummed();
if (dependencyMap == null) {
dependencyMap = files.getDependencies(files, false);
}
System.out.println();
System.out.println("File: " + file.getFilename(true));
if (!file.getFilename(true).equals(file.localFilename)) {
System.out.println("(Local filename: " + file.localFilename + ")");
}
String description = file.description;
if (description != null && description.length() > 0) {
description = "\t" + (description.replaceAll("\n", "\n\t"));
System.out.println("Description:\n" + description);
}
System.out.println("Update site: " + file.updateSite);
if (file.current == null) {
System.out.println("Removed from update site");
} else {
System.out.println("URL: " + files.getURL(file));
System.out.println("checksum: " + file.current.checksum
+ ", timestamp: " + file.current.timestamp);
}
if (file.localChecksum != null
&& (file.current == null || !file.localChecksum
.equals(file.current.checksum))) {
System.out.println("Local checksum: "
+ file.localChecksum
+ " ("
+ (file.hasPreviousVersion(file.localChecksum) ? ""
: "NOT a ") + "previous version)");
}
final StringBuilder builder = new StringBuilder();
for (final FileObject dependency : file.getFileDependencies(files,
false)) {
if (builder.length() > 0)
builder.append(", ");
builder.append(dependency.getFilename(true));
}
if (builder.length() > 0) {
System.out.println("Dependencies: " + builder.toString());
}
final FilesCollection dependencees = getDependencees(file);
if (dependencees != null && !dependencees.isEmpty()) {
builder.setLength(0);
for (final FileObject dependencee : dependencees) {
if (builder.length() > 0)
builder.append(", ");
builder.append(dependencee.getFilename(true));
}
if (builder.length() > 0) {
System.out.println("Have '" + file.getFilename(true)
+ "' as dependency: " + builder.toString());
}
}
}
private FilesCollection getDependencees(final FileObject file) {
if (dependencyMap == null)
dependencyMap = files.getDependencies(files, false);
return dependencyMap.get(file);
}
class OneFile implements Downloadable {
FileObject file;
OneFile(final FileObject file) {
this.file = file;
}
@Override
public File getDestination() {
return files.prefix(file.filename);
}
@Override
public String getURL() {
return files.getURL(file);
}
@Override
public long getFilesize() {
return file.filesize;
}
@Override
public String toString() {
return file.filename;
}
}
public void download(final FileObject file) {
ensureChecksummed();
try {
new Downloader(progress, files.util).start(new OneFile(file));
if (file.executable && !files.util.platform.startsWith("win")) {
try {
Runtime.getRuntime().exec(
new String[] { "chmod", "0755",
files.prefix(file.filename).getPath() });
} catch (final Exception e) {
e.printStackTrace();
throw die("Could not mark " + file.filename
+ " as executable");
}
}
log.info("Installed " + file.filename);
} catch (final IOException e) {
log.error("IO error downloading " + file.filename, e);
}
}
public void delete(final FileObject file) {
if (new File(file.filename).delete()) {
log.info("Deleted " + file.filename);
} else {
log.error("Failed to delete " + file.filename);
}
}
public void update(final List<String> list) {
update(list, false);
}
public void update(final List<String> list, final boolean force) {
update(list, force, false);
}
public void update(final List<String> list, final boolean force,
final boolean pristine) {
ensureChecksummed();
try {
for (final FileObject file : files.filter(new FileFilter(list))) {
if (file.getStatus() == Status.LOCAL_ONLY) {
if (pristine)
file.setAction(files, Action.UNINSTALL);
} else if (file.isObsolete()) {
if (file.getStatus() == Status.OBSOLETE) {
log.info("Removing " + file.filename);
file.stageForUninstall(files);
} else if (file.getStatus() == Status.OBSOLETE_MODIFIED) {
if (force || pristine) {
file.stageForUninstall(files);
log.info("Removing " + file.filename);
} else {
log.warn("Skipping obsolete, but modified "
+ file.filename);
}
}
} else if (file.getStatus() != Status.INSTALLED
&& !file.stageForUpdate(files, force)) {
log.warn("Skipping " + file.filename);
}
// remove obsolete versions in pristine mode
if (pristine) {
final File correctVersion = files.prefix(file);
final File[] versions = FileUtils.getAllVersions(
correctVersion.getParentFile(),
correctVersion.getName());
if (versions != null) {
for (final File version : versions) {
if (!version.equals(correctVersion)) {
log.info("Deleting obsolete version " + version);
if (!version.delete()) {
log.error("Could not delete " + version
+ "!");
}
}
}
}
}
}
resolveConflicts(false);
final Installer installer = new Installer(files, progress);
installer.start();
installer.moveUpdatedIntoPlace();
files.write();
} catch (final Exception e) {
if (e.getMessage().indexOf("conflicts") >= 0) {
log.error("Could not update due to conflicts:");
for (final Conflict conflict : new Conflicts(files)
.getConflicts(false)) {
log.error(conflict.getFilename() + ": "
+ conflict.getConflict());
}
} else {
log.error("Error updating", e);
}
}
}
public void upload(final List<String> list) {
if (list == null) {
throw die("Which files do you mean to upload?");
}
boolean forceUpdateSite = false, forceShadow = false, simulate = false, forgetMissingDeps = false;
String updateSite = null;
while (list.size() > 0 && list.get(0).startsWith("-")) {
final String option = list.remove(0);
if ("--update-site".equals(option) || "--site".equals(option)) {
if (list.size() < 1) {
throw die("Missing name for --update-site");
}
updateSite = list.remove(0);
forceUpdateSite = true;
} else if ("--simulate".equals(option)) {
simulate = true;
} else if ("--force-shadow".equals(option)) {
forceShadow = true;
} else if ("--forget-missing-dependencies".equals(option)) {
forgetMissingDeps = true;
} else {
throw die("Unknown option: " + option);
}
}
if (list.size() == 0) {
throw die("Which files do you mean to upload?");
}
if (forceShadow && updateSite == null) {
throw die("Need an explicit update site with --force-shadow");
}
ensureChecksummed();
int count = 0;
for (final String name : list) {
final FileObject file = files.get(name);
if (file == null) {
throw die("No file '" + name + "' found!");
}
if (file.getStatus() == Status.INSTALLED) {
if (forceShadow && !updateSite.equals(file.updateSite)) {
// TODO: add overridden update site
file.updateSite = updateSite;
file.setStatus(Status.MODIFIED);
log.info("Uploading (force-shadow) '" + name
+ "' to site '" + updateSite + "'");
} else {
log.info("Skipping up-to-date " + name);
continue;
}
}
handleLauncherForUpload(file);
if (updateSite == null) {
updateSite = file.updateSite;
if (updateSite == null) {
updateSite = file.updateSite = chooseUploadSite(name);
}
if (updateSite == null) {
throw die("Canceled");
}
} else if (file.updateSite == null) {
log.info("Uploading new file '" + name + "' to site '"
+ updateSite + "'");
file.updateSite = updateSite;
} else if (!file.updateSite.equals(updateSite)) {
if (forceUpdateSite) {
file.updateSite = updateSite;
} else {
throw die("Cannot upload to multiple update sites ("
+ list.get(0) + " to " + updateSite + " and "
+ name + " to " + file.updateSite + ")");
}
}
if (file.getStatus() == Status.NOT_INSTALLED
|| file.getStatus() == Status.NEW) {
log.info("Removing file '" + name + "'");
file.setAction(files, Action.REMOVE);
} else {
if (simulate) {
log.info("Would upload '" + name + "'");
}
file.setAction(files, Action.UPLOAD);
}
count++;
}
if (count == 0) {
log.info("Nothing to upload");
return;
}
if (updateSite != null
&& files.getUpdateSite(updateSite, false) == null) {
throw die("Unknown update site: '" + updateSite + "'");
}
if (forgetMissingDeps) {
for (final Conflict conflict : new Conflicts(files)
.getConflicts(true)) {
final String message = conflict.getConflict();
if (!message.startsWith("Depends on ")
|| !message.endsWith(" which is about to be removed.")) {
continue;
}
log.info("Breaking dependency: " + conflict);
for (final Resolution resolution : conflict.getResolutions()) {
if (resolution.getDescription().startsWith("Break")) {
resolution.resolve();
break;
}
}
}
}
if (simulate) {
final Iterable<Conflict> conflicts = new Conflicts(files)
.getConflicts(true);
if (Conflicts.needsFeedback(conflicts)) {
log.error("Unresolved upload conflicts!\n\n"
+ Util.join("\n", conflicts));
} else {
log.info("Would upload/remove " + count + " to/from "
+ getLongUpdateSiteName(updateSite));
}
return;
}
log.info("Uploading to " + getLongUpdateSiteName(updateSite));
upload(updateSite);
}
public void uploadCompleteSite(final List<String> list) {
if (list == null) {
throw die("Which files do you mean to upload?");
}
boolean ignoreWarnings = false, forceShadow = false, simulate = false;
while (list.size() > 0 && list.get(0).startsWith("-")) {
final String option = list.remove(0);
if ("--force".equals(option)) {
ignoreWarnings = true;
} else if ("--force-shadow".equals(option)) {
forceShadow = true;
} else if ("--simulate".equals(option)) {
simulate = true;
} else if ("--platforms".equals(option)) {
if (list.size() == 0) {
throw die("Need a comma-separated list of platforms with --platform");
}
files.util.setUpdateablePlatforms(list.remove(0).split(","));
} else {
throw die("Unknown option: " + option);
}
}
if (list.size() != 1) {
throw die("Which files do you mean to upload?");
}
final String updateSite = list.get(0);
ensureChecksummed();
if (files.getUpdateSite(updateSite, false) == null) {
throw die("Unknown update site '" + updateSite + "'");
}
int removeCount = 0, uploadCount = 0, warningCount = 0;
for (final FileObject file : files) {
if (!file.isUpdateablePlatform(files)) {
continue;
}
final String name = file.filename;
handleLauncherForUpload(file);
switch (file.getStatus()) {
case OBSOLETE:
case OBSOLETE_MODIFIED:
if (forceShadow) {
file.updateSite = updateSite;
file.setAction(files, Action.UPLOAD);
if (simulate) {
log.info("Would upload " + file.filename);
}
uploadCount++;
} else if (ignoreWarnings && updateSite.equals(file.updateSite)) {
file.setAction(files, Action.UPLOAD);
if (simulate) {
log.info("Would re-upload " + file.filename);
}
uploadCount++;
} else {
log.warn("Obsolete '" + name + "' still installed!");
warningCount++;
}
break;
case UPDATEABLE:
case MODIFIED:
if (!forceShadow && !updateSite.equals(file.updateSite)) {
log.warn("'" + name + "' of update site '"
+ file.updateSite + "' is not up-to-date!");
warningCount++;
continue;
}
//$FALL-THROUGH$
case LOCAL_ONLY:
file.updateSite = updateSite;
file.setAction(files, Action.UPLOAD);
if (simulate) {
log.info("Would upload new "
+ (file.getStatus() == Status.LOCAL_ONLY ? ""
: "version of ")
+ file.getLocalFilename(true));
}
uploadCount++;
break;
case NEW:
case NOT_INSTALLED:
// special: keep tools-1.4.2.jar, needed for ImageJ 1.x
if ("ImageJ".equals(updateSite)
&& file.getFilename(true).equals("jars/tools.jar")) {
break;
}
file.setAction(files, Action.REMOVE);
if (simulate) {
log.info("Would mark " + file.filename + " obsolete");
}
removeCount++;
break;
case INSTALLED:
case OBSOLETE_UNINSTALLED:
// leave these alone
break;
}
}
// remove all obsolete dependencies of the same upload site
for (final FileObject file : files.forUpdateSite(updateSite)) {
if (!file.willBeUpToDate()) {
continue;
}
for (final FileObject dependency : file.getFileDependencies(files,
false)) {
if (dependency.willNotBeInstalled()
&& updateSite.equals(dependency.updateSite)) {
file.removeDependency(dependency.getFilename(false));
}
}
if (ignoreWarnings) {
final List<String> obsoleteDependencies = new ArrayList<String>();
for (final Dependency dependency : file.getDependencies()) {
final FileObject dep = files.get(dependency.filename);
if (dep != null && dep.isObsolete()) {
obsoleteDependencies.add(dependency.filename);
}
}
for (final String filename : obsoleteDependencies) {
file.removeDependency(filename);
}
}
}
if (!ignoreWarnings && warningCount > 0) {
throw die("Use --force to ignore warnings and upload anyway");
}
if (removeCount == 0 && uploadCount == 0) {
log.info("Nothing to upload");
return;
}
if (simulate) {
final Iterable<Conflict> conflicts = new Conflicts(files)
.getConflicts(true);
if (Conflicts.needsFeedback(conflicts)) {
log.error("Unresolved upload conflicts!\n\n"
+ Util.join("\n", conflicts));
} else {
log.info("Would upload " + uploadCount + " (removing "
+ removeCount + ") to "
+ getLongUpdateSiteName(updateSite));
}
return;
}
log.info("Uploading " + uploadCount + " (removing " + removeCount
+ ") to " + getLongUpdateSiteName(updateSite));
upload(updateSite);
}
private void handleLauncherForUpload(final FileObject file) {
if (file.getStatus() == Status.LOCAL_ONLY
&& files.util.isLauncher(file.filename)) {
file.executable = true;
file.addPlatform(Util.platformForLauncher(file.filename));
for (final String fileName : new String[] { "jars/ij-launcher.jar" }) {
final FileObject dependency = files.get(fileName);
if (dependency != null) {
file.addDependency(files, dependency);
}
}
}
}
private void upload(final String updateSite) {
resolveConflicts(true);
FilesUploader uploader = null;
try {
uploader = new FilesUploader(null, files, updateSite, progress);
if (!uploader.login())
throw die("Login failed!");
uploader.upload(progress);
files.write();
} catch (final Throwable e) {
final String message = e.getMessage();
if (message != null && message.indexOf("conflicts") >= 0) {
log.error("Could not upload due to conflicts:");
for (final Conflict conflict : new Conflicts(files)
.getConflicts(true)) {
log.error(conflict.getFilename() + ": "
+ conflict.getConflict());
}
} else {
e.printStackTrace();
throw die("Error during upload: " + e);
}
if (uploader != null)
uploader.logout();
}
}
private void resolveConflicts(final boolean forUpload) {
final Console console = System.console();
final Conflicts conflicts = new Conflicts(files);
for (;;) {
final Iterable<Conflict> list = conflicts.getConflicts(forUpload);
if (!Conflicts.needsFeedback(list)) {
for (final Conflict conflict : list) {
final String filename = conflict.getFilename();
log.info((filename != null ? filename + ": " : "")
+ conflict.getConflict());
}
return;
}
if (console == null) {
final StringBuilder builder = new StringBuilder();
for (final Conflict conflict : list) {
final String filename = conflict.getFilename();
builder.append((filename != null ? filename + ": " : "")
+ conflict.getConflict());
}
throw die("There are conflicts:\n" + builder);
}
for (final Conflict conflict : list) {
final String filename = conflict.getFilename();
if (filename != null) {
console.printf("File '%s':\n", filename);
}
console.printf("%s\n", conflict.getConflict());
if (conflict.getResolutions().length == 0) {
continue;
}
console.printf("\nResolutions:\n");
final Resolution[] resolutions = conflict.getResolutions();
for (int i = 0; i < resolutions.length; i++) {
console.printf("% 3d %s\n", i + 1,
resolutions[i].getDescription());
}
for (;;) {
final String answer = console.readLine("\nResolution? ");
if (answer == null || answer.toLowerCase().startsWith("x")) {
throw die("Aborted");
}
try {
final int index = Integer.parseInt(answer);
if (index > 0 && index <= resolutions.length) {
resolutions[index - 1].resolve();
break;
}
console.printf(
"Invalid choice: %d (must be between 1 and %d)",
index, resolutions.length);
} catch (final NumberFormatException e) {
console.printf("Invalid answer: %s\n", answer);
}
}
}
}
}
public String chooseUploadSite(final String file) {
final List<String> names = new ArrayList<String>();
final List<String> options = new ArrayList<String>();
for (final String name : files.getUpdateSiteNames(false)) {
final UpdateSite updateSite = files.getUpdateSite(name, true);
if (updateSite.getUploadDirectory() == null
|| updateSite.getUploadDirectory().equals("")) {
continue;
}
names.add(name);
options.add(getLongUpdateSiteName(name));
}
if (names.size() == 0) {
log.error("No uploadable sites found");
return null;
}
final String message = "Choose upload site for file '" + file + "'";
final int index = UpdaterUserInterface.get().optionDialog(message,
message, options.toArray(new String[options.size()]), 0);
return index < 0 ? null : names.get(index);
}
public String getLongUpdateSiteName(final String name) {
final UpdateSite site = files.getUpdateSite(name, true);
String host = site.getHost();
if (host == null || host.equals("")) {
host = "";
} else {
if (host.startsWith("webdav:")) {
final int colon = host.indexOf(':', 8);
if (colon > 0) {
host = host.substring(0, colon) + ":<password>";
}
}
host += ":";
}
return name + " (" + host + site.getUploadDirectory() + ")";
}
public void listUpdateSites(Collection<String> args) {
ensureChecksummed();
if (args == null || args.size() == 0)
args = files.getUpdateSiteNames(true);
for (final String name : args) {
final UpdateSite site = files.getUpdateSite(name, true);
System.out.print(name + (site.isActive() ? "" : " (DISABLED)")
+ ": " + site.getURL());
if (site.getUploadDirectory() == null)
System.out.println();
else
System.out.println(" (upload host: " + site.getHost()
+ ", upload directory: " + site.getUploadDirectory()
+ ")");
}
}
public void addOrEditUploadSite(final List<String> args, final boolean add) {
if (args.size() != 2 && args.size() != 4)
throw die("Usage: " + (add ? "add" : "edit")
+ "-update-site <name> <url> [<host> <upload-directory>]");
addOrEditUploadSite(args.get(0), args.get(1),
args.size() > 2 ? args.get(2) : null,
args.size() > 3 ? args.get(3) : null, add);
}
public void addOrEditUploadSite(final String name, final String url,
final String sshHost, final String uploadDirectory,
final boolean add) {
ensureChecksummed();
final UpdateSite site = files.getUpdateSite(name, true);
if (add) {
if (site != null)
throw die("Site '" + name + "' was already added!");
files.addUpdateSite(name, url, sshHost, uploadDirectory, 0l);
} else {
if (site == null)
throw die("Site '" + name + "' was not yet added!");
site.setURL(url);
site.setHost(sshHost);
site.setUploadDirectory(uploadDirectory);
site.setActive(true);
}
try {
files.write();
} catch (final Exception e) {
UpdaterUserInterface.get().handleException(e);
throw die("Could not write local file database");
}
}
public void removeUploadSite(final List<String> names) {
if (names == null || names.size() < 1) {
throw die("Which update-site do you want to remove, exactly?");
}
removeUploadSite(names.toArray(new String[names.size()]));
}
public void removeUploadSite(final String... names) {
ensureChecksummed();
for (final String name : names) {
files.removeUpdateSite(name);
}
try {
files.write();
} catch (final Exception e) {
UpdaterUserInterface.get().handleException(e);
throw die("Could not write local file database");
}
}
@Deprecated
public static CommandLine getInstance() {
try {
return new CommandLine();
} catch (final Exception e) {
e.printStackTrace();
log.error("Could not parse db.xml.gz: " + e.getMessage());
throw new RuntimeException(e);
}
}
private static List<String> makeList(final String[] list, int start) {
final List<String> result = new ArrayList<String>();
while (start < list.length)
result.add(list[start++]);
return result;
}
/**
* Print an error message and exit the process with an error.
*
* Note: Java has no "noreturn" annotation, but you can always write:
* <code>throw die(<message>)</code> to make the Java compiler understand.
*
* @param message
* the error message
* @return a dummy return value to be able to use "throw die(...)" to shut
* up the compiler
*/
private RuntimeException die(final String message) {
if (standalone) {
log.error(message);
System.exit(1);
}
return new RuntimeException(message);
}
public void usage() {
final StringBuilder diffOptions = new StringBuilder();
diffOptions.append("[ ");
for (final Mode mode : Mode.values()) {
if (diffOptions.length() > 2) {
diffOptions.append(" | ");
}
diffOptions.append("
+ mode.toString().toLowerCase().replace(' ', '-'));
}
diffOptions.append(" ]");
throw die("Usage: imagej.updater.ui.CommandLine <command>\n"
+ "\n"
+ "Commands:\n"
+ "\tdiff "
+ diffOptions
+ " [<files>]\n"
+ "\tlist [<files>]\n"
+ "\tlist-uptodate [<files>]\n"
+ "\tlist-not-uptodate [<files>]\n"
+ "\tlist-updateable [<files>]\n"
+ "\tlist-modified [<files>]\n"
+ "\tlist-current [<files>]\n"
+ "\tlist-local-only [<files>]\n"
+ "\tlist-from-site <name>\n"
+ "\tshow [<files>]\n"
+ "\tupdate [<files>]\n"
+ "\tupdate-force [<files>]\n"
+ "\tupdate-force-pristine [<files>]\n"
+ "\tupload [--simulate] [--[update-]site <name>] [--force-shadow] [--forget-missing-dependencies] [<files>]\n"
+ "\tupload-complete-site [--simulate] [--force] [--force-shadow] [--platforms <platform>[,<platform>...]] <name>\n"
+ "\tlist-update-sites [<nick>...]\n"
+ "\tadd-update-site <nick> <url> [<host> <upload-directory>]\n"
+ "\tedit-update-site <nick> <url> [<host> <upload-directory>]");
}
public static void main(final String... args) {
try {
main(AppUtils.getBaseDirectory(), 80, null, true, args);
} catch (final RuntimeException e) {
log.error(e);
System.exit(1);
} catch (final Exception e) {
log.error("Could not parse db.xml.gz", e);
System.exit(1);
}
}
public static void main(final File ijDir, final int columnCount,
final String... args) {
main(ijDir, columnCount, null, args);
}
public static void main(final File ijDir, final int columnCount,
final Progress progress, final String... args) {
main(ijDir, columnCount, progress, false, args);
}
private static void main(final File ijDir, final int columnCount,
final Progress progress, final boolean standalone,
final String[] args) {
String http_proxy = System.getenv("http_proxy");
if (http_proxy != null && http_proxy.startsWith("http:
final int colon = http_proxy.indexOf(':', 7);
final int slash = http_proxy.indexOf('/', 7);
int port = 80;
if (colon < 0) {
http_proxy = slash < 0 ? http_proxy.substring(7) : http_proxy
.substring(7, slash);
} else {
port = Integer.parseInt(slash < 0 ? http_proxy
.substring(colon + 1) : http_proxy.substring(colon + 1,
slash));
http_proxy = http_proxy.substring(7, colon);
}
System.setProperty("http.proxyHost", http_proxy);
System.setProperty("http.proxyPort", "" + port);
} else {
Util.useSystemProxies();
}
Authenticator.setDefault(new ProxyAuthenticator());
setUserInterface();
final CommandLine instance = new CommandLine(ijDir, columnCount,
progress);
instance.standalone = standalone;
if (args.length == 0) {
instance.usage();
}
final String command = args[0];
if (command.equals("diff")) {
instance.diff(makeList(args, 1));
} else if (command.equals("list")) {
instance.list(makeList(args, 1));
} else if (command.equals("list-current")) {
instance.listCurrent(makeList(args, 1));
} else if (command.equals("list-uptodate")) {
instance.listUptodate(makeList(args, 1));
} else if (command.equals("list-not-uptodate")) {
instance.listNotUptodate(makeList(args, 1));
} else if (command.equals("list-updateable")) {
instance.listUpdateable(makeList(args, 1));
} else if (command.equals("list-modified")) {
instance.listModified(makeList(args, 1));
} else if (command.equals("list-local-only")) {
instance.listLocalOnly(makeList(args, 1));
} else if (command.equals("list-from-site")) {
instance.listFromSite(makeList(args, 1));
} else if (command.equals("show")) {
instance.show(makeList(args, 1));
} else if (command.equals("update")) {
instance.update(makeList(args, 1));
} else if (command.equals("update-force")) {
instance.update(makeList(args, 1), true);
} else if (command.equals("update-force-pristine")) {
instance.update(makeList(args, 1), true, true);
} else if (command.equals("upload")) {
instance.upload(makeList(args, 1));
} else if (command.equals("upload-complete-site")) {
instance.uploadCompleteSite(makeList(args, 1));
} else if (command.equals("list-update-sites")) {
instance.listUpdateSites(makeList(args, 1));
} else if (command.equals("add-update-site")) {
instance.addOrEditUploadSite(makeList(args, 1), true);
} else if (command.equals("edit-update-site")) {
instance.addOrEditUploadSite(makeList(args, 1), false);
} else if (command.equals("remove-update-site")) {
instance.removeUploadSite(makeList(args, 1));
} else {
instance.usage();
}
}
protected static class ProxyAuthenticator extends Authenticator {
protected Console console = System.console();
@Override
protected PasswordAuthentication getPasswordAuthentication() {
if (console == null) {
throw new RuntimeException(
"Need a console for user interaction!");
}
final String user = console
.readLine(" \rProxy User: ");
final char[] password = console.readPassword("Proxy Password: ");
return new PasswordAuthentication(user, password);
}
}
protected static void setUserInterface() {
UpdaterUserInterface.set(new ConsoleUserInterface());
}
protected static class ConsoleUserInterface extends UpdaterUserInterface {
protected Console console = System.console();
protected int count;
@Override
public String getPassword(final String message) {
if (console == null) {
throw new RuntimeException(
"Password prompt requires interactive operation!");
}
System.out.print(message + ": ");
return new String(console.readPassword());
}
@Override
public boolean promptYesNo(final String title, final String message) {
if (console == null) {
throw new RuntimeException(
"Prompt requires interactive operation!");
}
System.err.print(title + ": " + message);
final String line = console.readLine();
return line.startsWith("y") || line.startsWith("Y");
}
public void showPrompt(String prompt) {
if (!prompt.endsWith(": ")) {
prompt += ": ";
}
System.err.print(prompt);
}
public String getUsername(final String prompt) {
if (console == null) {
throw new RuntimeException(
"Username prompt requires interactive operation!");
}
showPrompt(prompt);
return console.readLine();
}
public int askChoice(final String[] options) {
if (console == null) {
throw new RuntimeException(
"Prompt requires interactive operation!");
}
for (int i = 0; i < options.length; i++)
System.err.println("" + (i + 1) + ": " + options[i]);
for (;;) {
System.err.print("Choice? ");
final String answer = console.readLine();
if (answer.equals("")) {
return -1;
}
try {
return Integer.parseInt(answer) - 1;
} catch (final Exception e) { /* ignore */
}
}
}
@Override
public void error(final String message) {
log.error(message);
}
@Override
public void info(final String message, final String title) {
log.info(title + ": " + message);
}
@Override
public void log(final String message) {
log.info(message);
}
@Override
public void debug(final String message) {
log.debug(message);
}
@Override
public OutputStream getOutputStream() {
return System.out;
}
@Override
public void showStatus(final String message) {
log(message);
}
@Override
public void handleException(final Throwable exception) {
exception.printStackTrace();
}
@Override
public boolean isBatchMode() {
return false;
}
@Override
public int optionDialog(final String message, final String title,
final Object[] options, final int def) {
if (console == null) {
throw new RuntimeException(
"Prompt requires interactive operation!");
}
for (int i = 0; i < options.length; i++)
System.err.println("" + (i + 1) + ") " + options[i]);
for (;;) {
System.out.print("Your choice (default: " + def + ": "
+ options[def] + ")? ");
final String line = console.readLine();
if (line.equals("")) {
return def;
}
try {
final int option = Integer.parseInt(line);
if (option > 0 && option <= options.length) {
return option - 1;
}
} catch (final NumberFormatException e) {
// ignore
}
}
}
@Override
public String getPref(final String key) {
return null;
}
@Override
public void setPref(final String key, final String value) {
log("Ignoring setting '" + key + "'");
}
@Override
public void savePreferences() { /* do nothing */
}
@Override
public void openURL(final String url) throws IOException {
log("Please open " + url + " in your browser");
}
@Override
public String getString(final String title) {
if (console == null) {
throw new RuntimeException(
"Prompt requires interactive operation!");
}
System.out.print(title + ": ");
return console.readLine();
}
@Override
public void addWindow(final Frame window) { }
@Override
public void removeWindow(final Frame window) { }
}
}
|
package de.lessvoid.coregl;
import java.io.*;
import java.lang.reflect.*;
import java.nio.*;
import java.util.*;
import java.util.logging.*;
import de.lessvoid.coregl.spi.CoreGL;
/**
* Helper class that represents a shader (actually the combination of a vertex
* and a fragment shader - what GL actually calls a program).
* @author void
*/
public class CoreShader {
private static final Logger log = Logger.getLogger(CoreShader.class.getName());
private int program;
private Hashtable<String, Integer> parameter = new Hashtable<String, Integer>();
private FloatBuffer matBuffer;
private final String[] attributes;
private final CoreGL gl;
/**
* Create a new Shader.
* @return the new CoreShader instance
*/
public static CoreShader createShader(final CoreGL gl) {
return new CoreShader(gl);
}
/**
* Create a new Shader with the given vertex attributes automatically bind to the generic attribute indices in
* ascending order beginning with 0. This method can be used when you want to control the vertex attribute binding
* on your own.
*
* @param vertexAttributes the name of the vertex attribute. The first String gets generic attribute index 0. the
* second String gets generic attribute index 1 and so on.
* @return the CoreShader instance
*/
public static CoreShader createShaderWithVertexAttributes(final CoreGL gl, String ... vertexAttributes) {
return new CoreShader(gl, vertexAttributes);
}
CoreShader(final CoreGL gl, final String ... vertexAttributes) {
this.gl = gl;
this.attributes = vertexAttributes;
this.program = gl.glCreateProgram();
checkGLError("glCreateProgram");
}
public int vertexShader(final String filename) {
return vertexShader(filename, getStream(filename));
}
public int vertexShader(final File file) throws FileNotFoundException {
return vertexShader(file.getName(), getStream(file));
}
public int vertexShader(final String streamName, final InputStream ... sources) {
return vertexShaderFromStream(streamName, sources);
}
public void vertexShader(final int shaderId, final String filename) {
vertexShader(shaderId, filename, getStream(filename));
}
public void vertexShader(final int shaderId, final File file) throws FileNotFoundException {
vertexShader(shaderId, file.getName(), getStream(file));
}
public void vertexShader(final int shaderId, final String streamName, final InputStream source) {
prepareShader(shaderId, streamName, source);
}
public void geometryShader(final int shaderId, final String filename) {
geometryShader(shaderId, filename, getStream(filename));
}
public int geometryShader(final String filename) {
return geometryShaderFromStream(filename, getStream(filename));
}
public int geometryShader(final File file) throws FileNotFoundException {
return geometryShader(file.getName(), getStream(file));
}
public int geometryShader(final File file, final InputStream ... inputStreams) throws FileNotFoundException {
InputStream[] sources = new InputStream[inputStreams.length + 1];
System.arraycopy(inputStreams, 0, sources, 0, inputStreams.length);
sources[sources.length - 1] = getStream(file);
return geometryShader(file.getName(), sources);
}
public int geometryShader(final String streamName, final InputStream ... inputStreams) throws FileNotFoundException {
return geometryShaderFromStream(streamName, inputStreams);
}
public void geometryShader(final int shaderId, final String streamName, InputStream source) {
prepareShader(shaderId, streamName, source);
}
public void geometryShader(final int shaderId, final File file) throws FileNotFoundException {
geometryShader(shaderId, file.getName(), getStream(file));
}
public int fragmentShader(final String filename) {
return fragmentShader(filename, getStream(filename));
}
public int fragmentShader(final File file) throws FileNotFoundException {
return fragmentShaderFromStream(file.getName(), getStream(file));
}
public int fragmentShader(final String streamName, final InputStream ... inputStreams) {
return fragmentShaderFromStream(streamName, inputStreams);
}
public void fragmentShader(final int shaderId, final String filename) {
fragmentShader(shaderId, filename, getStream(filename));
}
public void fragmentShader(final int shaderId, final File file) throws FileNotFoundException {
fragmentShader(shaderId, file.getName(), getStream(file));
}
public void fragmentShader(final int shaderId, final String streamName, final InputStream source) {
prepareShader(shaderId, streamName, source);
}
private int vertexShaderFromStream(final String streamName, final InputStream ... sources) {
int shaderId = gl.glCreateShader(gl.GL_VERTEX_SHADER());
checkGLError("glCreateShader(GL_VERTEX_SHADER)");
prepareShader(shaderId, streamName, sources);
gl.glAttachShader(program, shaderId);
checkGLError("glAttachShader");
return shaderId;
}
private int geometryShaderFromStream(final String streamName, final InputStream ... sources) {
int shaderId = gl.glCreateShader(gl.GL_GEOMETRY_SHADER());
checkGLError("glCreateShader(GL_GEOMETRY_SHADER)");
prepareShader(shaderId, streamName, sources);
gl.glAttachShader(program, shaderId);
checkGLError("glAttachShader");
return shaderId;
}
private int fragmentShaderFromStream(final String streamName, final InputStream ... sources) {
int shaderId = gl.glCreateShader(gl.GL_FRAGMENT_SHADER());
checkGLError("glCreateShader(GL_FRAGMENT_SHADER)");
prepareShader(shaderId, streamName, sources);
gl.glAttachShader(program, shaderId);
checkGLError("glAttachShader");
return shaderId;
}
public void link() {
for (int i=0; i<attributes.length; i++) {
gl.glBindAttribLocation(program, i, attributes[i]);
checkGLError("glBindAttribLocation (" + attributes[i] + ")");
}
gl.glLinkProgram(program);
checkGLError("glLinkProgram");
IntBuffer params = gl.getUtil().createIntBuffer(1);
gl.glGetProgramiv(program, gl.GL_LINK_STATUS(), params);
if (params.get(0) != gl.GL_TRUE()) {
log.warning("link error: " + gl.glGetProgramInfoLog(program));
checkGLError("glGetProgramInfoLog");
}
checkGLError("glGetProgram");
}
public void setUniformi(final String name, final int...values) {
setUniform(name, UniformType.INT, toObjectArray(values));
}
public void setUniformf(final String name, final float...values) {
setUniform(name, UniformType.FLOAT, toObjectArray(values));
}
public void setUniformd(final String name, final double...values) {
setUniform(name, UniformType.DOUBLE, toObjectArray(values));
}
public void setUniformiv(final String name, final int componentNum, final int... values) {
IntBuffer buff = gl.getUtil().createIntBuffer(values.length);
buff.put(values);
buff.flip();
setUniformv(name, componentNum, UniformType.INT, buff);
}
public void setUniformiv(final String name, final int componentNum, final IntBuffer values) {
setUniformv(name, componentNum, UniformType.INT, values);
}
public void setUniformfv(final String name, final int componentNum, final float... values) {
FloatBuffer buff = gl.getUtil().createFloatBuffer(values.length);
buff.put(values);
buff.flip();
setUniformv(name, componentNum, UniformType.FLOAT, buff);
}
public void setUniformfv(final String name, final int componentNum, final FloatBuffer values) {
setUniformv(name, componentNum, UniformType.FLOAT, values);
}
public void setUniformdv(final String name, final int componentNum, final double... values) {
DoubleBuffer buff = gl.getUtil().createDoubleBuffer(values.length);
buff.put(values);
buff.flip();
setUniformv(name, componentNum, UniformType.DOUBLE, buff);
}
public void setUniformdv(final String name, final int componentNum, final DoubleBuffer values) {
setUniformv(name, componentNum, UniformType.DOUBLE, values);
}
public void setUniformMatrix(final String name, final int componentNum, final float... values) {
if(matBuffer == null)
gl.getUtil().createFloatBuffer(16);
matBuffer.clear();
matBuffer.put(values);
matBuffer.flip();
setUniformMatrix(name, componentNum, UniformType.FLOAT, matBuffer);
}
public void setUniformMatrix(final String name, final int componentNum,
FloatBuffer values) {
setUniformMatrix(name, componentNum, UniformType.FLOAT, values);
}
private void setUniform(final String name, final UniformType type, final Object...values) {
int loc = getLocation(name);
String method = "glUniform"+values.length+type.suffix;
try {
switch(values.length) {
case 1:
Method m = CoreGL.class.getMethod(method, int.class, type.value);
m.setAccessible(true);
m.invoke(gl, loc, values[0]);
break;
case 2:
m = CoreGL.class.getMethod(method, int.class, type.value, type.value);
m.setAccessible(true);
m.invoke(gl, loc, values[0], values[1]);
break;
case 3:
m = CoreGL.class.getMethod(method, int.class, type.value, type.value, type.value);
m.setAccessible(true);
m.invoke(gl, loc, values[0], values[1], values[2]);
break;
case 4:
m = CoreGL.class.getMethod(method, int.class, type.value, type.value, type.value, type.value);
m.setAccessible(true);
m.invoke(gl, loc, values[0], values[1], values[2], values[3]);
break;
default:
throw(new IllegalArgumentException("illegal number of values supplied to "
+ "setUniform"+type.suffix));
}
} catch (NoSuchMethodException e) {
throw(new CoreGLException("failed to locate set uniform method: " + method));
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
checkGLError(method);
}
private void setUniformv(final String name, final int componentNum,
final UniformType type, final Buffer data) {
int loc = getLocation(name);
if(componentNum < 1 || componentNum > 4)
throw(new IllegalArgumentException("illegal number of compoments for setUniform"+type.suffix+"v"));
String method = "glUniform"+componentNum+type.suffix+"v";
try {
Method m = CoreGL.class.getMethod(method, int.class, type.buffer);
m.setAccessible(true);
m.invoke(gl, loc, data);
} catch (NoSuchMethodException e) {
throw(new CoreGLException("failed to locate set uniform method: " + method));
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
checkGLError(method);
}
private void setUniformMatrix(final String name, final int componentNum,
final UniformType type, final Buffer data) {
int loc = getLocation(name);
if(componentNum < 2 || componentNum > 4)
throw(new IllegalArgumentException("illegal number of compoments for setUniformMatrix"));
String method = "glUniformMatrix"+componentNum;
try {
Method m = CoreGL.class.getMethod(method, int.class, boolean.class, type.buffer);
m.setAccessible(true);
m.invoke(gl, loc, false, data);
} catch (NoSuchMethodException e) {
throw(new CoreGLException("failed to locate set uniform method: " + method));
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
checkGLError(method);
}
public int getAttribLocation(final String name) {
int result = gl.glGetAttribLocation(program, name);
checkGLError("glGetAttribLocation");
return result;
}
public void bindAttribLocation(final String name, final int index) {
gl.glBindAttribLocation(program, index, name);
checkGLError("glBindAttribLocation");
}
public Map<String, UniformBlockInfo> getUniformIndices(final String ... uniformNames) {
Map<String, UniformBlockInfo> result = new Hashtable<String, UniformBlockInfo>();
IntBuffer intBuffer = gl.getUtil().createIntBuffer(uniformNames.length);
gl.glGetUniformIndices(program, uniformNames, intBuffer);
IntBuffer uniformOffsets = gl.getUtil().createIntBuffer(uniformNames.length);
gl.glGetActiveUniforms(program, uniformNames.length, intBuffer, gl.GL_UNIFORM_OFFSET(), uniformOffsets);
IntBuffer arrayStrides = gl.getUtil().createIntBuffer(uniformNames.length);
gl.glGetActiveUniforms(program, uniformNames.length, intBuffer, gl.GL_UNIFORM_ARRAY_STRIDE(), arrayStrides);
IntBuffer matrixStrides = gl.getUtil().createIntBuffer(uniformNames.length);
gl.glGetActiveUniforms(program, uniformNames.length, intBuffer, gl.GL_UNIFORM_MATRIX_STRIDE(), matrixStrides);
checkGLError("getUniformIndices");
for (int i=0; i<uniformNames.length; i++) {
UniformBlockInfo blockInfo = new UniformBlockInfo();
blockInfo.name = uniformNames[i];
blockInfo.offset = uniformOffsets.get(i);
blockInfo.arrayStride = arrayStrides.get(i);
blockInfo.matrixStride = matrixStrides.get(i);
result.put(blockInfo.name, blockInfo);
}
return result;
}
public void uniformBlockBinding(final String name, final int uniformBlockBinding) {
int uniformBlockIndex = gl.glGetUniformBlockIndex(program, name);
checkGLError("glGetUniformBlockIndex");
gl.glUniformBlockBinding(program, uniformBlockIndex, uniformBlockBinding);
checkGLError("glUniformBlockBinding");
}
public void activate() {
gl.glUseProgram(program);
checkGLError("glUseProgram");
}
private int registerParameter(final String name) {
int location = getUniform(name);
parameter.put(name, location);
return location;
}
private int getLocation(final String name) {
Integer value = parameter.get(name);
if (value == null) {
return registerParameter(name);
}
return value;
}
private int getUniform(final String uniformName) {
int result = gl.glGetUniformLocation(program, uniformName);
checkGLError("glGetUniformLocation for [" + uniformName + "] failed");
log.fine(getLoggingPrefix() + "glUniformLocation for [" + uniformName + "] = [" + result + "]");
return result;
}
private void prepareShader(final int shaderId, final String name, final InputStream ... sources) {
try {
gl.glShaderSource(shaderId, loadShader(sources));
checkGLError("glShaderSource");
} catch (IOException e) {
throw new CoreGLException(e);
}
gl.glCompileShader(shaderId);
checkGLError("glCompileShader");
IntBuffer ret = gl.getUtil().createIntBuffer(1);
gl.glGetShaderiv(shaderId, gl.GL_COMPILE_STATUS(), ret);
if (ret.get(0) == gl.GL_FALSE()) {
log.warning("'" + name + "' compile error: " + gl.glGetShaderInfoLog(shaderId));
}
printLogInfo(shaderId);
checkGLError(String.valueOf(shaderId));
}
private String loadShader(final InputStream ... sources) throws IOException {
StringBuilder srcbuff = new StringBuilder();
for (InputStream source : sources) {
InputStreamReader streamReader = new InputStreamReader(source);
BufferedReader buffReader = new BufferedReader(streamReader);
String nextLine = null;
while((nextLine = buffReader.readLine()) != null) {
srcbuff.append(nextLine + "\n");
}
buffReader.close();
}
return srcbuff.toString();
}
private void printLogInfo(final int obj) {
String logInfoMsg = gl.glGetShaderInfoLog(obj);
checkGLError("glGetShaderInfoLog");
if (!logInfoMsg.isEmpty()) {
log.info(getLoggingPrefix() + "Info log:\n" + logInfoMsg);
}
checkGLError("printLogInfo");
}
private void checkGLError(final String message) {
gl.checkGLError(getLoggingPrefix() + message);
}
private String getLoggingPrefix() {
return "[" + program + "] ";
}
private InputStream getStream(final File file) throws FileNotFoundException {
log.fine("loading shader file [" + file + "]");
return new FileInputStream(file);
}
private InputStream getStream(final String filename) {
return Thread.currentThread().getContextClassLoader().getResourceAsStream(filename);
}
private Object[] toObjectArray(int[] ints) {
Object[] intObjs = new Integer[ints.length];
for(int i=0; i < intObjs.length; i++)
intObjs[i] = ints[i];
return intObjs;
}
private Object[] toObjectArray(float[] floats) {
Object[] intObjs = new Float[floats.length];
for(int i=0; i < intObjs.length; i++)
intObjs[i] = floats[i];
return intObjs;
}
private Object[] toObjectArray(double[] doubles) {
Object[] intObjs = new Double[doubles.length];
for(int i=0; i < intObjs.length; i++)
intObjs[i] = doubles[i];
return intObjs;
}
enum UniformType {
INT("i", int.class, IntBuffer.class),
FLOAT("f", float.class, FloatBuffer.class),
DOUBLE("d", double.class, DoubleBuffer.class);
String suffix;
Class<?> value, buffer;
UniformType(String suffix, Class<?> value, Class<?> buffer) {
this.suffix = suffix;
this.buffer = buffer;
this.value = value;
}
}
}
|
package edu.cmu.sv.kelinci;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Arrays;
import java.util.Queue;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* TODO add "local" mode that prevents sending input files
* TODO Option to replace System.exit() with RuntimeException?
* TODO put in the cloud
*
* @author rodykers
*
*/
class Kelinci {
private static final int maxQueue = 10;
private static Queue<FuzzRequest> requestQueue = new ConcurrentLinkedQueue<>();
public static final byte STATUS_SUCCESS = 0;
public static final byte STATUS_TIMEOUT = 1;
public static final byte STATUS_CRASH = 2;
public static final byte STATUS_QUEUE_FULL = 3;
public static final byte STATUS_COMM_ERROR = 4;
public static final byte STATUS_DONE = 5;
public static final int DEFAULT_TIMEOUT = 300000; // in milliseconds
private static int timeout;
public static final int DEFAULT_VERBOSITY = 2;
private static int verbosity;
public static final int DEFAULT_PORT = 7007;
private static int port;
private static Method targetMain;
private static String targetArgs[];
private static File tmpfile;
private static class FuzzRequest {
Socket clientSocket;
FuzzRequest(Socket clientSocket) {
this.clientSocket = clientSocket;
}
}
/**
* Method to run in a thread to accept requests coming
* in over TCP and put them in a queue.
*/
private static void runServer() {
try (ServerSocket ss = new ServerSocket(port)) {
if (verbosity > 1)
System.out.println("Server listening on port " + port);
while (true) {
Socket s = ss.accept();
if (verbosity > 1)
System.out.println("Connection established.");
boolean status = false;
if (requestQueue.size() < maxQueue) {
status = requestQueue.offer(new FuzzRequest(s));
if (verbosity > 1)
System.out.println("Request added to queue: " + status);
}
if (!status) {
if (verbosity > 1)
System.out.println("Queue full.");
OutputStream os = s.getOutputStream();
os.write(STATUS_QUEUE_FULL);
os.flush();
s.shutdownOutput();
s.shutdownInput();
s.close();
if (verbosity > 1)
System.out.println("Connection closed.");
}
}
} catch (BindException be) {
System.err.println("Unable to bind to port " + port);
System.exit(1);
} catch (Exception e) {
System.err.println("Exception in request server");
e.printStackTrace();
System.exit(1);
}
}
/**
* Writes the provided input to a file, then calls main()
* Replaces @@ by the tmp file name.
*
* @param input
*/
private static long runApplication(byte input[]) {
Mem.clear();
long runtime = -1L;
try (FileOutputStream stream = new FileOutputStream(tmpfile)) {
stream.write(input);
stream.close();
String[] args = Arrays.copyOf(targetArgs, targetArgs.length);
for (int i = 0; i < args.length; i++) {
if (args[i].equals("@@")) {
args[i] = tmpfile.getAbsolutePath();
}
}
long pre = System.nanoTime();
targetMain.invoke(null, (Object) args);
runtime = System.nanoTime() - pre;
} catch (IOException ioe) {
throw new RuntimeException("Error writing to tmp file");
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
e.printStackTrace();
throw new RuntimeException("Error invoking target main method");
}
return runtime;
}
/**
* Runner thread for the target application.
*
*/
private static class ApplicationCall implements Callable<Long> {
byte input[];
ApplicationCall(byte input[]) {
this.input = input;
}
@Override
public Long call() throws Exception {
return runApplication(input);
}
}
/**
* Method to run in a thread handling one request from the queue at a time.
*/
private static void doFuzzerRuns() {
if (verbosity > 1)
System.out.println("Fuzzer runs handler thread started.");
while (true) {
try {
FuzzRequest request = requestQueue.poll();
if (request != null) {
if (verbosity > 1)
System.out.println("Handling request 1 of " + (requestQueue.size()+1));
InputStream is = request.clientSocket.getInputStream();
OutputStream os = request.clientSocket.getOutputStream();
byte result = STATUS_CRASH;
// read the size of the input file (integer)
int filesize = is.read() | is.read() << 8 | is.read() << 16 | is.read() << 24;
if (verbosity > 2)
System.out.println("File size = " + filesize);
if (filesize < 0) {
if (verbosity > 1)
System.err.println("Failed to read file size");
result = STATUS_COMM_ERROR;
} else {
// read the input file
byte input[] = new byte[filesize];
int read = 0;
while (read < filesize) {
if (is.available() > 0) {
input[read++] = (byte) is.read();
} else {
if (verbosity > 1) {
System.err.println("No input available from stream, strangely");
System.err.println("Appending a 0");
}
input[read++] = 0;
}
}
// run app with input
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Long> future = executor.submit(new ApplicationCall(input));
try {
if (verbosity > 1)
System.out.println("Started...");
future.get(timeout, TimeUnit.MILLISECONDS);
result = STATUS_SUCCESS;
if (verbosity > 1)
System.out.println("Finished!");
} catch (TimeoutException te) {
future.cancel(true);
if (verbosity > 1)
System.out.println("Time-out!");
result = STATUS_TIMEOUT;
} catch (Throwable e) {
future.cancel(true);
if (e.getCause() instanceof RuntimeException) {
if (verbosity > 1)
System.out.println("RuntimeException thrown!");
} else if (e.getCause() instanceof Error) {
if (verbosity > 1)
System.out.println("Error thrown!");
} else {
if (verbosity > 1)
System.out.println("Uncaught throwable!");
}
e.printStackTrace();
}
executor.shutdownNow();
}
if (verbosity > 1)
System.out.println("Result: " + result);
if (verbosity > 2)
Mem.print();
// send back status
os.write(result);
// send back "shared memory" over TCP
os.write(Mem.mem, 0, Mem.mem.length);
// close connection
os.flush();
request.clientSocket.shutdownOutput();
request.clientSocket.shutdownInput();
request.clientSocket.setSoLinger(true, 100000);
request.clientSocket.close();
if (verbosity > 1)
System.out.println("Connection closed.");
} else {
// if no request, close your eyes for a bit
Thread.sleep(100);
}
} catch (SocketException se) {
// Connection was reset, most probably means AFL process was killed.
if (verbosity > 1)
System.out.println("Connection reset.");
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Exception running fuzzed input");
}
}
}
public static void main(String args[]) {
/**
* Parse command line parameters: load the main class,
* grab -port option and store command-line parameters for fuzzing runs.
*/
if (args.length < 1) {
System.err.println("Usage: java edu.cmu.sv.kelinci.Kelinci [-v N] [-p N] [-t N] package.ExampleMain <args>");
return;
}
port = DEFAULT_PORT;
timeout = DEFAULT_TIMEOUT;
verbosity = DEFAULT_VERBOSITY;
int curArg = 0;
while (args.length > curArg) {
if (args[curArg].equals("-p") || args[curArg].equals("-port")) {
port = Integer.parseInt(args[curArg+1]);
curArg += 2;
} else if (args[curArg].equals("-v") || args[curArg].equals("-verbosity")) {
verbosity = Integer.parseInt(args[curArg+1]);
curArg += 2;
} else if (args[curArg].equals("-t") || args[curArg].equals("-timeout")) {
timeout = Integer.parseInt(args[curArg+1]);
curArg += 2;
} else {
break;
}
}
String mainClass = args[curArg];
targetArgs = Arrays.copyOfRange(args, curArg+1, args.length);
/**
* Check if at least one of the target parameters is @@
*/
boolean present = false;
for (int i = 0; i < targetArgs.length; i++) {
if (targetArgs[i].equals("@@")) {
present = true;
break;
}
}
if (!present) {
System.err.println("Error: none of the target application parameters is @@");
System.exit(1);
}
/**
* Redirect target program output to /dev/null if requested.
*/
if (verbosity <= 0) {
PrintStream nullStream = new PrintStream(new NullOutputStream());
System.setOut(nullStream);
System.setErr(nullStream);
}
ClassLoader classloader = Thread.currentThread().getContextClassLoader();
try {
Class<?> target = classloader.loadClass(mainClass);
targetMain = target.getMethod("main", String[].class);
} catch (ClassNotFoundException e) {
System.err.println("Main class not found: " + mainClass);
return;
} catch (NoSuchMethodException e) {
System.err.println("No main method found in class: " + mainClass);
return;
} catch (SecurityException e) {
System.err.println("Main method in class not accessible: " + mainClass);
return;
}
/**
* Create the tmp file to serve as input file to the program.
*/
try {
tmpfile = File.createTempFile("kelinci-input", "");
tmpfile.deleteOnExit();
} catch (IOException ioe) {
throw new RuntimeException("Error creating tmp file");
}
/**
* Start the server thread
*/
Thread server = new Thread(new Runnable() {
@Override
public void run() {
runServer();
}
});
server.start();
/**
* Handle requests for fuzzer runs in multiple threads.
* The number of threads can be specified by the user with the -threads option.
* By default, the number of threads is equal to the number of available processors - 1.
*/
Thread fuzzerRuns = new Thread(new Runnable() {
@Override
public void run() {
doFuzzerRuns();
}
});
fuzzerRuns.start();
}
/**
* Stream to /dev/null. Used to redirect output of target program.
*
* I know something like this is also in Apache Commons IO, but if I include it here,
* we don't need any libs on the classpath when running the Kelinci server.
*
* @author rodykers
*
*/
private static class NullOutputStream extends ByteArrayOutputStream {
@Override
public void write(int b) {}
@Override
public void write(byte[] b, int off, int len) {}
@Override
public void writeTo(OutputStream out) throws IOException {}
}
}
|
package io.sidecar.client;
import static com.google.common.base.Throwables.propagate;
import static io.sidecar.security.signature.SignatureVersion.Version.ONE;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import com.fasterxml.jackson.databind.JsonNode;
import io.sidecar.access.AccessKey;
import io.sidecar.credential.Credential;
import io.sidecar.event.Event;
import io.sidecar.jackson.ModelMapper;
import io.sidecar.notification.NotificationRule;
import io.sidecar.org.PlatformDeviceToken;
import io.sidecar.org.UserGroup;
import io.sidecar.org.UserGroupMember;
import io.sidecar.query.Query;
import io.sidecar.query.UserAnswerBucket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SuppressWarnings("unused")
public class SidecarClient {
private static final Logger LOGGER = LoggerFactory.getLogger(SidecarClient.class);
private final ClientConfig clientConfig;
private final AccessKey accessKey;
private final ModelMapper mapper = new ModelMapper();
@SuppressWarnings("unused")
public SidecarClient(AccessKey accessKey) {
this(accessKey, new ClientConfig());
}
public SidecarClient(AccessKey accessKey, ClientConfig clientConfig) {
this.accessKey = accessKey;
this.clientConfig = clientConfig;
}
/**
* Given a username and password, obtain that user's AccessKey's for this application if that user exists.
*
* @param credential The user's credentials.
* @return AccessKeys for the user identified by the provided Credentials
*/
@SuppressWarnings("unused")
public AccessKey authenticateUser(Credential credential) {
try {
URL endpoint = fullUrlForPath("/rest/v1/provision/application/auth");
SidecarPostRequest sidecarPostRequest = new SidecarPostRequest.Builder(
accessKey.getKeyId(), "", accessKey.getSecret())
.withSignatureVersion(ONE)
.withUrl(endpoint)
.withPayload(credential)
.build();
SidecarResponse response = sidecarPostRequest.send();
if (response.getStatusCode() == 200) {
LOGGER.debug(response.getBody());
return mapper.readValue(response.getBody(), AccessKey.class);
} else {
throw new SidecarClientException(response.getStatusCode(), response.getBody());
}
} catch (Exception e) {
throw propagate(e);
}
}
public boolean checkApplicationKeyset() {
try {
URL endpoint = fullUrlForPath("/rest/v1/provision/application/status");
SidecarGetRequest sidecarGetRequest =
new SidecarGetRequest.Builder(accessKey.getKeyId(), "", accessKey.getSecret())
.withSignatureVersion(ONE)
.withUrl(endpoint)
.build();
SidecarResponse response = sidecarGetRequest.send();
if (response.getStatusCode() == 200) {
return true;
} else {
throw new SidecarClientException(response.getStatusCode(), response.getBody());
}
} catch (Exception e) {
throw propagate(e);
}
}
public boolean checkUserKeyset() {
try {
URL endpoint = fullUrlForPath("/rest/v1/provision/user/status");
SidecarGetRequest sidecarGetRequest =
new SidecarGetRequest.Builder(accessKey.getKeyId(), "", accessKey.getSecret())
.withSignatureVersion(ONE)
.withUrl(endpoint)
.build();
SidecarResponse response = sidecarGetRequest.send();
if (response.getStatusCode() == 200) {
return true;
} else {
throw new SidecarClientException(response.getStatusCode(), response.getBody());
}
} catch (Exception e) {
throw propagate(e);
}
}
public UUID postEvent(Event event) {
try {
URL endpoint = fullUrlForPath("/rest/v1/event");
SidecarPostRequest sidecarPostRequest = new SidecarPostRequest.Builder(
accessKey.getKeyId(), "", accessKey.getSecret())
.withSignatureVersion(ONE)
.withUrl(endpoint)
.withPayload(event)
.build();
SidecarResponse response = sidecarPostRequest.send();
if (response.getStatusCode() == 202) {
String s = response.getBody();
JsonNode json = mapper.readTree(s);
System.out.println(json);
return UUID.fromString(json.path("id").asText());
} else {
throw new SidecarClientException(response.getStatusCode(), response.getBody());
}
} catch (Exception e) {
throw propagate(e);
}
}
@SuppressWarnings("unused")
public AccessKey createNewUser(String emailAddress, String password) {
try {
Credential credential = new Credential(emailAddress, password);
URL endpoint = fullUrlForPath("/rest/v1/provision/application/user");
SidecarPostRequest sidecarRequest =
new SidecarPostRequest.Builder(accessKey.getKeyId(), "", accessKey.getSecret())
.withUrl(endpoint)
.withSignatureVersion(ONE)
.withPayload(credential)
.build();
SidecarResponse response = sidecarRequest.send();
if (response.getStatusCode() == 200) {
return mapper.readValue(response.getBody(), AccessKey.class);
} else {
throw new SidecarClientException(response.getStatusCode(), response.getBody());
}
} catch (Exception e) {
throw propagate(e);
}
}
@SuppressWarnings("unused")
public void deleteUser(String emailAddress, String password) {
try {
Credential credential = new Credential(emailAddress, password);
URL endpoint = fullUrlForPath("/rest/v1/provision/application/user");
SidecarDeleteRequest sidecarRequest =
new SidecarDeleteRequest.Builder(accessKey.getKeyId(), "", accessKey.getSecret())
.withUrl(endpoint)
.withSignatureVersion(ONE)
.withPayload(credential)
.build();
SidecarResponse response = sidecarRequest.send();
// check for an no content response code
if (response.getStatusCode() != 204) {
throw new SidecarClientException(response.getStatusCode(), response.getBody());
}
} catch (Exception e) {
throw propagate(e);
}
}
@SuppressWarnings("unused")
public void updateUserMetadata(Map<String, String> metaData) {
try {
URL endpoint = fullUrlForPath("/rest/v1/provision/user");
SidecarPutRequest sidecarPutRequest =
new SidecarPutRequest.Builder(accessKey.getKeyId(), "", accessKey.getSecret())
.withSignatureVersion(ONE)
.withUrl(endpoint)
.withPayload(metaData)
.build();
SidecarResponse response = sidecarPutRequest.send();
if (response.getStatusCode() != 204) {
throw new SidecarClientException(response.getStatusCode(), response.getBody());
}
} catch (Exception e) {
throw propagate(e);
}
}
@SuppressWarnings("unused")
public Map<String, String> getUserMetadata() {
try {
URL endpoint = fullUrlForPath("/rest/v1/provision/user");
SidecarGetRequest sidecarGetRequest =
new SidecarGetRequest.Builder(accessKey.getKeyId(), "", accessKey.getSecret())
.withSignatureVersion(ONE)
.withUrl(endpoint)
.build();
SidecarResponse response = sidecarGetRequest.send();
if (response.getStatusCode() == 200) {
return mapper.readValue(response.getBody(), Map.class);
} else {
throw new SidecarClientException(response.getStatusCode(), response.getBody());
}
} catch (Exception e) {
throw propagate(e);
}
}
@SuppressWarnings("unused")
public UUID userIdForUserAddress(String emailAddress) {
try {
URL endpoint = fullUrlForPath("/rest/v1/provision/user/" + emailAddress);
SidecarGetRequest sidecarGetRequest =
new SidecarGetRequest.Builder(accessKey.getKeyId(), "", accessKey.getSecret())
.withSignatureVersion(ONE)
.withUrl(endpoint)
.build();
SidecarResponse response = sidecarGetRequest.send();
if (response.getStatusCode() == 200) {
return UUID
.fromString(mapper.readTree(response.getBody()).get("userId").textValue());
} else {
throw new SidecarClientException(response.getStatusCode(), response.getBody());
}
} catch (Exception e) {
throw propagate(e);
}
}
@SuppressWarnings("unused")
public UserGroup createNewUserGroup(String newGroupName) {
try {
HashMap<String, String> payload = new HashMap<>();
payload.put("name", newGroupName);
URL endpoint = fullUrlForPath("/rest/v1/provision/group");
SidecarPostRequest
sidecarPostRequest =
new SidecarPostRequest.Builder(accessKey.getKeyId(), "", accessKey.getSecret())
.withSignatureVersion(ONE)
.withUrl(endpoint)
.withPayload(payload)
.build();
SidecarResponse response = sidecarPostRequest.send();
if (response.getStatusCode() == 200) {
return mapper.readValue(response.getBody(), UserGroup.class);
} else {
throw new SidecarClientException(response.getStatusCode(), response.getBody());
}
} catch (Exception e) {
throw propagate(e);
}
}
@SuppressWarnings("unused")
public UserGroup addUserToUserGroup(UserGroup userGroup, UserGroupMember member) {
try {
URL endpoint = fullUrlForPath("/rest/v1/provision/group/" + userGroup.getId() + "/members");
SidecarPostRequest sidecarPostRequest =
new SidecarPostRequest.Builder(accessKey.getKeyId(), "", accessKey.getSecret())
.withSignatureVersion(ONE)
.withUrl(endpoint)
.withPayload(member)
.build();
SidecarResponse response = sidecarPostRequest.send();
if (response.getStatusCode() == 200) {
return mapper.readValue(response.getBody(), UserGroup.class);
} else {
throw new SidecarClientException(response.getStatusCode(), response.getBody());
}
} catch (Exception e) {
throw propagate(e);
}
}
@SuppressWarnings({"unchecked", "unused"})
public List<UUID> getGroupsForUser(String emailAddress) {
try {
URL endpoint = fullUrlForPath("/rest/v1/provision/user/" + emailAddress + "/groups");
SidecarGetRequest sidecarGetRequest =
new SidecarGetRequest.Builder(accessKey.getKeyId(), "", accessKey.getSecret())
.withSignatureVersion(ONE)
.withUrl(endpoint)
.build();
SidecarResponse response = sidecarGetRequest.send();
if (response.getStatusCode() == 200) {
return Collections.checkedList(mapper.readValue(response.getBody(), List.class), UUID.class);
} else {
throw new SidecarClientException(response.getStatusCode(), response.getBody());
}
} catch (Exception e) {
throw propagate(e);
}
}
@SuppressWarnings("unused")
public void provisionDevice(UUID deviceId) {
Map<String, String> metaData = new HashMap<>();
metaData.put("deviceId", deviceId.toString());
try {
URL endpoint = fullUrlForPath("/rest/v1/provision/user/device");
SidecarPostRequest sidecarPostRequest =
new SidecarPostRequest.Builder(accessKey.getKeyId(), "", accessKey.getSecret())
.withSignatureVersion(ONE)
.withUrl(endpoint)
.withPayload(metaData)
.build();
SidecarResponse response = sidecarPostRequest.send();
//The response body is empty if 204, so only check if we do not have a 204 response
if (response.getStatusCode() != 204) {
throw new SidecarClientException(response.getStatusCode(), response.getBody());
}
} catch (Exception e) {
throw propagate(e);
}
}
@SuppressWarnings("unused")
public void deprovisionDevice(UUID deviceId) {
try {
URL endpoint = fullUrlForPath("/rest/v1/provision/user/device/" + deviceId);
SidecarDeleteRequest sidecarDeleteRequest =
new SidecarDeleteRequest.Builder(accessKey.getKeyId(), "", accessKey.getSecret())
.withSignatureVersion(ONE)
.withUrl(endpoint)
.build();
SidecarResponse response = sidecarDeleteRequest.send();
//The response body is empty if 204, so only check if we do not have a 204 response
if (response.getStatusCode() != 204) {
throw new SidecarClientException(response.getStatusCode(), response.getBody());
}
} catch (Exception e) {
throw propagate(e);
}
}
@SuppressWarnings("unused")
public Map<String, String> getUserDeviceMetadata(UUID deviceId) {
try {
URL endpoint = fullUrlForPath("/rest/v1/provision/user/device/" + deviceId);
SidecarGetRequest sidecarGetRequest =
new SidecarGetRequest.Builder(accessKey.getKeyId(), "", accessKey.getSecret())
.withSignatureVersion(ONE)
.withUrl(endpoint)
.build();
SidecarResponse response = sidecarGetRequest.send();
if (response.getStatusCode() == 200) {
return mapper.readValue(response.getBody(), Map.class);
} else {
throw new SidecarClientException(response.getStatusCode(), response.getBody());
}
} catch (Exception e) {
throw propagate(e);
}
}
@SuppressWarnings("unused")
public void updateUserDeviceMetadata(UUID deviceId, Map<String, String> metaData) {
try {
URL endpoint = fullUrlForPath("/rest/v1/provision/user/device/" + deviceId);
SidecarPutRequest sidecarPutRequest =
new SidecarPutRequest.Builder(accessKey.getKeyId(), "", accessKey.getSecret())
.withSignatureVersion(ONE)
.withUrl(endpoint)
.withPayload(metaData)
.build();
SidecarResponse response = sidecarPutRequest.send();
if (response.getStatusCode() != 204) {
throw new SidecarClientException(response.getStatusCode(), response.getBody());
}
} catch (Exception e) {
throw propagate(e);
}
}
@SuppressWarnings("unused")
public void addNotificationToken(PlatformDeviceToken token) {
try {
URL endpoint = fullUrlForPath("/rest/v1/provision/user/notifications/token");
SidecarPostRequest sidecarPostRequest =
new SidecarPostRequest.Builder(accessKey.getKeyId(), "", accessKey.getSecret())
.withSignatureVersion(ONE)
.withUrl(endpoint)
.withPayload(token)
.build();
SidecarResponse response = sidecarPostRequest.send();
// check for an no content response code
if (response.getStatusCode() != 204) {
throw new SidecarClientException(response.getStatusCode(), response.getBody());
}
} catch (Exception e) {
throw propagate(e);
}
}
@SuppressWarnings("unused")
public UUID addNotificationRule(String name, String description, String stream, String key, Double min, Double max) {
HashMap<String, Object> payload = new HashMap<>();
payload.put("name", name);
payload.put("description", description);
payload.put("stream", stream);
payload.put("key", key);
payload.put("min", min);
payload.put("max", max);
try {
URL endpoint = fullUrlForPath("/rest/v1/provision/user/notifications/rule");
SidecarPostRequest sidecarPostRequest =
new SidecarPostRequest.Builder(accessKey.getKeyId(), "", accessKey.getSecret())
.withSignatureVersion(ONE)
.withUrl(endpoint)
.withPayload(payload)
.build();
SidecarResponse response = sidecarPostRequest.send();
// check for an OK response code
if (response.getStatusCode() == 200) {
return UUID.fromString(mapper.readTree(response.getBody()).get("id").textValue());
} else {
throw new SidecarClientException(response.getStatusCode(), response.getBody());
}
} catch (Exception e) {
throw propagate(e);
}
}
@SuppressWarnings("unused")
public NotificationRule getNotificationRule(UUID ruleId) {
try {
URL endpoint = fullUrlForPath("/rest/v1/provision/user/notifications/rule/" + ruleId.toString());
SidecarGetRequest sidecarPostRequest =
new SidecarGetRequest.Builder(accessKey.getKeyId(), "", accessKey.getSecret())
.withSignatureVersion(ONE)
.withUrl(endpoint)
.build();
SidecarResponse response = sidecarPostRequest.send();
// check for an OK response code
if (response.getStatusCode() == 200) {
return mapper.readValue(response.getBody(), NotificationRule.class);
} else {
throw new SidecarClientException(response.getStatusCode(), response.getBody());
}
} catch (Exception e) {
throw propagate(e);
}
}
@SuppressWarnings({"unused", "unchecked"})
public List<NotificationRule> getNotificationRules(UUID appId, UUID userId) {
try {
URL endpoint = fullUrlForPath("/rest/v1/provision/user/notifications/rules");
SidecarGetRequest sidecarPostRequest =
new SidecarGetRequest.Builder(accessKey.getKeyId(), "", accessKey.getSecret())
.withSignatureVersion(ONE)
.withUrl(endpoint)
.build();
SidecarResponse response = sidecarPostRequest.send();
// check for an OK response code
if (response.getStatusCode() == 200) {
return Collections.checkedList(mapper.readValue(response.getBody(), java.util.List.class), NotificationRule.class);
} else {
throw new SidecarClientException(response.getStatusCode(), response.getBody());
}
} catch (Exception e) {
throw propagate(e);
}
}
@SuppressWarnings("unused")
public List<UserAnswerBucket> postUserQuery(String type, Query query) {
String path = "/rest/v1/query/user/devices/" + type;
return postUserBasedQuery(path, query);
}
public List<UserAnswerBucket> postUserDeviceQuery(String type, UUID deviceId, Query query) {
String path = "/rest/v1/query/user/device/" + deviceId.toString() + "/" + type;
return postUserBasedQuery(path, query);
}
@SuppressWarnings("unchecked")
private List<UserAnswerBucket> postUserBasedQuery(String path, Query query) {
try {
URL endpoint = fullUrlForPath(path);
SidecarPostRequest sidecarPostRequest = new SidecarPostRequest.Builder(
accessKey.getKeyId(), "", accessKey.getSecret())
.withSignatureVersion(ONE)
.withUrl(endpoint)
.withPayload(query)
.build();
SidecarResponse response = sidecarPostRequest.send();
if (response.getStatusCode() == 200) {
LOGGER.debug(response.getBody());
return Collections.checkedList(mapper.readValue(response.getBody(), List.class), UserAnswerBucket.class);
} else {
throw new SidecarClientException(response.getStatusCode(), response.getBody());
}
} catch (Exception e) {
throw propagate(e);
}
}
public ClientConfig getConfig() {
return clientConfig;
}
private URL fullUrlForPath(String path) {
try {
URL baseUrl = clientConfig.getRestApiBasePath();
return new URL(baseUrl.toString() + path);
} catch (MalformedURLException e) {
throw propagate(e);
}
}
}
|
package org.intermine.util;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import junit.framework.TestCase;
import org.intermine.metadata.Model;
import org.intermine.model.testmodel.*;
public class DynamicUtilTest extends TestCase
{
public DynamicUtilTest(String arg) {
super(arg);
}
public void setUp() throws Exception {
}
// NEED MORE TESTS FOR MULTIPLE INHERITED INTERFACES WHEN AVAILABLE
// eg. - B
// A - D
// - C - F
public void testCreateObjectOneInterface() throws Exception {
Object obj = DynamicUtil.createObject(Collections.singleton(Company.class));
assertTrue(obj instanceof Company);
Company c = (Company) obj;
c.setName("Flibble");
assertEquals("Flibble", c.getName());
}
public void testCreateObjectOneInterfaceWithParents() throws Exception {
Object obj = DynamicUtil.createObject(Collections.singleton(Employable.class));
assertTrue(obj instanceof Employable);
assertTrue(obj instanceof Thing);
}
public void testCreateObjectNoClassTwoInterfaces() throws Exception {
Set intSet = new HashSet();
intSet.add(Company.class);
intSet.add(Broke.class);
Object obj = DynamicUtil.createObject(intSet);
assertTrue(obj instanceof Company);
assertTrue(obj instanceof RandomInterface);
assertTrue(obj instanceof Broke);
assertTrue(obj instanceof HasSecretarys);
assertTrue(obj instanceof HasAddress);
((Company) obj).setName("Wotsit");
((Broke) obj).setDebt(40);
assertEquals("Wotsit", ((Company) obj).getName());
assertEquals(40, ((Broke) obj).getDebt());
}
public void testCreateObjectClassOnly() throws Exception {
Object obj = DynamicUtil.createObject(Collections.singleton(Employee.class));
assertEquals(Employee.class, obj.getClass());
}
public void testCreateObjectClassAndRedundantInterfaces() {
Set intSet = new HashSet();
intSet.add(Employee.class);
intSet.add(Employable.class);
Object obj = DynamicUtil.createObject(intSet);
assertEquals(Employee.class, obj.getClass());
assertTrue(obj instanceof Employee);
assertTrue(obj instanceof Employable);
}
public void testCreateObjectClassInterfaces() throws Exception {
Set intSet = new HashSet();
intSet.add(Manager.class);
intSet.add(Broke.class);
Object obj = DynamicUtil.createObject(intSet);
assertTrue(obj instanceof Manager);
assertTrue(obj instanceof Employee);
assertTrue(obj instanceof ImportantPerson);
assertTrue(obj instanceof Employable);
assertTrue(obj instanceof HasAddress);
assertTrue(obj instanceof Broke);
Manager m = (Manager) obj;
m.setName("Frank");
m.setTitle("Mr.");
((Broke) m).setDebt(30);
assertEquals("Frank", m.getName());
assertEquals("Mr.", m.getTitle());
assertEquals(30, ((Broke) m).getDebt());
}
public void testCreateObjectTwoClasses() throws Exception {
Set intSet = new HashSet();
intSet.add(Manager.class);
intSet.add(Department.class);
try {
Object obj = DynamicUtil.createObject(intSet);
fail("Expected: IllegalArgumentException");
} catch (IllegalArgumentException e) {
}
}
public void testCreateObjectNothing() throws Exception {
try {
Object obj = DynamicUtil.createObject(Collections.EMPTY_SET);
fail("Expected: IllegalArgumentException");
} catch (IllegalArgumentException e) {
}
}
public void testConstructors() throws Exception {
Class c = DynamicUtil.createObject(Collections.singleton(Company.class)).getClass();
Company obj = (Company) c.newInstance();
((net.sf.cglib.proxy.Factory) obj).setCallback(0, new DynamicBean());
obj.setName("Fred");
assertEquals("Fred", obj.getName());
}
public void testInstantiateObjectNullClassName() throws Exception {
Object obj = DynamicUtil.instantiateObject(null, "org.intermine.model.testmodel.Broke");
assertTrue(obj instanceof Broke);
}
public void testInstantiateObjectEmptyClassName() throws Exception {
Object obj = DynamicUtil.instantiateObject("", "org.intermine.model.testmodel.Broke");
assertTrue(obj instanceof Broke);
}
public void testInstantiateObjectNullImplementations() throws Exception {
Object obj = DynamicUtil.instantiateObject("org.intermine.model.testmodel.Manager", null);
assertTrue(obj instanceof Manager);
}
public void testInstantiateObjectEmptyImplementations() throws Exception {
Object obj = DynamicUtil.instantiateObject("org.intermine.model.testmodel.Manager", "");
assertTrue(obj instanceof Manager);
}
public void testInstantiateObject() throws Exception {
Object obj = DynamicUtil.instantiateObject("org.intermine.model.testmodel.Manager", "org.intermine.model.testmodel.Broke");
assertTrue(obj instanceof Manager);
assertTrue(obj instanceof Broke);
}
/* public void testComposedClass() throws Exception {
StringBuffer b = new StringBuffer();
Class c = DynamicUtil.composeClass(Collections.singleton(Company.class));
Set alreadySeen = new HashSet();
while (c != null) {
Method methods[] = c.getDeclaredMethods();
for (int i = 0; i < methods.length; i++) {
Method m = methods[i];
if (! Modifier.isPrivate(methods[i].getModifiers())) {
MethodDescriptor md = new MethodDescriptor(m.getName(), m.getParameterTypes());
if (! alreadySeen.contains(md)) {
b.append(m.toString()).append("\n");
alreadySeen.add(md);
}
}
}
c = c.getSuperclass();
}
throw new Exception(b.toString());
}
private static class MethodDescriptor
{
public String name;
public Class[] parameters;
public MethodDescriptor(String name, Class parameters[]) {
this.name = name;
this.parameters = parameters;
}
public boolean equals(Object o) {
if (o instanceof MethodDescriptor) {
if (name.equals(((MethodDescriptor) o).name)) {
Class oparameters[] = ((MethodDescriptor) o).parameters;
if (parameters.length == oparameters.length) {
for (int i = 0; i < parameters.length; i++) {
if (parameters[i] != oparameters[i]) {
return false;
}
}
return true;
}
}
}
return false;
}
public int hashCode() {
return name.hashCode();
}
}*/
}
|
package org.intermine.web;
import java.util.Iterator;
import junit.framework.TestCase;
import org.intermine.model.testmodel.Department;
import org.intermine.model.testmodel.Employee;
import org.intermine.objectstore.ObjectStore;
import org.intermine.objectstore.dummy.ObjectStoreDummyImpl;
/**
* Tests for InterMineBag.
*
* @author tom
*/
public class InterMineBagTest extends TestCase
{
ObjectStore os = new ObjectStoreDummyImpl();
Department d1 = new Department();
Employee e2 = new Employee();
protected void setUp() throws Exception {
super.setUp();
d1.setId(new Integer(1));
e2.setId(new Integer(2));
os.cacheObjectById(new Integer(1), d1);
os.cacheObjectById(new Integer(2), e2);
}
public void testGetSize() {
InterMineBag bag = new InterMineBag(os);
bag.add("Hello");
bag.addId(new Integer(1));
assertEquals(2, bag.getSize());
assertEquals(2, bag.size());
}
public void testAddId() {
InterMineBag bag = new InterMineBag(os);
bag.addId(new Integer(1));
assertEquals(1, bag.getSize());
assertEquals(d1, bag.get(0));
}
/*
* Class under test for boolean add(Object)
*/
public void testAddObject() {
InterMineBag bag = new InterMineBag(os);
bag.add(new Integer(1));
bag.add("asdf");
assertEquals(2, bag.getSize());
assertEquals(new Integer(1), bag.get(0));
assertEquals("asdf", bag.get(1));
}
/*
* Class under test for Iterator iterator()
*/
public void testIterator() {
InterMineBag bag = new InterMineBag(os);
bag.add(new Integer(1));
bag.add("hello");
Iterator iter = bag.iterator();
assertTrue(iter.hasNext());
Object o = iter.next();
assertEquals(new Integer(1), o);
assertTrue(iter.hasNext());
assertEquals("hello", iter.next());
assertFalse(iter.hasNext());
iter = bag.iterator();
iter.next();
iter.remove();
assertTrue(iter.hasNext());
assertEquals("hello", iter.next());
assertFalse(iter.hasNext());
assertEquals(1, bag.size());
}
public void testLazyIterator() {
InterMineBag bag = new InterMineBag(os);
bag.add(new Integer(1));
bag.addId(new Integer(1));
bag.add("hello");
Iterator iter = bag.lazyIterator();
assertTrue(iter.hasNext());
Object o = iter.next();
assertEquals(new Integer(1), o);
assertTrue(iter.hasNext());
o = iter.next();
assertTrue("object not instance of ID", o instanceof InterMineBag.ID);
assertEquals(1, ((InterMineBag.ID) o).getId());
iter.remove();
assertTrue(iter.hasNext());
assertEquals("hello", iter.next());
assertFalse(iter.hasNext());
}
/*
* Class under test for Object get(int)
*/
public void testGetint() {
InterMineBag bag = new InterMineBag(os);
bag.add(new Integer(1));
bag.addId(new Integer(1));
bag.add("hello");
assertEquals(new Integer(1), bag.get(0));
assertEquals(d1, bag.get(1));
assertEquals("hello", bag.get(2));
}
public void testClear() {
InterMineBag bag = new InterMineBag(os);
bag.add(new Integer(1));
bag.addId(new Integer(1));
bag.add("hello");
bag.clear();
assertEquals(0, bag.size());
Iterator iter = bag.iterator();
assertFalse(iter.hasNext());
}
public void testAddAllCollection() {
InterMineBag bag = new InterMineBag(os);
bag.add(new Integer(1));
bag.addId(new Integer(1));
bag.add("hello");
InterMineBag bag2 = new InterMineBag(os);
bag2.add("world");
bag2.addId(new Integer(2));
assertEquals(3, bag.size());
assertEquals(2, bag2.size());
bag.addAll(bag2);
assertEquals(5, bag.size());
assertEquals(e2, bag.get(4));
}
/*
* Class under test for boolean remove(java.lang.Object)
*/
public void testRemoveObject() {
InterMineBag bag = new InterMineBag(os);
bag.add(new Integer(1));
bag.addId(new Integer(1));
bag.add("hello");
assertEquals(3, bag.size());
bag.remove(1);
assertEquals(2, bag.size());
assertEquals(new Integer(1), bag.get(0));
assertEquals("hello", bag.get(1));
}
public void testRemoveAll() {
InterMineBag bag = new InterMineBag(os);
bag.add(new Integer(1));
bag.addId(new Integer(1));
bag.add("hello");
InterMineBag bag2 = new InterMineBag(os);
bag2.add("hello");
bag2.add(d1);
assertEquals(3, bag.size());
assertEquals(2, bag2.size());
bag.removeAll(bag2);
assertEquals(1, bag.size());
assertEquals(new Integer(1), bag.get(0));
}
}
|
package org.intermine.dwr;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.lucene.queryParser.ParseException;
import org.apache.struts.Globals;
import org.apache.struts.util.MessageResources;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;
import org.intermine.InterMineException;
import org.intermine.model.userprofile.Tag;
import org.intermine.objectstore.ObjectStore;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.objectstore.ObjectStoreWriter;
import org.intermine.objectstore.intermine.ObjectStoreInterMineImpl;
import org.intermine.objectstore.query.Query;
import org.intermine.objectstore.query.QueryNode;
import org.intermine.objectstore.query.Results;
import org.intermine.path.Path;
import org.intermine.web.logic.Constants;
import org.intermine.web.logic.WebUtil;
import org.intermine.web.logic.bag.InterMineBag;
import org.intermine.web.logic.profile.Profile;
import org.intermine.web.logic.profile.ProfileManager;
import org.intermine.web.logic.query.MainHelper;
import org.intermine.web.logic.query.PathQuery;
import org.intermine.web.logic.query.QueryMonitorTimeout;
import org.intermine.web.logic.query.SavedQuery;
import org.intermine.web.logic.results.PagedTable;
import org.intermine.web.logic.results.WebResultsSimple;
import org.intermine.web.logic.results.WebTable;
import org.intermine.web.logic.search.SearchRepository;
import org.intermine.web.logic.search.WebSearchable;
import org.intermine.web.logic.session.SessionMethods;
import org.intermine.web.logic.tagging.TagTypes;
import org.intermine.web.logic.template.TemplateHelper;
import org.intermine.web.logic.template.TemplateQuery;
/**
* This class contains the methods called through DWR Ajax
*
* @author Xavier Watkins
*
*/
public class AjaxServices
{
protected static final Logger LOG = Logger.getLogger(AjaxServices.class);
/**
* Creates a favourite Tag for the given templateName
*
* @param name the name of the template we want to set as a favourite
* @param type type of tag (bag or template)
* @param isFavourite whether or not this item is currently a favourite
*/
public void setFavourite(String name, String type, boolean isFavourite) {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
Profile profile = (Profile) session.getAttribute(Constants.PROFILE);
HttpServletRequest request = ctx.getHttpServletRequest();
String nameCopy = name.replaceAll("#039;", "'");
ProfileManager pm = (ProfileManager) request.getSession().getServletContext().getAttribute(
Constants.PROFILE_MANAGER);
// already a favourite. turning off.
if (isFavourite) {
List<Tag> tags;
Tag tag;
if (type.equals(TagTypes.TEMPLATE)) {
tags = pm.getTags("favourite", nameCopy, TagTypes.TEMPLATE, profile.getUsername());
} else if (type.equals(TagTypes.BAG)) {
tags = pm.getTags("favourite", nameCopy, TagTypes.BAG, profile.getUsername());
} else {
throw new RuntimeException("Unknown tag type.");
}
if (tags.isEmpty()) {
throw new RuntimeException("User tried to mark a non-existent template "
+ "as favourite");
}
tag = tags.get(0);
pm.deleteTag(tag);
// not a favourite. turning on.
} else {
if (type.equals(TagTypes.TEMPLATE)) {
pm.addTag("favourite", nameCopy, TagTypes.TEMPLATE, profile.getUsername());
} else if (type.equals(TagTypes.BAG)) {
pm.addTag("favourite", nameCopy, TagTypes.BAG, profile.getUsername());
} else {
throw new RuntimeException("Unknown tag type.");
}
}
}
/**
* Precomputes the given template query
* @param templateName the template query name
* @return a String to guarantee the service ran properly
*/
public String preCompute(String templateName) {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
ServletContext servletContext = ctx.getServletContext();
Profile profile = (Profile) session.getAttribute(Constants.PROFILE);
Map templates = profile.getSavedTemplates();
TemplateQuery template = (TemplateQuery) templates.get(templateName);
ObjectStoreInterMineImpl os = (ObjectStoreInterMineImpl) servletContext
.getAttribute(Constants.OBJECTSTORE);
List indexes = new ArrayList();
Query query = TemplateHelper.getPrecomputeQuery(template, indexes, null);
try {
if (!os.isPrecomputed(query, "template")) {
session.setAttribute("precomputing_" + templateName, "true");
os.precompute(query, indexes, "template");
}
} catch (ObjectStoreException e) {
LOG.error(e);
} finally {
session.removeAttribute("precomputing_" + templateName);
}
return "precomputed";
}
/**
* Summarises the given template query.
*
* @param templateName the template query name
* @return a String to guarantee the service ran properly
*/
public String summarise(String templateName) {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
ServletContext servletContext = ctx.getServletContext();
Profile profile = (Profile) session.getAttribute(Constants.PROFILE);
Map templates = profile.getSavedTemplates();
TemplateQuery template = (TemplateQuery) templates.get(templateName);
ObjectStoreInterMineImpl os = (ObjectStoreInterMineImpl) servletContext
.getAttribute(Constants.OBJECTSTORE);
ObjectStoreWriter osw = ((ProfileManager) servletContext.getAttribute(
Constants.PROFILE_MANAGER)).getUserProfileObjectStore();
try {
session.setAttribute("summarising_" + templateName, "true");
template.summarise(os, osw);
} catch (ObjectStoreException e) {
LOG.error("Failed to summarise " + templateName, e);
} catch (NullPointerException e) {
NullPointerException e2 = new NullPointerException("No such template " + templateName);
e2.initCause(e);
throw e2;
} finally {
session.removeAttribute("summarising_" + templateName);
}
return "summarised";
}
/**
* Rename a element such as history, name, bag
* @param name the name of the element
* @param type history, saved, bag
* @param reName the new name for the element
* @return the new name of the element as a String
* @exception Exception if the application business logic throws
* an exception
*/
public String rename(String name, String type, String reName)
throws Exception {
String newName = reName.trim();
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
Profile profile = (Profile) session.getAttribute(Constants.PROFILE);
ServletContext servletContext = ctx.getServletContext();
ObjectStoreWriter uosw = ((ProfileManager) servletContext.getAttribute(
Constants.PROFILE_MANAGER)).getUserProfileObjectStore();
SavedQuery sq;
if (name.equals(newName) || StringUtils.isEmpty(newName)) {
return name;
}
if (!WebUtil.isValidName(newName)) {
String errorMsg = "<i>Invalid name. Names may only contain letters, "
+ "numbers, spaces, and underscores.</i>";
return errorMsg;
}
if (type.equals("history")) {
if (profile.getHistory().get(name) == null) {
return "<i>" + name + " does not exist</i>";
}
if (profile.getHistory().get(newName) != null) {
return "<i>" + newName + " already exists</i>";
}
profile.renameHistory(name, newName);
} else if (type.equals("saved")) {
if (profile.getSavedQueries().get(name) == null) {
return "<i>" + name + " does not exist</i>";
}
if (profile.getSavedQueries().get(newName) != null) {
return "<i>" + newName + " already exists</i>";
}
sq = profile.getSavedQueries().get(name);
profile.deleteQuery(sq.getName());
sq = new SavedQuery(newName, sq.getDateCreated(), sq.getPathQuery());
profile.saveQuery(sq.getName(), sq);
} else if (type.equals("bag")) {
if (profile.getSavedBags().get(name) == null) {
return "<i>" + name + " does not exist</i>";
}
if (profile.getSavedBags().get(newName) != null) {
return "<i>" + newName + " already exists</i>";
}
InterMineBag bag = profile.getSavedBags().get(name);
bag.setName(newName, uosw);
profile.deleteBag(name);
profile.saveBag(newName, bag);
} else {
return "Type unknown";
}
return newName;
}
/**
* For a given bag, set its description
* @param bagName the bag
* @param description the desciprion as entered by the user
* @return the description for display on the jsp page
* @throws Exception an exception
*/
public String saveBagDescription(String bagName, String description) throws Exception {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
Profile profile = (Profile) session.getAttribute(Constants.PROFILE);
ServletContext servletContext = ctx.getServletContext();
ObjectStoreWriter uosw = ((ProfileManager) servletContext.getAttribute(
Constants.PROFILE_MANAGER)).getUserProfileObjectStore();
InterMineBag bag = profile.getSavedBags().get(bagName);
if (bag == null) {
throw new InterMineException("List \"" + bagName + "\" not found.");
}
bag.setDescription(description, uosw);
profile.getSearchRepository().descriptionChanged(bag);
return description;
}
/**
* Set the description of a view path.
* @param pathString the string representation of the path
* @param description the new description
* @return the description, or null if the description was empty
*/
public String changeViewPathDescription(String pathString, String description) {
String descr = description;
if (description.trim().length() == 0) {
descr = null;
}
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
PathQuery query = (PathQuery) session.getAttribute(Constants.QUERY);
Path path = MainHelper.makePath(query.getModel(), query, pathString);
Path prefixPath = path.getPrefix();
if (descr == null) {
query.getPathDescriptions().remove(prefixPath);
} else {
query.getPathDescriptions().put(prefixPath, descr);
}
return descr;
}
/**
* Get the summary for the given column
* @param summaryPath the path for the column as a String
* @param tableName name of column-owning table
* @return a collection of rows
* @throws Exception an exception
*/
public static List getColumnSummary(String tableName, String summaryPath) throws Exception {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
ServletContext servletContext = session.getServletContext();
ObjectStore os = (ObjectStore) servletContext.getAttribute(Constants.OBJECTSTORE);
WebTable webTable = (SessionMethods.getResultsTable(session, tableName))
.getWebTable();
PathQuery pathQuery = webTable.getPathQuery();
SearchRepository globalRepository =
(SearchRepository) servletContext.getAttribute(Constants.
GLOBAL_SEARCH_REPOSITORY);
Profile currentProfile = (Profile) session.getAttribute(Constants.PROFILE);
SearchRepository userSearchRepository = currentProfile.getSearchRepository();
Map<String, InterMineBag> userWsMap =
(Map<String, InterMineBag>) userSearchRepository.getWebSearchableMap(TagTypes.BAG);
Map<String, InterMineBag> globalWsMap =
(Map<String, InterMineBag>) globalRepository.getWebSearchableMap(TagTypes.BAG);
Map<String, InterMineBag> allBags = new HashMap<String, InterMineBag>(userWsMap);
allBags.putAll(globalWsMap);
Query distinctQuery =
MainHelper.makeSummaryQuery(pathQuery, allBags,
new HashMap<String, QueryNode>(), summaryPath,
servletContext);
Results results = os.execute(distinctQuery);
WebResultsSimple webResults = new WebResultsSimple(results,
Arrays.asList(new String[] {"col1", "col2"}));
PagedTable pagedTable = new PagedTable(webResults);
// Start the count of results
QueryMonitorTimeout clientState
= new QueryMonitorTimeout(Constants.QUERY_TIMEOUT_SECONDS * 1000);
MessageResources messages = (MessageResources) ctx.getHttpServletRequest()
.getAttribute(Globals.MESSAGES_KEY);
Query countQuery =
MainHelper.makeSummaryQuery(pathQuery, allBags,
new HashMap<String, QueryNode>(), summaryPath
, servletContext);
String qid = SessionMethods.startQueryCount(clientState, session, messages, countQuery);
return Arrays.asList(new Object[] {
pagedTable.getRows(), qid, new Integer(pagedTable.getExactSize())
});
}
/**
* Return the results from the query with the given query id. If the results aren't yet
* available, return null. The returned List is the visible rows from the PagedTable associated
* with the query id.
* @param qid the id
* @return the current rows from the table
*/
public static List getResults(String qid) {
// results to return if there is an internal error
List<List<String>> unavailableListList = new ArrayList<List<String>>();
ArrayList<String> unavailableList = new ArrayList<String>();
unavailableList.add("results unavailable");
unavailableListList.add(unavailableList);
if (StringUtils.isEmpty(qid)) {
return unavailableListList;
}
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
QueryMonitorTimeout controller = (QueryMonitorTimeout)
SessionMethods.getRunningQueryController(qid, session);
// First tickle the controller to avoid timeout
controller.tickle();
if (controller.isCancelledWithError()) {
LOG.debug("query qid " + qid + " error");
return unavailableListList;
} else if (controller.isCancelled()) {
LOG.debug("query qid " + qid + " cancelled");
return unavailableListList;
} else if (controller.isCompleted()) {
LOG.debug("query qid " + qid + " complete");
// Look at results, if only one result, go straight to object details page
PagedTable pr = SessionMethods.getResultsTable(session, "results." + qid);
return pr.getRows();
} else {
// query still running
LOG.debug("query qid " + qid + " still running, making client wait");
return null;
}
}
/**
* Given a scope, type, tags and some filter text, produce a list of matching WebSearchable, in
* a format useful in JavaScript. Each element of the returned List is a List containing a
* WebSearchable name, a score (from Lucene) and a string with the matching parts of the
* description highlighted.
* @param scope the scope (from TemplateHelper.GLOBAL_TEMPLATE or TemplateHelper.USER_TEMPLATE,
* even though not all WebSearchables are templates)
* @param type the type (from TagTypes)
* @param tags the tags to filter on
* @param filterText the text to pass to Lucene
* @param filterAction toggles favourites filter off an on; will be blank or 'favourites'
* @param callId unique id
* @return a List of Lists
*/
public static List<String> filterWebSearchables(String scope, String type,
List<String> tags, String filterText,
String filterAction, String callId) {
ServletContext servletContext = WebContextFactory.get().getServletContext();
ProfileManager pm = SessionMethods.getProfileManager(servletContext);
HttpSession session = WebContextFactory.get().getSession();
Profile profile = (Profile) session.getAttribute(Constants.PROFILE);
Map<String, WebSearchable> wsMap;
Map<WebSearchable, Float> hitMap = new LinkedHashMap<WebSearchable, Float>();
Map<WebSearchable, String> highlightedDescMap = new HashMap<WebSearchable, String>();
if (filterText != null && filterText.length() > 1) {
wsMap = new LinkedHashMap<String, WebSearchable>();
Map<WebSearchable, String> scopeMap = new LinkedHashMap<WebSearchable, String>();
try {
long time =
SearchRepository.runLeuceneSearch(filterText, scope, type, profile,
servletContext,
hitMap, scopeMap, null, highlightedDescMap);
LOG.info("Lucene search took " + time + " milliseconds");
} catch (ParseException e) {
LOG.error("couldn't run lucene filter", e);
ArrayList emptyList = new ArrayList();
emptyList.add(callId);
return emptyList;
} catch (IOException e) {
LOG.error("couldn't run lucene filter", e);
ArrayList emptyList = new ArrayList();
emptyList.add(callId);
return emptyList;
}
//long time = System.currentTimeMillis();
for (WebSearchable ws: hitMap.keySet()) {
wsMap.put(ws.getName(), ws);
}
} else {
if (scope.equals("user")) {
SearchRepository searchRepository = profile.getSearchRepository();
wsMap = (Map<String, WebSearchable>) searchRepository.getWebSearchableMap(type);
} else {
SearchRepository globalRepository =
(SearchRepository) servletContext.getAttribute(Constants.
GLOBAL_SEARCH_REPOSITORY);
if (scope.equals("global")) {
wsMap = (Map<String, WebSearchable>) globalRepository.getWebSearchableMap(type);
} else {
// must be "all"
SearchRepository userSearchRepository = profile.getSearchRepository();
Map<String, ? extends WebSearchable> userWsMap =
userSearchRepository.getWebSearchableMap(type);
Map<String, ? extends WebSearchable> globalWsMap =
globalRepository.getWebSearchableMap(type);
wsMap = new HashMap<String, WebSearchable>(userWsMap);
wsMap.putAll(globalWsMap);
}
}
}
Map<String, ? extends WebSearchable> filteredWsMap
= new LinkedHashMap<String, WebSearchable>();
//Filter by aspects (defined in superuser account)
List<String> aspectTags = new ArrayList<String>();
List<String> userTags = new ArrayList<String>();
for (String tag :tags) {
if (tag.startsWith("aspect:")) {
aspectTags.add(tag);
} else {
userTags.add(tag);
}
}
if (aspectTags.size() > 0) {
wsMap = pm.filterByTags(wsMap, aspectTags, type,
(String) servletContext.getAttribute(Constants.SUPERUSER_ACCOUNT));
}
if (profile.getUsername() != null && userTags != null && userTags.size() > 0) {
filteredWsMap = pm.filterByTags(wsMap, userTags, type, profile.getUsername());
} else {
filteredWsMap = wsMap;
}
List returnList = new ArrayList<String>();
returnList.add(callId);
for (WebSearchable ws: filteredWsMap.values()) {
List row = new ArrayList();
row.add(ws.getName());
if (filterText != null && filterText.length() > 1) {
row.add(highlightedDescMap.get(ws));
row.add(hitMap.get(ws));
} else {
row.add(ws.getDescription());
}
returnList.add(row);
}
// if(searching) {
// time = System.currentTimeMillis() - time;
// LOG.info("processing in filterWebSearchables() took: " + time + " milliseconds:");
return returnList;
}
}
|
package org.opencms.gwt.client.ui.input;
import org.opencms.gwt.client.I_CmsHasInit;
import org.opencms.gwt.client.ui.I_CmsAutoHider;
import org.opencms.gwt.client.ui.css.I_CmsInputCss;
import org.opencms.gwt.client.ui.css.I_CmsInputLayoutBundle;
import org.opencms.gwt.client.ui.css.I_CmsLayoutBundle;
import org.opencms.gwt.client.ui.input.form.CmsWidgetFactoryRegistry;
import org.opencms.gwt.client.ui.input.form.I_CmsFormWidgetFactory;
import org.opencms.util.CmsStringUtil;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.FocusEvent;
import com.google.gwt.event.dom.client.FocusHandler;
import com.google.gwt.event.dom.client.HasBlurHandlers;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.dom.client.HasFocusHandlers;
import com.google.gwt.event.dom.client.HasKeyPressHandlers;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.event.dom.client.MouseOutEvent;
import com.google.gwt.event.dom.client.MouseOutHandler;
import com.google.gwt.event.dom.client.MouseOverEvent;
import com.google.gwt.event.dom.client.MouseOverHandler;
import com.google.gwt.event.logical.shared.HasValueChangeHandlers;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.TextBox;
/**
* Basic text box class for forms.
*
* @since 8.0.0
*
*/
public class CmsTextBox extends Composite
implements I_CmsFormWidget, I_CmsHasInit, HasFocusHandlers, HasBlurHandlers, HasValueChangeHandlers<String>,
HasKeyPressHandlers, HasClickHandlers, I_CmsHasBlur, I_CmsHasGhostValue {
/**
* Event handler for this text box.<p>
*/
private class TextBoxHandler
implements MouseOverHandler, MouseOutHandler, FocusHandler, BlurHandler, ValueChangeHandler<String>,
KeyPressHandler {
/** The current text box value. */
private String m_currentValue;
/**
* Constructor.<p>
*
* @param currentValue the current text box value
*/
protected TextBoxHandler(String currentValue) {
m_currentValue = currentValue;
}
/**
* @see com.google.gwt.event.dom.client.BlurHandler#onBlur(com.google.gwt.event.dom.client.BlurEvent)
*/
public void onBlur(BlurEvent event) {
if (!m_ghostMode && m_textbox.getText().equals("")) {
setGhostValue(m_ghostValue, true);
} else if (m_ghostMode) {
setGhostStyleEnabled(true);
}
checkForChange();
}
/**
* @see com.google.gwt.event.dom.client.FocusHandler#onFocus(com.google.gwt.event.dom.client.FocusEvent)
*/
public void onFocus(FocusEvent event) {
setGhostStyleEnabled(false);
}
/**
* @see com.google.gwt.event.dom.client.KeyPressHandler#onKeyPress(com.google.gwt.event.dom.client.KeyPressEvent)
*/
public void onKeyPress(KeyPressEvent event) {
int keyCode = event.getNativeEvent().getKeyCode();
if (!isNavigationKey(keyCode)) {
setGhostMode(false);
}
if (isTriggerChangeOnKeyPress()) {
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
public void execute() {
checkForChange();
}
});
}
}
/**
* @see com.google.gwt.event.dom.client.MouseOutHandler#onMouseOut(com.google.gwt.event.dom.client.MouseOutEvent)
*/
public void onMouseOut(MouseOutEvent event) {
hideError();
}
/**
* @see com.google.gwt.event.dom.client.MouseOverHandler#onMouseOver(com.google.gwt.event.dom.client.MouseOverEvent)
*/
public void onMouseOver(MouseOverEvent event) {
if (!isPreventShowError()) {
showError();
}
}
/**
* @see com.google.gwt.event.logical.shared.ValueChangeHandler#onValueChange(ValueChangeEvent event)
*/
public void onValueChange(ValueChangeEvent<String> event) {
setGhostMode(false);
if ((m_ghostValue != null) && "".equals(m_textbox.getValue())) {
m_ghostMode = true;
setGhostStyleEnabled(true);
m_textbox.setValue(m_ghostValue);
}
if (!event.getValue().equals(m_currentValue)) {
m_currentValue = event.getValue();
fireValueChangedEvent();
}
}
/**
* Sets the current value.<p>
*
* @param value the current value
*/
public void setValue(String value) {
m_currentValue = value;
}
/**
* Checks if the current text box value has changed and fires the value changed event.<p>
*/
protected void checkForChange() {
if (!m_textbox.getValue().equals(m_currentValue)) {
m_currentValue = getFormValueAsString();
fireValueChangedEvent();
}
}
}
/** The CSS bundle used for this widget. */
public static final I_CmsInputCss CSS = I_CmsInputLayoutBundle.INSTANCE.inputCss();
/** The widget type identifier for this widget. */
public static final String WIDGET_TYPE = "string";
/** Key codes for functional keys. */
protected static final int[] NAVIGATION_CODES = {
KeyCodes.KEY_ALT,
KeyCodes.KEY_CTRL,
KeyCodes.KEY_DOWN,
KeyCodes.KEY_END,
KeyCodes.KEY_ENTER,
KeyCodes.KEY_ESCAPE,
KeyCodes.KEY_HOME,
KeyCodes.KEY_LEFT,
KeyCodes.KEY_RIGHT,
KeyCodes.KEY_SHIFT,
KeyCodes.KEY_TAB,
KeyCodes.KEY_UP};
/** Default pseudo-padding for text boxes. */
private static final int DEFAULT_PADDING = 4;
/** A counter used for giving text box widgets ids. */
private static int idCounter;
/** Flag for ghost mode. */
protected boolean m_ghostMode;
/** The ghost value. */
protected String m_ghostValue;
/** The text box used internally by this widget. */
protected TextBox m_textbox = new TextBox();
/** Flag indicating if the text box should be cleared when leaving the ghost mode. */
private boolean m_clearOnChangeMode;
/** A list of the click handler registrations for this text box. */
private List<HandlerRegistration> m_clickHandlerRegistrations = new ArrayList<HandlerRegistration>();
/** A list of the click handlers for this text box. */
private List<ClickHandler> m_clickHandlers = new ArrayList<ClickHandler>();
/** Stores the enable/disable state of the textbox. */
private boolean m_enabled;
/** The error display for this widget. */
private CmsErrorWidget m_error = new CmsErrorWidget();
/** The width of the error message. */
private String m_errorMessageWidth;
/** The text box handler instance. */
private TextBoxHandler m_handler;
/** The container for the textbox container and error widget. */
private FlowPanel m_panel = new FlowPanel();
/** Signals whether the error message will be shown on mouse over. */
private boolean m_preventShowError;
/** The container for the text box. */
private CmsPaddedPanel m_textboxContainer = new CmsPaddedPanel(DEFAULT_PADDING);
/** Flag indicating if the value change event should also be fired after key press events. */
private boolean m_triggerChangeOnKeyPress;
/**
* Constructs a new instance of this widget.
*/
public CmsTextBox() {
setEnabled(true);
m_textbox.setStyleName(CSS.textBox());
m_textbox.getElement().setId("CmsTextBox_" + (idCounter++));
TextBoxHandler handler = new TextBoxHandler("");
m_textbox.addMouseOverHandler(handler);
m_textbox.addMouseOutHandler(handler);
m_textbox.addFocusHandler(handler);
m_textbox.addBlurHandler(handler);
m_textbox.addValueChangeHandler(handler);
m_textbox.addKeyPressHandler(handler);
m_handler = handler;
m_textboxContainer.setStyleName(CSS.textBoxPanel());
m_textboxContainer.addStyleName(I_CmsLayoutBundle.INSTANCE.generalCss().cornerAll());
m_textboxContainer.addStyleName(I_CmsLayoutBundle.INSTANCE.generalCss().textMedium());
m_panel.add(m_textboxContainer);
m_panel.add(m_error);
m_textboxContainer.add(m_textbox);
m_textboxContainer.setPaddingX(4);
sinkEvents(Event.ONPASTE);
initWidget(m_panel);
}
/**
* Initializes this class.<p>
*/
public static void initClass() {
// registers a factory for creating new instances of this widget
CmsWidgetFactoryRegistry.instance().registerFactory(WIDGET_TYPE, new I_CmsFormWidgetFactory() {
/**
* @see org.opencms.gwt.client.ui.input.form.I_CmsFormWidgetFactory#createWidget(java.util.Map)
*/
public I_CmsFormWidget createWidget(Map<String, String> widgetParams) {
return new CmsTextBox();
}
});
}
/**
* @see com.google.gwt.event.dom.client.HasBlurHandlers#addBlurHandler(com.google.gwt.event.dom.client.BlurHandler)
*/
public HandlerRegistration addBlurHandler(BlurHandler handler) {
return m_textbox.addBlurHandler(handler);
}
/**
* @see com.google.gwt.event.dom.client.HasClickHandlers#addClickHandler(com.google.gwt.event.dom.client.ClickHandler)
*/
public HandlerRegistration addClickHandler(ClickHandler handler) {
HandlerRegistration registration = addDomHandler(handler, ClickEvent.getType());
m_clickHandlerRegistrations.add(registration);
m_clickHandlers.add(handler);
return registration;
}
/**
* @see com.google.gwt.event.dom.client.HasFocusHandlers#addFocusHandler(com.google.gwt.event.dom.client.FocusHandler)
*/
public HandlerRegistration addFocusHandler(FocusHandler handler) {
return m_textbox.addFocusHandler(handler);
}
/**
* @see com.google.gwt.event.dom.client.HasKeyPressHandlers#addKeyPressHandler(com.google.gwt.event.dom.client.KeyPressHandler)
*/
public HandlerRegistration addKeyPressHandler(KeyPressHandler handler) {
return addDomHandler(handler, KeyPressEvent.getType());
}
/**
* @see com.google.gwt.event.logical.shared.HasValueChangeHandlers#addValueChangeHandler(com.google.gwt.event.logical.shared.ValueChangeHandler)
*/
public HandlerRegistration addValueChangeHandler(ValueChangeHandler<String> handler) {
return addHandler(handler, ValueChangeEvent.getType());
}
/**
* @see org.opencms.gwt.client.ui.input.I_CmsHasBlur#blur()
*/
public void blur() {
m_textbox.getElement().blur();
}
/**
* @see org.opencms.gwt.client.ui.input.I_CmsFormWidget#getApparentValue()
*/
public String getApparentValue() {
String result = m_textbox.getValue();
if (CmsStringUtil.isEmpty(result)) {
result = null;
}
return result;
}
/**
* @see org.opencms.gwt.client.ui.input.I_CmsFormWidget#getFieldType()
*/
public FieldType getFieldType() {
return I_CmsFormWidget.FieldType.STRING;
}
/**
* @see org.opencms.gwt.client.ui.input.I_CmsFormWidget#getFormValue()
*/
public Object getFormValue() {
String result = m_textbox.getText();
if (result.equals("")) {
result = null;
}
return result;
}
/**
* @see org.opencms.gwt.client.ui.input.I_CmsFormWidget#getFormValueAsString()
*/
public String getFormValueAsString() {
if (m_ghostMode) {
return null;
}
return (String)getFormValue();
}
/**
* Returns the HTML id of the internal textbox used by this widget.<p>
*
* @return the HTML id of the internal textbox used by this widget
*/
public String getId() {
return m_textbox.getElement().getId();
}
/**
* Returns the text in the text box.<p>
*
* @return the text
*/
public String getText() {
return m_textbox.getText();
}
/**
* Returns <code>true</code> if this textbox has an error set.<p>
*
* @return <code>true</code> if this textbox has an error set
*/
public boolean hasError() {
return m_error.hasError();
}
/**
* Gets whether this widget is enabled.
*
* @return <code>true</code> if the widget is enabled
*/
public boolean isEnabled() {
return m_enabled;
}
/**
* Returns the preventShowError.<p>
*
* @return the preventShowError
*/
public boolean isPreventShowError() {
return m_preventShowError;
}
/**
* Returns the read only flag.<p>
*
* @return <code>true</code> if this text box is only readable
*/
public boolean isReadOnly() {
return m_textbox.isReadOnly();
}
/**
* Returns if the text box is set to trigger the value changed event on key press and not on blur only.<p>
*
* @return <code>true</code> if the text box is set to trigger the value changed event on key press
*/
public boolean isTriggerChangeOnKeyPress() {
return m_triggerChangeOnKeyPress;
}
/**
* @see com.google.gwt.user.client.ui.Composite#onBrowserEvent(com.google.gwt.user.client.Event)
*/
@Override
public void onBrowserEvent(Event event) {
super.onBrowserEvent(event);
/*
* In IE8, the change event is not fired if we switch to another application window after having
* pasted some text into the text box, so we need to turn off ghost mode manually
*/
if (event.getTypeInt() == Event.ONPASTE) {
setGhostMode(false);
}
}
/**
* @see org.opencms.gwt.client.ui.input.I_CmsFormWidget#reset()
*/
public void reset() {
m_textbox.setText("");
}
/**
* @see org.opencms.gwt.client.ui.input.I_CmsFormWidget#setAutoHideParent(org.opencms.gwt.client.ui.I_CmsAutoHider)
*/
public void setAutoHideParent(I_CmsAutoHider autoHideParent) {
// nothing to do
}
/**
* Sets the changed style on the text box.<p>
*/
public void setChangedStyle() {
m_textbox.addStyleName(CSS.changed());
}
/**
* @see org.opencms.gwt.client.ui.input.I_CmsFormWidget#setEnabled(boolean)
*/
public void setEnabled(boolean enabled) {
if (!m_enabled && enabled) {
// if the state changed to enable then add the stored handlers
// copy the stored handlers into a new list to avoid concurred access to the list
List<ClickHandler> handlers = new ArrayList<ClickHandler>(m_clickHandlers);
m_clickHandlers.clear();
for (ClickHandler handler : handlers) {
addClickHandler(handler);
}
m_textboxContainer.removeStyleName(CSS.textBoxPanelDisabled());
m_enabled = true;
} else if (m_enabled && !enabled) {
// if state changed to disable then remove all click handlers
for (HandlerRegistration registration : m_clickHandlerRegistrations) {
registration.removeHandler();
}
m_clickHandlerRegistrations.clear();
m_textboxContainer.addStyleName(CSS.textBoxPanelDisabled());
setErrorMessage(null);
m_enabled = false;
}
m_textbox.setEnabled(m_enabled);
}
/**
* @see org.opencms.gwt.client.ui.input.I_CmsFormWidget#setErrorMessage(java.lang.String)
*/
public void setErrorMessage(String errorMessage) {
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(errorMessage)) {
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(m_errorMessageWidth)) {
m_error.setWidth(m_errorMessageWidth);
} else {
int width = getOffsetWidth() - 8;
width = width > 0 ? width : 100;
m_error.setWidth(width + Unit.PX.toString());
}
m_textboxContainer.removeStyleName(CSS.textBoxPanel());
m_textboxContainer.addStyleName(CSS.textBoxPanelError());
} else {
m_textboxContainer.removeStyleName(CSS.textBoxPanelError());
m_textboxContainer.addStyleName(CSS.textBoxPanel());
}
m_error.setText(errorMessage);
}
/**
* Sets the width of the error message for this textbox.<p>
*
* @param width the object's new width, in CSS units (e.g. "10px", "1em")
*/
public void setErrorMessageWidth(String width) {
m_errorMessageWidth = width;
}
/**
* Sets the focus on the text box.<p>
*
* @param focused signals if the focus should be set
*/
public void setFocus(boolean focused) {
m_textbox.setFocus(focused);
}
/**
* Sets the value of the widget.<p>
*
* @param value the new value
*/
public void setFormValue(Object value) {
if (value instanceof String) {
String strValue = (String)value;
setText(strValue);
}
}
/**
* @see org.opencms.gwt.client.ui.input.I_CmsFormWidget#setFormValueAsString(java.lang.String)
*/
public void setFormValueAsString(String newValue) {
if (newValue == null) {
newValue = "";
}
if ("".equals(newValue) && (m_ghostValue != null)) {
m_ghostMode = true;
setGhostStyleEnabled(true);
m_textbox.setValue(m_ghostValue);
} else {
setFormValue(newValue);
}
}
/**
* Enables or disables ghost mode.<p>
*
* @param ghostMode if true, enables ghost mode, else disables it
*/
public void setGhostMode(boolean ghostMode) {
//setGhostStyleEnabled(ghostMode);
m_ghostMode = ghostMode;
}
/**
* Sets if the input field should be cleared when leaving the ghost mode.<p>
*
* @param clearOnChangeMode <code>true</code> to clear on leaving the ghost mode
*/
public void setGhostModeClear(boolean clearOnChangeMode) {
m_clearOnChangeMode = clearOnChangeMode;
}
/**
* Enables or disables the "ghost mode" style.<p>
*
* This *only* changes the style, not the actual mode.
*
* @param enabled true if the ghost mode style should be enabled, false if it should be disabled
*/
public void setGhostStyleEnabled(boolean enabled) {
if (enabled) {
m_textbox.addStyleName(CSS.textboxGhostMode());
} else {
m_textbox.removeStyleName(CSS.textboxGhostMode());
if (m_clearOnChangeMode) {
setText("");
}
}
}
/**
* @see org.opencms.gwt.client.ui.input.I_CmsHasGhostValue#setGhostValue(java.lang.String, boolean)
*/
public void setGhostValue(String value, boolean ghostMode) {
m_ghostValue = value;
if (!ghostMode) {
return;
}
m_textbox.setValue(value);
setGhostMode(true);
setGhostStyleEnabled(true);
}
/**
* Sets the preventShowError.<p>
*
* @param preventShowError the preventShowError to set
*/
public void setPreventShowError(boolean preventShowError) {
m_preventShowError = preventShowError;
if (preventShowError) {
m_error.setErrorVisible(false);
}
}
/**
* Enables or disables read-only mode.<p>
*
* @param readOnly if true, enables read-only mode, else disables it
*/
public void setReadOnly(boolean readOnly) {
m_textbox.setReadOnly(readOnly);
if (readOnly) {
addStyleName(CSS.textBoxReadOnly());
} else {
removeStyleName(CSS.textBoxReadOnly());
}
}
/**
* Sets if the value changed event should be triggered on key press and not on blur only.<p>
*
* @param triggerOnKeyPress <code>true</code> if the value changed event should be triggered on key press
*/
public void setTriggerChangeOnKeyPress(boolean triggerOnKeyPress) {
m_triggerChangeOnKeyPress = triggerOnKeyPress;
}
/**
* Updates the layout of the text box.<p>
*/
public void updateLayout() {
m_textboxContainer.updatePadding();
}
/**
* Helper method for firing a 'value changed' event.<p>
*/
protected void fireValueChangedEvent() {
ValueChangeEvent.fire(this, getFormValueAsString());
}
/**
* Hides the error for this textbox.<p>
*/
protected void hideError() {
m_error.hideError();
}
/**
* Checks if the given key code represents a functional key.<p>
*
* @param keyCode the key code to check
*
* @return <code>true</code> if the given key code represents a functional key
*/
protected boolean isNavigationKey(int keyCode) {
for (int i = 0; i < NAVIGATION_CODES.length; i++) {
if (NAVIGATION_CODES[i] == keyCode) {
return true;
}
}
return false;
}
/**
* Shows the error for this textbox.<p>
*/
protected void showError() {
m_error.showError();
}
/**
* Sets the text in the text box.<p>
*
* @param text the new text
*/
private void setText(String text) {
m_textbox.setText(text);
m_handler.setValue(text);
}
}
|
package org.intermine.dwr;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Constructor;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeSet;
import javax.mail.MessagingException;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.lucene.queryParser.ParseException;
import org.apache.struts.Globals;
import org.apache.struts.util.MessageResources;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;
import org.intermine.InterMineException;
import org.intermine.api.InterMineAPI;
import org.intermine.api.bag.BagManager;
import org.intermine.api.bag.TypeConverter;
import org.intermine.api.bag.UnknownBagTypeException;
import org.intermine.api.mines.FriendlyMineManager;
import org.intermine.api.mines.FriendlyMineQueryRunner;
import org.intermine.api.mines.Mine;
import org.intermine.api.profile.BagDoesNotExistException;
import org.intermine.api.profile.BagState;
import org.intermine.api.profile.InterMineBag;
import org.intermine.api.profile.Profile;
import org.intermine.api.profile.ProfileAlreadyExistsException;
import org.intermine.api.profile.ProfileManager;
import org.intermine.api.profile.SavedQuery;
import org.intermine.api.profile.TagManager;
import org.intermine.api.profile.UserAlreadyShareBagException;
import org.intermine.api.profile.UserNotFoundException;
import org.intermine.api.profile.UserPreferences;
import org.intermine.api.query.WebResultsExecutor;
import org.intermine.api.results.WebTable;
import org.intermine.api.search.SearchRepository;
import org.intermine.api.search.SearchResults;
import org.intermine.api.search.SearchTarget;
import org.intermine.api.search.TagFilter;
import org.intermine.api.search.WebSearchable;
import org.intermine.api.tag.TagNames;
import org.intermine.api.tag.TagTypes;
import org.intermine.api.template.ApiTemplate;
import org.intermine.api.template.TemplateManager;
import org.intermine.api.template.TemplateSummariser;
import org.intermine.api.util.NameUtil;
import org.intermine.metadata.ClassDescriptor;
import org.intermine.metadata.FieldDescriptor;
import org.intermine.metadata.ReferenceDescriptor;
import org.intermine.objectstore.ObjectStore;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.objectstore.query.Query;
import org.intermine.objectstore.query.ResultsRow;
import org.intermine.pathquery.OrderDirection;
import org.intermine.pathquery.Path;
import org.intermine.pathquery.PathConstraint;
import org.intermine.pathquery.PathException;
import org.intermine.pathquery.PathQuery;
import org.intermine.template.TemplateQuery;
import org.intermine.util.Emailer;
import org.intermine.util.MailUtils;
import org.intermine.util.StringUtil;
import org.intermine.util.TypeUtil;
import org.intermine.web.autocompletion.AutoCompleter;
import org.intermine.web.context.InterMineContext;
import org.intermine.web.displayer.InterMineLinkGenerator;
import org.intermine.web.logic.Constants;
import org.intermine.web.logic.PortalHelper;
import org.intermine.web.logic.bag.BagConverter;
import org.intermine.web.logic.config.WebConfig;
import org.intermine.web.logic.profile.UpgradeBagList;
import org.intermine.web.logic.query.PageTableQueryMonitor;
import org.intermine.web.logic.query.QueryMonitorTimeout;
import org.intermine.web.logic.results.PagedTable;
import org.intermine.web.logic.results.WebState;
import org.intermine.web.logic.session.QueryCountQueryMonitor;
import org.intermine.web.logic.session.SessionMethods;
import org.json.JSONException;
import org.json.JSONObject;
/**
* This class contains the methods called through DWR Ajax
*
* @author Xavier Watkins
* @author Daniela Butano
*
*/
public class AjaxServices
{
protected static final Logger LOG = Logger.getLogger(AjaxServices.class);
private static final Object ERROR_MSG = "Error happened during DWR ajax service.";
private static final Set<String> NON_WS_TAG_TYPES = new HashSet<String>(Arrays.asList(
TagTypes.CLASS, TagTypes.COLLECTION, TagTypes.REFERENCE));
/**
* Creates a favourite Tag for the given templateName
*
* @param name the name of the template we want to set as a favourite
* @param type type of tag (bag or template)
* @param isFavourite whether or not this item is currently a favourite
*/
public void setFavourite(String name, String type, boolean isFavourite) {
String nameCopy = name.replaceAll("#039;", "'");
try {
// already a favourite. turning off.
if (isFavourite) {
AjaxServices.deleteTag(TagNames.IM_FAVOURITE, nameCopy, type);
// not a favourite. turning on.
} else {
AjaxServices.addTag(TagNames.IM_FAVOURITE, nameCopy, type);
}
} catch (Exception e) {
processException(e);
}
}
private static void processException(Exception e) {
LOG.error(ERROR_MSG, e);
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
}
throw new RuntimeException(e);
}
/**
* Precomputes the given template query
* @param templateName the template query name
* @return a String to guarantee the service ran properly
*/
public String preCompute(String templateName) {
try {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
Profile profile = SessionMethods.getProfile(session);
Map<String, ApiTemplate> templates = profile.getSavedTemplates();
TemplateQuery t = templates.get(templateName);
WebResultsExecutor executor = im.getWebResultsExecutor(profile);
try {
session.setAttribute("precomputing_" + templateName, "true");
executor.precomputeTemplate(t);
} catch (ObjectStoreException e) {
LOG.error("Error while precomputing", e);
} finally {
session.removeAttribute("precomputing_" + templateName);
}
} catch (RuntimeException e) {
processException(e);
}
return "precomputed";
}
/**
* Summarises the given template query.
*
* @param templateName the template query name
* @return a String to guarantee the service ran properly
*/
public String summarise(String templateName) {
try {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
Profile profile = SessionMethods.getProfile(session);
Map<String, ApiTemplate> templates = profile.getSavedTemplates();
ApiTemplate template = templates.get(templateName);
TemplateSummariser summariser = im.getTemplateSummariser();
try {
session.setAttribute("summarising_" + templateName, "true");
summariser.summarise(template);
} catch (ObjectStoreException e) {
LOG.error("Failed to summarise " + templateName, e);
} catch (NullPointerException e) {
NullPointerException e2 = new NullPointerException("No such template "
+ templateName);
e2.initCause(e);
throw e2;
} finally {
session.removeAttribute("summarising_" + templateName);
}
} catch (RuntimeException e) {
processException(e);
}
return "summarised";
}
/**
* Rename a element such as history, name, bag
* @param name the name of the element
* @param type history, saved, bag
* @param reName the new name for the element
* @return the new name of the element as a String
* @exception Exception if the application business logic throws
* an exception
*/
public String rename(String name, String type, String reName)
throws Exception {
String newName;
try {
newName = reName.trim();
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
Profile profile = SessionMethods.getProfile(session);
SavedQuery sq;
if (name.equals(newName) || StringUtils.isEmpty(newName)) {
return name;
}
// TODO get error text from properties file
if (!NameUtil.isValidName(newName)) {
return "<i>" + NameUtil.INVALID_NAME_MSG + "</i>";
}
if ("history".equals(type)) {
if (profile.getHistory().get(name) == null) {
return "<i>" + name + " does not exist</i>";
}
if (profile.getHistory().get(newName) != null) {
return "<i>" + newName + " already exists</i>";
}
profile.renameHistory(name, newName);
} else if ("saved".equals(type)) {
if (profile.getSavedQueries().get(name) == null) {
return "<i>" + name + " does not exist</i>";
}
if (profile.getSavedQueries().get(newName) != null) {
return "<i>" + newName + " already exists</i>";
}
sq = profile.getSavedQueries().get(name);
profile.deleteQuery(sq.getName());
sq = new SavedQuery(newName, sq.getDateCreated(), sq.getPathQuery());
profile.saveQuery(sq.getName(), sq);
} else if ("bag".equals(type)) {
try {
profile.renameBag(name, newName);
} catch (IllegalArgumentException e) {
return "<i>" + name + " does not exist</i>";
} catch (ProfileAlreadyExistsException e) {
return "<i>" + newName + " already exists</i>";
}
} else if ("invalid.bag.type".equals(type)) {
try {
profile.fixInvalidBag(name, newName);
InterMineAPI im = SessionMethods.getInterMineAPI(session);
new Thread(new UpgradeBagList(profile, im.getBagQueryRunner()))
.start();
} catch (UnknownBagTypeException e) {
return "<i>" + e.getMessage() + "</i>";
} catch (ObjectStoreException e) {
return "<i>Error fixing type</i>";
}
} else {
return "Type unknown";
}
return newName;
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* Generate a new API key for a given user.
* @param username the user to generate the key for.
* @return A new API key, or null if something untoward happens.
* @throws Exception an exception.
*/
public String generateApiKey(String username) throws Exception {
try {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
final ProfileManager pm = im.getProfileManager();
Profile p = pm.getProfile(username);
return pm.generateApiKey(p);
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* Delete a user's API key, thus disabling webservice access. A message "deleted"
* is returned to confirm success.
* @param username The user whose key we should delete.
* @return A confirmation string.
* @throws Exception if somethign bad happens
*/
public String deleteApiKey(String username)
throws Exception {
try {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
final ProfileManager pm = im.getProfileManager();
Profile p = pm.getProfile(username);
p.setApiKey(null);
return "deleted";
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* For a given bag, set its description
* @param bagName the bag
* @param description the description as entered by the user
* @return the description for display on the jsp page
* @throws Exception an exception
*/
public String saveBagDescription(String bagName, String description) throws Exception {
try {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
Profile profile = SessionMethods.getProfile(session);
InterMineBag bag = profile.getSavedBags().get(bagName);
if (bag == null) {
throw new InterMineException("List \"" + bagName + "\" not found.");
}
bag.setDescription(description);
return description;
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* Set the description of a view path.
* @param pathString the string representation of the path
* @param description the new description
* @return the description, or null if the description was empty
*/
public String changeViewPathDescription(String pathString, String description) {
try {
String descr = description;
if (description.trim().length() == 0) {
descr = null;
}
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
PathQuery query = SessionMethods.getQuery(session);
Path path = query.makePath(pathString);
Path prefixPath = path.getPrefix();
if (descr == null) {
// setting to null removes the description
query.setDescription(prefixPath.getNoConstraintsString(), null);
} else {
query.setDescription(prefixPath.getNoConstraintsString(), descr);
}
if (descr == null) {
return null;
}
return descr.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">");
} catch (RuntimeException e) {
processException(e);
return null;
} catch (PathException e) {
processException(e);
return null;
}
}
/*
* Cannot be refactored from AjaxServices, else WebContextFactory.get() returns null
*/
private static WebState getWebState() {
HttpSession session = WebContextFactory.get().getSession();
return SessionMethods.getWebState(session);
}
/**
* This method gets a map of ids of elements that were in the past (during session) toggled and
* returns them in JSON
* @return JSON serialized to a String
* @throws JSONException
*/
public static String getToggledElements() {
HttpSession session = WebContextFactory.get().getSession();
WebState webState = SessionMethods.getWebState(session);
Collection<JSONObject> lists = new HashSet<JSONObject>();
try {
for (Map.Entry<String, Boolean> entry : webState.getToggledElements().entrySet()) {
JSONObject list = new JSONObject();
list.put("id", entry.getKey());
list.put("opened", entry.getValue().toString());
lists.add(list);
}
} catch (JSONException jse) {
LOG.error("Errors generating json objects", jse);
}
return lists.toString();
}
/**
* Get the summary for the given column
* @param summaryPath the path for the column as a String
* @param tableName name of column-owning table
* @return a collection of rows
* @throws Exception an exception
*/
public static List getColumnSummary(String tableName, String summaryPath) throws Exception {
try {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
Profile profile = SessionMethods.getProfile(session);
WebResultsExecutor webResultsExecutor = im.getWebResultsExecutor(profile);
WebTable webTable = (SessionMethods.getResultsTable(session, tableName))
.getWebTable();
PathQuery pathQuery = webTable.getPathQuery();
List<ResultsRow> results = (List) webResultsExecutor.summariseQuery(pathQuery,
summaryPath);
// Start the count of results
Query countQuery = webResultsExecutor.makeSummaryQuery(pathQuery, summaryPath);
QueryCountQueryMonitor clientState
= new QueryCountQueryMonitor(Constants.QUERY_TIMEOUT_SECONDS * 1000, countQuery);
MessageResources messages = (MessageResources) ctx.getHttpServletRequest()
.getAttribute(Globals.MESSAGES_KEY);
String qid = SessionMethods.startQueryCount(clientState, session, messages);
List<ResultsRow> pageSizeResults = new ArrayList<ResultsRow>();
int rowCount = 0;
for (ResultsRow row : results) {
rowCount++;
if (rowCount > 10) {
break;
}
pageSizeResults.add(row);
}
return Arrays.asList(new Object[] {pageSizeResults, qid, new Integer(rowCount)});
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* Return the number of rows of results from the query with the given query id. If the size
* isn't yet available, return null. The query must be started with
* SessionMethods.startPagedTableCount().
* @param qid the id
* @return the row count or null if not yet available
*/
public static Integer getResultsSize(String qid) {
try {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
QueryMonitorTimeout controller = (QueryMonitorTimeout)
SessionMethods.getRunningQueryController(qid, session);
// this could happen if the user navigates away then back to the page
if (controller == null) {
return null;
}
// First tickle the controller to avoid timeout
controller.tickle();
if (controller.isCancelledWithError()) {
LOG.debug("query qid " + qid + " error");
return null;
} else if (controller.isCancelled()) {
LOG.debug("query qid " + qid + " cancelled");
return null;
} else if (controller.isCompleted()) {
LOG.debug("query qid " + qid + " complete");
if (controller instanceof PageTableQueryMonitor) {
PagedTable pt = ((PageTableQueryMonitor) controller).getPagedTable();
return new Integer(pt.getExactSize());
}
if (controller instanceof QueryCountQueryMonitor) {
return new Integer(((QueryCountQueryMonitor) controller).getCount());
}
LOG.debug("query qid " + qid + " - unknown controller type");
return null;
} else {
// query still running
LOG.debug("query qid " + qid + " still running, making client wait");
return null;
}
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* Given a scope, type, tags and some filter text, produce a list of matching WebSearchable, in
* a format useful in JavaScript.
* <p>
* Each element of the returned List is a List containing a
* WebSearchable name, a score (from Lucene) and a string with the matching parts of the
* description highlighted.
* <p>
* ie - search for "<code>me</code>":
* <pre>
* [
* [ "Some name", 0.123, "So<i>me</i> name" ],
* ...
* ]
* </pre>
*
* @param scope the scope (either Scope.GLOBAL or Scope.USER).
* @param type the type (from TagTypes).
* @param tags the tags to filter on.
* @param filterText the text to pass to Lucene.
* @param filterAction toggles favourites filter off and on; will be blank or 'favourites'
* @param callId unique id
* @return a List of Lists
*/
public static List<String> filterWebSearchables(String scope, String type,
List<String> tags, String filterText,
String filterAction, String callId) {
try {
final HttpSession session = WebContextFactory.get().getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
final ProfileManager pm = im.getProfileManager();
final Profile profile = SessionMethods.getProfile(session);
final SearchRepository userRepository = profile.getSearchRepository();
final SearchTarget target = new SearchTarget(scope, type);
final SearchResults results;
try {
results = SearchResults.runLuceneSearch(filterText, target, userRepository);
} catch (ParseException e) {
LOG.error("couldn't run lucene filter", e);
ArrayList<String> emptyList = new ArrayList<String>();
emptyList.add(callId);
return emptyList;
} catch (IOException e) {
LOG.error("couldn't run lucene filter", e);
ArrayList<String> emptyList = new ArrayList<String>();
emptyList.add(callId);
return emptyList;
}
//Filter by aspects (defined in superuser account)
List<String> aspectTags = new ArrayList<String>();
List<String> userTags = new ArrayList<String>();
for (String tag :tags) {
if (tag.startsWith(TagNames.IM_ASPECT_PREFIX)) {
aspectTags.add(tag);
} else {
if (profile.getUsername() != null) {
// Only allow filtering from registered users.
userTags.add(tag);
}
}
}
TagFilter aspects = new TagFilter(aspectTags, pm.getSuperuserProfile(), type);
TagFilter requiredTags = new TagFilter(userTags, profile, type);
List returnList = new ArrayList();
returnList.add(callId);
for (org.intermine.api.search.SearchResult sr: results) {
WebSearchable ws = sr.getItem();
if (SearchResults.isInvalidTemplate(ws)) {
continue;
}
if (!(aspects.hasAllTags(ws) && requiredTags.hasAllTags(ws))) {
continue;
}
returnList.add(sr.asList());
}
return returnList;
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* For a given bag name and a type different from the bag type, give the number of
* converted objects
*
* @param bagName the name of the bag
* @param type the type to convert to
* @return the number of converted objects
*/
public static int getConvertCountForBag(String bagName, String type) {
try {
HttpSession session = WebContextFactory.get().getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
String pckName = im.getModel().getPackageName();
Profile profile = SessionMethods.getProfile(session);
BagManager bagManager = im.getBagManager();
TemplateManager templateManager = im.getTemplateManager();
WebResultsExecutor webResultsExecutor = im.getWebResultsExecutor(profile);
int count = 0;
InterMineBag imBag = bagManager.getBag(profile, bagName);
List<ApiTemplate> conversionTemplates = templateManager.getConversionTemplates();
PathQuery pathQuery = TypeConverter.getConversionQuery(conversionTemplates,
TypeUtil.instantiate(pckName + "." + imBag.getType()),
TypeUtil.instantiate(pckName + "." + type), imBag);
count = webResultsExecutor.count(pathQuery);
return count;
} catch (Exception e) {
LOG.error("failed to get type converted counts", e);
return 0;
}
}
/**
* For a list and a converter, return types and related counts
*
* @param bagName the name of the bag
* @param converterName Java class that processes the data
* @return the number of converted objects
*/
public static String getCustomConverterCounts(String bagName, String converterName) {
try {
final HttpSession session = WebContextFactory.get().getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
final Profile profile = SessionMethods.getProfile(session);
final BagManager bagManager = im.getBagManager();
final InterMineBag imBag = bagManager.getBag(profile, bagName);
final ServletContext servletContext = WebContextFactory.get().getServletContext();
final WebConfig webConfig = SessionMethods.getWebConfig(servletContext);
final BagConverter bagConverter = PortalHelper.getBagConverter(im, webConfig,
converterName);
// should be ordered
Map<String, String> results = bagConverter.getCounts(profile, imBag);
List<JSONObject> jsonResults = new LinkedList<JSONObject>();
for (Map.Entry<String, String> entry : results.entrySet()) {
JSONObject organism = new JSONObject();
organism.put("name", entry.getKey());
organism.put("count", entry.getValue());
jsonResults.add(organism);
}
return jsonResults.toString();
} catch (Exception e) {
LOG.error("failed to get custom converter counts", e);
return null;
}
}
/**
* used on REPORT page
*
* For a gene, generate links to other intermines. Include gene and orthologues.
*
* Returns NULL if no values found. It's possible that the identifier in the local mine will
* match more than one entry in the remote mine but this will be handled by the portal of the
* remote mine.
*
* @param mineName name of mine to query
* @param organisms gene.organism
* @param identifiers identifiers for gene
* @return the links to friendly intermines
*/
public static String getFriendlyMineLinks(String mineName, String organisms,
String identifiers) {
if (StringUtils.isEmpty(mineName) || StringUtils.isEmpty(organisms)
|| StringUtils.isEmpty(identifiers)) {
return null;
}
final HttpSession session = WebContextFactory.get().getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
final ServletContext servletContext = WebContextFactory.get().getServletContext();
final Properties webProperties = SessionMethods.getWebProperties(servletContext);
final FriendlyMineManager fmm = FriendlyMineManager.getInstance(im, webProperties);
InterMineLinkGenerator linkGen = null;
Constructor<?> constructor;
try {
Class<?> clazz = TypeUtil.instantiate(
"org.intermine.bio.web.displayer.FriendlyMineLinkGenerator");
constructor = clazz.getConstructor(new Class[] {});
linkGen = (InterMineLinkGenerator) constructor.newInstance(new Object[] {});
} catch (Exception e) {
LOG.error("Failed to instantiate FriendlyMineLinkGenerator because: " + e);
return null;
}
Collection<JSONObject> results = linkGen.getLinks(fmm, mineName, organisms, identifiers);
if (results == null || results.isEmpty()) {
return null;
}
return results.toString();
}
/**
* used on REPORT page
*
* For a gene, display pathways found in other mines for orthologous genes
*
* @param mineName mine to query
* @param orthologues list of genes to query for
* @return the links to friendly intermines
*/
public static String getFriendlyMinePathways(String mineName, String orthologues) {
if (StringUtils.isEmpty(orthologues)) {
return null;
}
Mine mine;
HttpSession session = WebContextFactory.get().getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
final ServletContext servletContext = WebContextFactory.get().getServletContext();
final Properties webProperties = SessionMethods.getWebProperties(servletContext);
final FriendlyMineManager linkManager = FriendlyMineManager.getInstance(im, webProperties);
mine = linkManager.getMine(mineName);
if (mine == null || mine.getReleaseVersion() == null) {
// mine is dead
return null;
}
final String xmlQuery = getXMLQuery("FriendlyMinesPathways.xml", orthologues);
try {
JSONObject results = FriendlyMineQueryRunner.runJSONWebServiceQuery(mine, xmlQuery);
if (results == null) {
LOG.error("Couldn't query " + mine.getName() + " for pathways");
return null;
}
results.put("mineURL", mine.getUrl());
return results.toString();
} catch (IOException e) {
LOG.error("Couldn't query " + mine.getName() + " for pathways", e);
return null;
} catch (JSONException e) {
LOG.error("Error adding Mine URL to pathways results", e);
return null;
} catch (Throwable t) {
LOG.error(t);
return null;
}
}
private static String getXMLQuery(String filename, Object... positionalArgs) {
try {
return String.format(
IOUtils.toString(
AjaxServices.class.getResourceAsStream(filename)), positionalArgs);
} catch (IOException e) {
LOG.error(e);
throw new RuntimeException("Could not read " + filename, e);
} catch (NullPointerException npe) {
LOG.error(npe);
throw new RuntimeException(filename + " not found", npe);
} catch (Throwable e) {
LOG.error(e);
throw new RuntimeException("Unexpected exception", e);
}
}
/**
* Return list of disease ontology terms associated with list of provided rat genes. Returns
* JSONObject as string with ID (intermine ID) and name (ontologyTerm.name)
*
* @param orthologues list of rat genes
* @return JSONobject.toString of JSON object
*/
@SuppressWarnings("unchecked")
public static String getRatDiseases(String orthologues) {
if (StringUtils.isEmpty(orthologues)) {
return null;
}
HttpSession session = WebContextFactory.get().getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
final ServletContext servletContext = WebContextFactory.get().getServletContext();
final Properties webProperties = SessionMethods.getWebProperties(servletContext);
final FriendlyMineManager linkManager = FriendlyMineManager.getInstance(im, webProperties);
Mine mine = linkManager.getMine("RatMine");
HashMap<String, Object> map = new HashMap<String, Object>();
if (mine == null || mine.getReleaseVersion() == null) {
// mine is dead
map.put("status", "offline");
return new JSONObject(map).toString();
}
final String xmlQuery = getXMLQuery("RatDiseases.xml", orthologues);
try {
JSONObject results = FriendlyMineQueryRunner.runJSONWebServiceQuery(mine, xmlQuery);
if (results != null) {
results.put("mineURL", mine.getUrl());
results.put("status", "online");
return results.toString();
}
} catch (IOException e) {
LOG.error("Couldn't query ratmine for diseases", e);
} catch (JSONException e) {
LOG.error("Couldn't process ratmine disease results", e);
}
return null;
}
/**
* Saves information, that some element was toggled - displayed or hidden.
*
* @param elementId element id
* @param opened new aspect state
*/
public static void saveToggleState(String elementId, boolean opened) {
try {
AjaxServices.getWebState().getToggledElements().put(elementId,
Boolean.valueOf(opened));
} catch (RuntimeException e) {
processException(e);
}
}
/**
* Set state that should be saved during the session.
* @param name name of state
* @param value value of state
*/
public static void setState(String name, String value) {
try {
AjaxServices.getWebState().setState(name, value);
} catch (RuntimeException e) {
processException(e);
}
}
/**
* validate bag upload
* @param bagName name of new bag to be validated
* @return error msg to display, if any
*/
public static String validateBagName(String bagName) {
try {
HttpSession session = WebContextFactory.get().getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
Profile profile = SessionMethods.getProfile(session);
BagManager bagManager = im.getBagManager();
bagName = bagName.trim();
// TODO get message text from the properties file
if ("".equals(bagName)) {
return "You cannot save a list with a blank name";
}
if (!NameUtil.isValidName(bagName)) {
return TagManager.INVALID_NAME_MSG;
}
if (profile.getSavedBags().get(bagName) != null) {
return "The list name you have chosen is already in use";
}
if (bagManager.getGlobalBag(bagName) != null) {
return "The list name you have chosen is already in use -"
+ " there is a public list called " + bagName;
}
return "";
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* validation that happens before new bag is saved
* @param bagName name of new list
* @param selectedBags bags involved in operation
* @param operation which operation is taking place - delete, union, intersect or subtract
* @return error msg, if any
*/
public static String validateBagOperations(String bagName, String[] selectedBags,
String operation) {
try {
ServletContext servletContext = WebContextFactory.get().getServletContext();
HttpSession session = WebContextFactory.get().getSession();
Profile profile = SessionMethods.getProfile(session);
// TODO get error text from the properties file
if (selectedBags.length == 0) {
return "No lists are selected";
}
if ("delete".equals(operation)) {
for (int i = 0; i < selectedBags.length; i++) {
Set<String> queries = new HashSet<String>();
queries.addAll(queriesThatMentionBag(profile.getSavedQueries(),
selectedBags[i]));
queries.addAll(queriesThatMentionBag(profile.getHistory(), selectedBags[i]));
if (queries.size() > 0) {
// TODO the javascript method relies on the content of this message.
// which is dumb and should be fixed. in the meantime, don't change this.
final String msg = "You are trying to delete the list: `"
+ selectedBags[i] + "`, which is used by these queries: "
+ queries + ". Select OK to delete the list and queries or Cancel "
+ "to cancel this operation.";
return msg;
}
}
} else if (!"copy".equals(operation)) {
Properties properties = SessionMethods.getWebProperties(servletContext);
String defaultName = properties.getProperty("lists.input.example");
if (bagName.equalsIgnoreCase(defaultName)) {
return "New list name is required";
} else if (!NameUtil.isValidName(bagName)) {
return NameUtil.INVALID_NAME_MSG;
}
}
return "";
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* Provide a list of queries that mention a named bag
* @param savedQueries a saved queries map (name -> query)
* @param bagName the name of a bag
* @return the list of queries
*/
private static List<String> queriesThatMentionBag(Map<String, SavedQuery> savedQueries,
String bagName) {
try {
List<String> queries = new ArrayList<String>();
for (Iterator<String> i = savedQueries.keySet().iterator(); i.hasNext();) {
String queryName = (String) i.next();
SavedQuery query = (SavedQuery) savedQueries.get(queryName);
if (query.getPathQuery().getBagNames().contains(bagName)) {
queries.add(queryName);
}
}
return queries;
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* Add an ID to the PagedTable selection
* @param selectedId the id
* @param tableId the identifier for the PagedTable
* @param columnIndex the column of the selected id
* @return the field values of the first selected objects
*/
public static List<String> selectId(String selectedId, String tableId, String columnIndex) {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
PagedTable pt = SessionMethods.getResultsTable(session, tableId);
pt.selectId(new Integer(selectedId), (new Integer(columnIndex)).intValue());
Map<String, List<FieldDescriptor>> classKeys = im.getClassKeys();
ObjectStore os = im.getObjectStore();
return pt.getFirstSelectedFields(os, classKeys);
}
/**
* remove an Id from the PagedTable
* @param deSelectId the ID to remove from the selection
* @param tableId the PagedTable identifier
* @return the field values of the first selected objects
*/
public static List<String> deSelectId(String deSelectId, String tableId) {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
PagedTable pt = SessionMethods.getResultsTable(session, tableId);
pt.deSelectId(new Integer(deSelectId));
Map<String, List<FieldDescriptor>> classKeys = im.getClassKeys();
ObjectStore os = im.getObjectStore();
return pt.getFirstSelectedFields(os, classKeys);
}
/**
* Select all the elements in a PagedTable
* @param index the index of the selected column
* @param tableId the PagedTable identifier
*/
public static void selectAll(int index, String tableId) {
HttpSession session = WebContextFactory.get().getSession();
PagedTable pt = SessionMethods.getResultsTable(session, tableId);
pt.clearSelectIds();
pt.setAllSelectedColumn(index);
}
/**
* AJAX request - reorder view.
* @param newOrder the new order as a String
* @param oldOrder the previous order as a String
*/
public void reorder(String newOrder, String oldOrder) {
HttpSession session = WebContextFactory.get().getSession();
List<String> newOrderList =
new LinkedList<String>(StringUtil.serializedSortOrderToMap(newOrder).values());
List<String> oldOrderList =
new LinkedList<String>(StringUtil.serializedSortOrderToMap(oldOrder).values());
List<String> view = SessionMethods.getEditingView(session);
ArrayList<String> newView = new ArrayList<String>();
for (int i = 0; i < view.size(); i++) {
String newi = newOrderList.get(i);
int oldi = oldOrderList.indexOf(newi);
newView.add(view.get(oldi));
}
PathQuery query = SessionMethods.getQuery(session);
query.clearView();
query.addViews(newView);
}
/**
* AJAX request - reorder the constraints.
* @param newOrder the new order as a String
* @param oldOrder the previous order as a String
*/
public void reorderConstraints(String newOrder, String oldOrder) {
HttpSession session = WebContextFactory.get().getSession();
List<String> newOrderList =
new LinkedList<String>(StringUtil.serializedSortOrderToMap(newOrder).values());
List<String> oldOrderList =
new LinkedList<String>(StringUtil.serializedSortOrderToMap(oldOrder).values());
PathQuery query = SessionMethods.getQuery(session);
if (query instanceof TemplateQuery) {
TemplateQuery template = (TemplateQuery) query;
for (int index = 0; index < newOrderList.size() - 1; index++) {
String newi = newOrderList.get(index);
int oldi = oldOrderList.indexOf(newi);
if (index != oldi) {
List<PathConstraint> editableConstraints =
template.getModifiableEditableConstraints();
PathConstraint editableConstraint = editableConstraints.remove(oldi);
editableConstraints.add(index, editableConstraint);
template.setEditableConstraints(editableConstraints);
break;
}
}
}
}
/**
* Add a Node from the sort order
* @param path the Path as a String
* @param direction the direction to sort by
* @exception Exception if the application business logic throws
*/
public void addToSortOrder(String path, String direction)
throws Exception {
HttpSession session = WebContextFactory.get().getSession();
PathQuery query = SessionMethods.getQuery(session);
OrderDirection orderDirection = OrderDirection.ASC;
if ("DESC".equals(direction.toUpperCase())) {
orderDirection = OrderDirection.DESC;
}
query.clearOrderBy();
query.addOrderBy(path, orderDirection);
}
/**
* Work as a proxy for fetching remote file (RSS)
* @param rssURL the url
* @return String representation of a file
*/
public static String getNewsPreview(String rssURL) {
try {
URL url = new URL(rssURL);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
StringBuffer sb = new StringBuffer();
// append to string buffer
while ((str = in.readLine()) != null) {
sb.append(str);
}
in.close();
return sb.toString();
} catch (MalformedURLException e) {
return "";
} catch (IOException e) {
return "";
}
}
/**
* Adds tag and assures that there is only one tag for this combination of tag name, tagged
* Object and type.
* @param tag tag name
* @param taggedObject object id that is tagged by this tag
* @param type tag type
* @return 'ok' string if succeeded else error string
*/
public static String addTag(String tag, String taggedObject, String type) {
String tagName = tag;
LOG.info("Called addTag(). tagName:" + tagName + " taggedObject:"
+ taggedObject + " type: " + type);
if (StringUtils.isBlank(tagName)) {
LOG.error("Adding tag failed");
return "tag must not be blank";
}
if (StringUtils.isBlank(taggedObject)) {
LOG.error("Adding tag failed");
return "object to tag must not be blank";
}
try {
final HttpServletRequest request = getRequest();
final Profile profile = getProfile(request);
final InterMineAPI im = SessionMethods.getInterMineAPI(request);
tagName = tagName.trim();
if (profile.getUsername() != null
&& !StringUtils.isEmpty(tagName)
&& !StringUtils.isEmpty(type)
&& !StringUtils.isEmpty(taggedObject)) {
if (tagExists(tagName, taggedObject, type)) {
return "Already tagged with this tag.";
}
TagManager tagManager = getTagManager();
BagManager bm = im.getBagManager();
TemplateManager tm = im.getTemplateManager();
if (NON_WS_TAG_TYPES.contains(type)) {
if (TagTypes.CLASS.equals(type)) {
ClassDescriptor cd = im.getModel().getClassDescriptorByName(taggedObject);
tagManager.addTag(tagName, cd, profile);
} else {
String[] bits = taggedObject.split("\\.");
ClassDescriptor cd = im.getModel().getClassDescriptorByName(bits[0]);
FieldDescriptor fd = cd.getFieldDescriptorByName(bits[1]);
if (fd.isCollection() || fd.isReference()) {
tagManager.addTag(tagName, (ReferenceDescriptor) fd, profile);
}
}
} else {
WebSearchable ws = null;
if (TagTypes.BAG.equals(type)) {
ws = bm.getBag(profile, taggedObject);
} else if (TagTypes.TEMPLATE.equals(type)) {
ws = tm.getUserOrGlobalTemplate(profile, taggedObject);
}
if (ws == null) {
throw new RuntimeException("Could not find " + type + " " + taggedObject);
} else {
tagManager.addTag(tagName, ws, profile);
}
}
return "ok";
}
LOG.error("Adding tag failed: tag='" + tag + "', taggedObject='" + taggedObject
+ "', type='" + type + "'");
return "Adding tag failed.";
} catch (TagManager.TagNamePermissionException e) {
LOG.error("Adding tag failed", e);
return e.getMessage();
} catch (TagManager.TagNameException e) {
LOG.error("Adding tag failed", e);
return e.getMessage();
} catch (Throwable e) {
LOG.error("Adding tag failed", e);
return "Adding tag failed.";
}
}
/**
* Deletes tag.
* @param tagName tag name
* @param tagged id of tagged object
* @param type tag type
* @return 'ok' string if succeeded else error string
*/
public static String deleteTag(String tagName, String tagged, String type) {
LOG.info("Called deleteTag(). tagName:" + tagName + " taggedObject:"
+ tagged + " type: " + type);
try {
HttpServletRequest request = getRequest();
HttpSession session = request.getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
Profile profile = getProfile(request);
TagManager manager = im.getTagManager();
BagManager bm = im.getBagManager();
TemplateManager tm = im.getTemplateManager();
if (NON_WS_TAG_TYPES.contains(type)) {
if (TagTypes.CLASS.equals(type)) {
ClassDescriptor cd = im.getModel().getClassDescriptorByName(tagged);
manager.deleteTag(tagName, cd, profile);
} else {
String[] bits = tagged.split("\\.");
ClassDescriptor cd = im.getModel().getClassDescriptorByName(bits[0]);
FieldDescriptor fd = cd.getFieldDescriptorByName(bits[1]);
if (fd.isCollection() || fd.isReference()) {
manager.deleteTag(tagName, (ReferenceDescriptor) fd, profile);
}
}
return "ok";
} else {
WebSearchable ws = null;
if (TagTypes.BAG.equals(type)) {
ws = (WebSearchable) bm.getBag(profile, tagged);
} else if (TagTypes.TEMPLATE.equals(type)) {
ws = (WebSearchable) tm.getUserOrGlobalTemplate(profile, tagged);
}
if (ws == null) {
throw new RuntimeException("Could not find " + type + " " + tagged);
}
manager.deleteTag(tagName, ws, profile);
}
return "ok";
} catch (Throwable e) {
LOG.error("Deleting tag failed", e);
return "Deleting tag failed.";
}
}
/**
* Returns all tags of specified tag type together with prefixes of these tags.
* For instance: for tag 'bio:experiment' it automatically adds 'bio' tag.
* @param type tag type
* @return tags
*/
public static Set<String> getTags(String type) {
final HttpServletRequest request = getRequest();
final InterMineAPI im = SessionMethods.getInterMineAPI(request.getSession());
final TagManager tagManager = im.getTagManager();
final Profile profile = getProfile(request);
if (profile.isLoggedIn()) {
return tagManager.getUserTagNames(type, profile.getUsername());
}
return new TreeSet<String>();
}
/**
* Returns all tags by which is specified object tagged.
* @param type tag type
* @param tagged id of tagged object
* @return tags
*/
public static Set<String> getObjectTags(String type, String tagged) {
HttpServletRequest request = getRequest();
final InterMineAPI im = SessionMethods.getInterMineAPI(request.getSession());
TagManager tagManager = im.getTagManager();
Profile profile = getProfile(request);
if (profile.isLoggedIn()) {
return tagManager.getObjectTagNames(tagged, type, profile.getUsername());
}
return new TreeSet<String>();
}
private static boolean tagExists(String tag, String taggedObject, String type) {
HttpServletRequest request = getRequest();
final InterMineAPI im = SessionMethods.getInterMineAPI(request.getSession());
TagManager tagManager = im.getTagManager();
String userName = getProfile(request).getUsername();
return tagManager.getObjectTagNames(taggedObject, type, userName).contains(tag);
}
private static Profile getProfile(HttpServletRequest request) {
return SessionMethods.getProfile(request.getSession());
}
/**
* Return the single use API key for the current profile
* @return the single use APi key
*/
public static String getSingleUseKey() {
HttpServletRequest request = getRequest();
Profile profile = SessionMethods.getProfile(request.getSession());
return profile.getSingleUseKey();
}
/**
* Return the request retrieved from the web contest
* @return the request
*/
private static HttpServletRequest getRequest() {
return WebContextFactory.get().getHttpServletRequest();
}
/**
* Return the TagManager
* @return the tag manager
*/
private static TagManager getTagManager() {
HttpServletRequest request = getRequest();
final InterMineAPI im = SessionMethods.getInterMineAPI(request.getSession());
return im.getTagManager();
}
/**
* Set the constraint logic on a query to be the given expression.
*
* @param expression the constraint logic for the query
* @return messages to display in the jsp page
* @throws PathException if the query is invalid
*/
public static String setConstraintLogic(String expression) throws PathException {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
PathQuery query = SessionMethods.getQuery(session);
query.setConstraintLogic(expression);
List<String> messages = query.fixUpForJoinStyle();
StringBuffer messagesToDisplay = new StringBuffer();
for (String message : messages) {
messagesToDisplay.append(message);
//SessionMethods.recordMessage(message, session);
}
return messagesToDisplay.toString();
}
/**
* Get the grouped constraint logic
* @return a list representing the grouped constraint logic
*/
public static String getConstraintLogic() {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
PathQuery query = SessionMethods.getQuery(session);
return (query.getConstraintLogic());
}
/**
* @param suffix string of input before request for more results
* @param wholeList whether or not to show the entire list or a truncated version
* @param field field name from the table for the lucene search
* @param className class name (table in the database) for lucene search
* @return an array of values for this classname.field
*/
public String[] getContent(String suffix, boolean wholeList, String field, String className) {
ServletContext servletContext = WebContextFactory.get().getServletContext();
AutoCompleter ac = SessionMethods.getAutoCompleter(servletContext);
ac.createRAMIndex(className + "." + field);
// swap "-" for spaces, ticket #2357
suffix = suffix.replace("-", " ");
if (!wholeList && suffix.length() > 0) {
String[] shortList = ac.getFastList(suffix, field, 31);
return shortList;
} else if (suffix.length() > 2 && wholeList) {
String[] longList = ac.getList(suffix, field);
return longList;
}
String[] defaultList = {""};
return defaultList;
}
/**
* This method gets the latest bags from the session (SessionMethods) and returns them in JSON
* @return JSON serialized to a String
* @throws JSONException json exception
*/
@SuppressWarnings("unchecked")
public String getSavedBagStatus() throws JSONException {
HttpSession session = WebContextFactory.get().getSession();
@SuppressWarnings("unchecked")
Map<String, InterMineBag> savedBags = SessionMethods.getProfile(session).getSavedBags();
// this is where my lists go
Collection<JSONObject> lists = new HashSet<JSONObject>();
try {
for (Map.Entry<String, InterMineBag> entry : savedBags.entrySet()) {
InterMineBag bag = entry.getValue();
// save to the resulting JSON object only if these are 'actionable' lists
if (bag.isCurrent() || bag.isToUpgrade()) {
JSONObject list = new JSONObject();
list.put("name", entry.getKey());
list.put("status", bag.getState());
if (bag.isCurrent()) {
try {
list.put("size", bag.getSize());
} catch (ObjectStoreException os) {
LOG.error("Problems retrieving size of bag " + bag.getName(), os);
}
} else {
list.put("size", 0);
}
lists.add(list);
}
}
} catch (JSONException jse) {
LOG.error("Errors generating json objects", jse);
}
return lists.toString();
}
/**
* Update with the value given in input the field of the previous template
* saved into the session
* @param field the field to update
* @param value the value
*/
public void updateTemplate(String field, String value) {
HttpSession session = WebContextFactory.get().getSession();
boolean isNewTemplate = (session.getAttribute(Constants.NEW_TEMPLATE) != null)
? true : false;
TemplateQuery templateQuery = (TemplateQuery) SessionMethods.getQuery(session);
if (!isNewTemplate && session.getAttribute(Constants.PREV_TEMPLATE_NAME) == null) {
session.setAttribute(Constants.PREV_TEMPLATE_NAME, templateQuery.getName());
}
try {
PropertyUtils.setSimpleProperty(templateQuery, field, value);
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* Share the bag given in input with the user which userName is input and send email
* @param userName the user which the bag has to be shared with
* @param bagName the bag name to share
* @return 'ok' string if succeeded else error string
*/
public String addUserToShareBag(String userName, String bagName) {
HttpSession session = WebContextFactory.get().getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
final Profile profile = SessionMethods.getProfile(session);
final BagManager bagManager = im.getBagManager();
final Emailer emailer = InterMineContext.getEmailer();
final ProfileManager pm = profile.getProfileManager();
InterMineBag bag = profile.getSavedBags().get(bagName);
Profile invitee = pm.getProfile(userName);
if (bag == null) {
return "This is not one of your lists";
}
if (invitee == null || invitee.getPreferences().containsKey(Constants.HIDDEN)) {
return "User not found."; // Users can request not to be found.
}
if (profile.getUsername().equals(userName)) {
return "You are trying to share this with yourself.";
}
try {
bagManager.shareBagWithUser(bag, invitee);
} catch (UserNotFoundException e1) {
return "User not found."; // Shouldn't happen now, but, hey ho.
} catch (UserAlreadyShareBagException e2) {
return "The user already shares the bag.";
}
try {
if (!invitee.getPreferences().containsKey(Constants.NO_SPAM)) {
emailer.informUserOfNewSharedBag(invitee.getEmailAddress(), profile, bag);
}
} catch (Exception ex) {
LOG.warn("Problems sending sharing list mail.", ex);
}
return "ok";
}
/**
* Un-share the bag given in input with the user which userName is input
* @param userName the user which the bag has to be un-shared with
* @param bagName the bag name to un-share
* @return 'ok' string if succeeded else error string
*/
public String deleteUserToShareBag(String userName, String bagName) {
HttpSession session = WebContextFactory.get().getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
Profile profile = SessionMethods.getProfile(session);
BagManager bagManager = im.getBagManager();
try {
bagManager.unshareBagWithUser(bagName, profile.getUsername(), userName);
} catch (UserNotFoundException unfe) {
return "User not found.";
} catch (BagDoesNotExistException bnee) {
return "That list does not exist.";
}
return "ok";
}
/**
* Return the list of users who have access to this bag because it has been
* shared with them.
*
* TODO: present pretty names for open-id users.
*
* @param bagName the bag name that the users share
* @return the list of users
*/
public Collection<String> getUsersSharingBag(String bagName) {
HttpSession session = WebContextFactory.get().getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
Profile profile = SessionMethods.getProfile(session);
BagManager bagManager = im.getBagManager();
return bagManager.getUsersSharingBag(bagName, profile.getUsername());
}
}
|
package org.pentaho.di.ui.trans.step;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.TraverseEvent;
import org.eclipse.swt.events.TraverseListener;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Monitor;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.logging.LogWriter;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.core.variables.VariableSpace;
import org.pentaho.di.core.variables.Variables;
import org.pentaho.di.laf.BasePropertyHandler;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.trans.StepLoader;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStepMeta;
import org.pentaho.di.trans.step.Messages;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.StepMetaInterface;
import org.pentaho.di.ui.core.PropsUI;
import org.pentaho.di.ui.core.database.dialog.DatabaseDialog;
import org.pentaho.di.ui.core.dialog.ErrorDialog;
import org.pentaho.di.ui.core.gui.GUIResource;
import org.pentaho.di.ui.core.gui.WindowProperty;
import org.pentaho.di.ui.core.widget.ComboVar;
import org.pentaho.di.ui.core.widget.TableView;
public class BaseStepDialog extends Dialog {
protected static VariableSpace variables = new Variables();
protected LogWriter log;
protected String stepname;
protected Label wlStepname;
protected Text wStepname;
protected FormData fdlStepname, fdStepname;
protected Button wOK, wGet, wPreview, wSQL, wCreate, wCancel;
protected FormData fdOK, fdGet, fdPreview, fdSQL, fdCreate, fdCancel;
protected Listener lsOK, lsGet, lsPreview, lsSQL, lsCreate, lsCancel;
protected TransMeta transMeta;
protected Shell shell;
protected SelectionAdapter lsDef;
protected Listener lsResize;
protected boolean changed, backupChanged;
protected BaseStepMeta baseStepMeta;
protected PropsUI props;
protected Repository repository;
protected StepMeta stepMeta;
protected static final int BUTTON_ALIGNMENT_CENTER = 0;
protected static final int BUTTON_ALIGNMENT_LEFT = 1;
protected static final int BUTTON_ALIGNMENT_RIGHT = 2;
protected static int buttonAlignment = BUTTON_ALIGNMENT_CENTER;
static {
// Get the button alignment
buttonAlignment = getButtonAlignment();
}
public BaseStepDialog(Shell parent, BaseStepMeta baseStepMeta, TransMeta transMeta, String stepname) {
super(parent, SWT.NONE);
this.log = LogWriter.getInstance();
this.transMeta = transMeta;
this.stepname = stepname;
this.stepMeta = transMeta.findStep(stepname);
this.baseStepMeta = baseStepMeta;
this.backupChanged = baseStepMeta.hasChanged();
this.props = PropsUI.getInstance();
}
public BaseStepDialog(Shell parent, int nr, BaseStepMeta in, TransMeta tr) {
this(parent, in, tr, null);
}
public void setShellImage(Shell shell, StepMetaInterface stepMetaInterface) {
try {
String id = StepLoader.getInstance().getStepPluginID(stepMetaInterface);
if (id != null) {
shell.setImage(GUIResource.getInstance().getImagesSteps().get(id));
}
} catch (Throwable e) {
}
}
public void dispose() {
WindowProperty winprop = new WindowProperty(shell);
props.setScreen(winprop);
shell.dispose();
}
/**
* Set the shell size, based upon the previous time the geometry was saved in the Properties file.
*/
public void setSize() {
setSize(shell);
}
protected void setButtonPositions(Button buttons[], int margin, Control lastControl) {
BaseStepDialog.positionBottomButtons(shell, buttons, margin, lastControl);
}
/**
* Position the specified buttons at the bottom of the parent composite.
* Also, make the buttons all the same width: the width of the largest button.
* <P>
* The default alignment for buttons in the system will be used. This is set as an LAF
* property with the key <code>Button_Position</code> and has the valid values
* of <code>left, center, right</code> with <code>center</code> being the default.
*
* @param buttons The buttons to position.
* @param margin The margin between the buttons in pixels
*/
public static final void positionBottomButtons(Composite composite, Button buttons[], int margin, Control lastControl) {
// Determine the largest button in the array
Rectangle largest = null;
for (int i = 0; i < buttons.length; i++) {
buttons[i].pack(true);
Rectangle r = buttons[i].getBounds();
if (largest == null || r.width > largest.width)
largest = r;
// Also, set the tooltip the same as the name if we don't have one...
if (buttons[i].getToolTipText() == null) {
buttons[i].setToolTipText(Const.replace(buttons[i].getText(), "&", "")); //$NON-NLS-1$ //$NON-NLS-2$
}
}
// Make buttons a bit larger... (nicer)
largest.width += 10;
if ((largest.width % 2) == 1)
largest.width++;
// Compute the left side of the 1st button (based on the system button alignment)
switch (buttonAlignment) {
case BUTTON_ALIGNMENT_CENTER:
centerButtons(buttons, largest.width, margin, lastControl);
break;
case BUTTON_ALIGNMENT_LEFT:
leftAlignButtons(buttons, largest.width, margin, lastControl);
break;
case BUTTON_ALIGNMENT_RIGHT:
rightAlignButtons(buttons, largest.width, margin, lastControl);
break;
}
if (Const.isOSX())
{
Shell parentShell=composite.getShell();
final List<TableView> tableViews = new ArrayList<TableView>();
getTableViews(parentShell, tableViews);
for (final Button button : buttons) {
// We know the table views
// We also know that if a button is hit, the table loses focus
// In that case, we can apply the content of an open text editor...
button.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
for (TableView view : tableViews)
{
view.applyOSXChanges();
}
}
});
}
}
}
private static final void getTableViews(Control parentControl, List<TableView> tableViews)
{
if (parentControl instanceof TableView)
{
tableViews.add((TableView) parentControl);
}
else
{
if (parentControl instanceof Composite)
{
Control[] children = ((Composite)parentControl).getChildren();
for (Control child : children)
{
getTableViews(child, tableViews);
}
}
else
{
if (parentControl instanceof Shell)
{
Control[] children = ((Shell)parentControl).getChildren();
for (Control child : children)
{
getTableViews(child, tableViews);
}
}
}
}
}
/**
* Returns the default alignment for the buttons. This is set in the
* LAF properties with the key <code>Button_Position</code>.
* The valid values are:<UL>
* <LI><code>left</code>
* <LI><code>center</code>
* <LI><code>right</code>
* </UL>
* NOTE: if the alignment is not provided or contains an invalid value, <code>center</code>
* will be used as a default
* @return a constant which indicates the button alignment
*/
protected static int getButtonAlignment() {
String buttonAlign = BasePropertyHandler.getProperty("Button_Position", "center").toLowerCase(); //$NON-NLS-1$ //$NON-NLS-2$
if ("center".equals(buttonAlign)) { //$NON-NLS-1$
return BUTTON_ALIGNMENT_CENTER;
} else if ("left".equals(buttonAlign)) { //$NON-NLS-1$
return BUTTON_ALIGNMENT_LEFT;
} else {
return BUTTON_ALIGNMENT_RIGHT;
}
}
/**
* Creats a default FormData object with the top / bottom / and left set (this is done to
* cut down on repetative code lines
* @param button the button to which this form data will be applied
* @param width the width of the button
* @param margin the margin between buttons
* @param lastControl the last control above the buttons
* @return the newly created FormData object
*/
private static FormData createDefaultFormData(Button button, int width, int margin, Control lastControl) {
FormData formData = new FormData();
if (lastControl != null) {
formData.top = new FormAttachment(lastControl, margin * 3);
} else {
formData.bottom = new FormAttachment(100, 0);
}
formData.right = new FormAttachment(button, width + margin);
return formData;
}
/**
* Aligns the buttons as left-aligned on the dialog
* @param buttons the array of buttons to align
* @param width the standardized width of all the buttons
* @param margin the margin between buttons
* @param lastControl (optional) the bottom most control used for aligning the buttons relative
* to the bottom of the controls on the dialog
*/
protected static void leftAlignButtons(Button[] buttons, int width, int margin, Control lastControl) {
for (int i = 0; i < buttons.length; ++i) {
FormData formData = createDefaultFormData(buttons[i], width, margin, lastControl);
// Set the left side of the buttons (either offset from the edge, or relative to the previous button)
if (i == 0) {
formData.left = new FormAttachment(0, margin);
} else {
formData.left = new FormAttachment(buttons[i - 1], margin);
}
// Apply the layout data
buttons[i].setLayoutData(formData);
}
}
/**
* Aligns the buttons as right-aligned on the dialog
* @param buttons the array of buttons to align
* @param width the standardized width of all the buttons
* @param margin the margin between buttons
* @param lastControl (optional) the bottom most control used for aligning the buttons relative
* to the bottom of the controls on the dialog
*/
protected static void rightAlignButtons(Button[] buttons, int width, int margin, Control lastControl) {
for (int i = buttons.length - 1; i >= 0; --i) {
FormData formData = createDefaultFormData(buttons[i], width, margin, lastControl);
// Set the right side of the buttons (either offset from the edge, or relative to the previous button)
if (i == buttons.length - 1) {
formData.left = new FormAttachment(100, -(width + margin));
} else {
formData.left = new FormAttachment(buttons[i + 1], -(2 * (width + margin)) - margin);
}
// Apply the layout data
buttons[i].setLayoutData(formData);
}
}
/**
* Aligns the buttons as centered on the dialog
* @param buttons the array of buttons to align
* @param width the standardized width of all the buttons
* @param margin the margin between buttons
* @param lastControl (optional) the bottom most control used for aligning the buttons relative
* to the bottom of the controls on the dialog
*/
protected static void centerButtons(Button[] buttons, int width, int margin, Control lastControl) {
// Setup the middle button
int middleButtonIndex = buttons.length / 2;
FormData formData = createDefaultFormData(buttons[middleButtonIndex], width, margin, lastControl);
// See if we have an even or odd number of buttons...
int leftOffset = 0;
if (buttons.length % 2 == 0) {
// Even number of buttons - the middle is between buttons. The "middle" button is
// actually to the right of middle
leftOffset = margin;
} else {
// Odd number of buttons - tht middle is in the middle of the button
leftOffset = -(width + margin) / 2;
}
formData.left = new FormAttachment(50, leftOffset);
buttons[middleButtonIndex].setLayoutData(formData);
// Do the buttons to the right of the middle
for (int i = middleButtonIndex + 1; i < buttons.length; ++i) {
formData = createDefaultFormData(buttons[i], width, margin, lastControl);
formData.left = new FormAttachment(buttons[i - 1], margin);
buttons[i].setLayoutData(formData);
}
// Do the buttons to the left of the middle
for (int i = middleButtonIndex - 1; i >= 0; --i) {
formData = createDefaultFormData(buttons[i], width, margin, lastControl);
formData.left = new FormAttachment(buttons[i + 1], -(2 * (width + margin)) - margin);
buttons[i].setLayoutData(formData);
}
}
public static final ModifyListener getModifyListenerTooltipText(final Text textField) {
return new ModifyListener() {
public void modifyText(ModifyEvent e) {
// maybe replace this with extra arguments
textField.setToolTipText(variables.environmentSubstitute(textField.getText()));
}
};
}
public void addDatabases(CCombo wConnection) {
addDatabases(wConnection, -1);
}
public void addDatabases(CCombo wConnection, int databaseType) {
for (int i = 0; i < transMeta.nrDatabases(); i++) {
DatabaseMeta ci = transMeta.getDatabase(i);
if (ci.getDatabaseType()==databaseType || databaseType<0)
{
wConnection.add(ci.getName());
}
}
}
public void selectDatabase(CCombo wConnection, String name) {
int idx = wConnection.indexOf(name);
if (idx >= 0) {
wConnection.select(idx);
}
}
public CCombo addConnectionLine(Composite parent, Control previous, int middle, int margin) {
return addConnectionLine(parent, previous, middle, margin, new Label(parent, SWT.RIGHT), null, null);
}
public CCombo addConnectionLine(Composite parent, Control previous, int middle, int margin, int databaseType) {
return addConnectionLine(parent, previous, middle, margin, new Label(parent, SWT.RIGHT), new Button(parent,
SWT.PUSH), new Button(parent, SWT.PUSH), databaseType);
}
public CCombo addConnectionLine(Composite parent, Control previous, int middle, int margin, final Label wlConnection,
final Button wbnConnection, final Button wbeConnection) {
return addConnectionLine(parent, previous, middle, margin, -1);
}
public CCombo addConnectionLine(Composite parent, Control previous, int middle, int margin, final Label wlConnection,
final Button wbnConnection, final Button wbeConnection, final int databaseType) {
final CCombo wConnection;
final FormData fdlConnection, fdbConnection, fdeConnection, fdConnection;
wConnection = new CCombo(parent, SWT.BORDER | SWT.READ_ONLY);
props.setLook(wConnection);
addDatabases(wConnection);
wlConnection.setText(Messages.getString("BaseStepDialog.Connection.Label")); //$NON-NLS-1$
props.setLook(wlConnection);
fdlConnection = new FormData();
fdlConnection.left = new FormAttachment(0, 0);
fdlConnection.right = new FormAttachment(middle, -margin);
if (previous != null)
fdlConnection.top = new FormAttachment(previous, margin);
else
fdlConnection.top = new FormAttachment(0, 0);
wlConnection.setLayoutData(fdlConnection);
// NEW button
wbnConnection.setText(Messages.getString("BaseStepDialog.NewConnectionButton.Label")); //$NON-NLS-1$
wbnConnection.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
DatabaseMeta databaseMeta = new DatabaseMeta();
databaseMeta.shareVariablesWith(transMeta);
DatabaseDialog cid = new DatabaseDialog(shell, databaseMeta);
cid.setModalDialog(true);
if (cid.open() != null) {
transMeta.addDatabase(databaseMeta);
wConnection.removeAll();
addDatabases(wConnection, databaseType);
selectDatabase(wConnection, databaseMeta.getName());
}
}
});
fdbConnection = new FormData();
fdbConnection.right = new FormAttachment(100, 0);
if (previous != null)
fdbConnection.top = new FormAttachment(previous, margin);
else
fdbConnection.top = new FormAttachment(0, 0);
wbnConnection.setLayoutData(fdbConnection);
// Edit button
wbeConnection.setText(Messages.getString("BaseStepDialog.EditConnectionButton.Label")); //$NON-NLS-1$
wbeConnection.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
DatabaseMeta databaseMeta = transMeta.findDatabase(wConnection.getText());
if (databaseMeta != null) {
databaseMeta.shareVariablesWith(transMeta);
DatabaseDialog cid = new DatabaseDialog(shell, databaseMeta);
cid.setModalDialog(true);
if (cid.open() != null) {
wConnection.removeAll();
addDatabases(wConnection);
selectDatabase(wConnection, databaseMeta.getName());
}
}
}
});
fdeConnection = new FormData();
fdeConnection.right = new FormAttachment(wbnConnection, -margin);
if (previous != null)
fdeConnection.top = new FormAttachment(previous, margin);
else
fdeConnection.top = new FormAttachment(0, 0);
wbeConnection.setLayoutData(fdeConnection);
// what's left of the line: combo box
fdConnection = new FormData();
fdConnection.left = new FormAttachment(middle, 0);
if (previous != null)
fdConnection.top = new FormAttachment(previous, margin);
else
fdConnection.top = new FormAttachment(0, 0);
fdConnection.right = new FormAttachment(wbeConnection, -margin);
wConnection.setLayoutData(fdConnection);
return wConnection;
}
public void storeScreenSize() {
props.setScreen(new WindowProperty(shell));
}
public String toString() {
return this.getClass().getName();
}
/**
* @return Returns the repository.
*/
public Repository getRepository() {
return repository;
}
/**
* @param repository The repository to set.
*/
public void setRepository(Repository repository) {
this.repository = repository;
}
public static void setMinimalShellHeight(Shell shell, Control[] controls, int margin, int extra) {
int height = 0;
for (int i = 0; i < controls.length; i++) {
Rectangle bounds = controls[i].getBounds();
height += bounds.height + margin;
}
height += extra;
shell.setSize(shell.getBounds().width, height);
}
public static void setSize(Shell shell) {
setSize(shell, -1, -1, true);
}
public static void setSize(Shell shell, int minWidth, int minHeight, boolean packIt) {
PropsUI props = PropsUI.getInstance();
WindowProperty winprop = props.getScreen(shell.getText());
if (winprop != null) {
winprop.setShell(shell, minWidth, minHeight);
} else {
if (packIt)
shell.pack();
else
shell.layout();
// OK, sometimes this produces dialogs that are waay too big.
// Try to limit this a bit, m'kay?
// Use the same algorithm by cheating :-)
winprop = new WindowProperty(shell);
winprop.setShell(shell, minWidth, minHeight);
// Now, as this is the first time it gets opened, try to put it in the middle of the screen...
Rectangle shellBounds = shell.getBounds();
Monitor monitor = shell.getDisplay().getPrimaryMonitor();
if (shell.getParent() != null)
{
monitor = shell.getParent().getMonitor();
}
Rectangle monitorClientArea = monitor.getClientArea();
int middleX = monitorClientArea.x + (monitorClientArea.width - shellBounds.width) / 2;
int middleY = monitorClientArea.y + (monitorClientArea.height - shellBounds.height) / 2;
shell.setLocation(middleX, middleY);
}
}
public static final void setTraverseOrder(final Control[] controls) {
for (int i = 0; i < controls.length; i++) {
final int controlNr = i;
if (i < controls.length - 1) {
controls[i].addTraverseListener(new TraverseListener() {
public void keyTraversed(TraverseEvent te) {
te.doit = false;
// set focus on the next control.
// What is the next control?
int thisOne = controlNr + 1;
while (!controls[thisOne].isEnabled()) {
thisOne++;
if (thisOne >= controls.length)
thisOne = 0;
if (thisOne == controlNr)
return; // already tried all others, time to quit.
}
controls[thisOne].setFocus();
}
});
} else // Link last item to first.
{
controls[i].addTraverseListener(new TraverseListener() {
public void keyTraversed(TraverseEvent te) {
te.doit = false;
// set focus on the next control.
// set focus on the next control.
// What is the next control : 0
int thisOne = 0;
while (!controls[thisOne].isEnabled()) {
thisOne++;
if (thisOne >= controls.length)
return; // already tried all others, time to quit.
}
controls[thisOne].setFocus();
}
});
}
}
}
/**
* Gets unused fields from previous steps and inserts them as rows into a table view.
* @param r
* @param fields
* @param i
* @param js the column in the table view to match with the names of the fields, checks for existance if >0
* @param nameColumn
* @param j
* @param lengthColumn
* @param listener
*/
public static final void getFieldsFromPrevious(TransMeta transMeta, StepMeta stepMeta, TableView tableView,
int keyColumn, int nameColumn[], int dataTypeColumn[], int lengthColumn, int precisionColumn,
TableItemInsertListener listener) {
try {
RowMetaInterface row = transMeta.getPrevStepFields(stepMeta);
if (row != null) {
getFieldsFromPrevious(row, tableView, keyColumn, nameColumn, dataTypeColumn, lengthColumn, precisionColumn,
listener);
}
} catch (KettleException ke) {
new ErrorDialog(
tableView.getShell(),
Messages.getString("BaseStepDialog.FailedToGetFields.Title"), Messages.getString("BaseStepDialog.FailedToGetFields.Message", stepMeta.getName()), ke); //$NON-NLS-1$ //$NON-NLS-2$
}
}
/**
* Gets unused fields from previous steps and inserts them as rows into a table view.
* @param row the input fields
* @param tableView the table view to modify
* @param keyColumn the column in the table view to match with the names of the fields, checks for existance if >0
* @param nameColumn the column numbers in which the name should end up in
* @param dataTypeColumn the target column numbers in which the data type should end up in
* @param lengthColumn the length column where the length should end up in (if >0)
* @param precisionColumn the length column where the precision should end up in (if >0)
* @param listener A listener that you can use to do custom modifications to the inserted table item, based on a value from the provided row
*/
public static final void getFieldsFromPrevious(RowMetaInterface row, TableView tableView, int keyColumn,
int nameColumn[], int dataTypeColumn[], int lengthColumn, int precisionColumn, TableItemInsertListener listener) {
if (row == null || row.size() == 0)
return; // nothing to do
Table table = tableView.table;
// get a list of all the non-empty keys (names)
List<String> keys = new ArrayList<String>();
for (int i = 0; i < table.getItemCount(); i++) {
TableItem tableItem = table.getItem(i);
String key = tableItem.getText(keyColumn);
if (!Const.isEmpty(key) && keys.indexOf(key) < 0)
keys.add(key);
}
int choice = 0;
if (keys.size() > 0) {
// Ask what we should do with the existing data in the step.
MessageDialog md = new MessageDialog(tableView.getShell(), Messages.getString("BaseStepDialog.GetFieldsChoice.Title"),//"Warning!" //$NON-NLS-1$
null, Messages.getString("BaseStepDialog.GetFieldsChoice.Message", "" + keys.size(), "" + row.size()), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
MessageDialog.WARNING, new String[] { Messages.getString("BaseStepDialog.AddNew"), //$NON-NLS-1$
Messages.getString("BaseStepDialog.Add"), Messages.getString("BaseStepDialog.ClearAndAdd"), //$NON-NLS-1$ //$NON-NLS-2$
Messages.getString("BaseStepDialog.Cancel"), }, 0); //$NON-NLS-1$
MessageDialog.setDefaultImage(GUIResource.getInstance().getImageSpoon());
int idx = md.open();
choice = idx & 0xFF;
}
if (choice == 3 || choice == 255 /* 255 = escape pressed */)
return; // Cancel clicked
if (choice == 2) {
tableView.clearAll(false);
}
for (int i = 0; i < row.size(); i++) {
ValueMetaInterface v = row.getValueMeta(i);
boolean add = true;
if (choice == 0) // hang on, see if it's not yet in the table view
{
if (keys.indexOf(v.getName()) >= 0)
add = false;
}
if (add) {
TableItem tableItem = new TableItem(table, SWT.NONE);
for (int c = 0; c < nameColumn.length; c++) {
tableItem.setText(nameColumn[c], Const.NVL(v.getName(), "")); //$NON-NLS-1$
}
if ( dataTypeColumn != null )
{
for (int c = 0; c < dataTypeColumn.length; c++) {
tableItem.setText(dataTypeColumn[c], v.getTypeDesc());
}
}
if (lengthColumn > 0) {
if (v.getLength() >= 0)
tableItem.setText(lengthColumn, Integer.toString(v.getLength()));
}
if (precisionColumn > 0) {
if (v.getPrecision() >= 0)
tableItem.setText(precisionColumn, Integer.toString(v.getPrecision()));
}
if (listener != null) {
if (!listener.tableItemInserted(tableItem, v)) {
tableItem.dispose(); // remove it again
}
}
}
}
tableView.removeEmptyRows();
tableView.setRowNums();
tableView.optWidth(true);
}
/**
* Gets fields from previous steps and populate a ComboVar.
* @param comboVar the comboVar to populate
* @param TransMeta the source transformation
* @param StepMeta the source step
*/
public static final void getFieldsFromPrevious(ComboVar comboVar,TransMeta transMeta,StepMeta stepMeta)
{
String selectedField=null;
int indexField=-1;
try{
RowMetaInterface r = transMeta.getPrevStepFields(stepMeta);
selectedField=comboVar.getText();
comboVar.removeAll();
if (r!=null && !r.isEmpty()) {
r.getFieldNames();
comboVar.setItems(r.getFieldNames());
indexField=r.indexOfValue(selectedField);
}
// Select value if possible...
if(indexField>-1) comboVar.select(indexField); else { if(selectedField!=null) comboVar.setText(selectedField);};
}catch(KettleException ke){
new ErrorDialog(comboVar.getShell(),Messages.getString("BaseStepDialog.FailedToGetFieldsPrevious.DialogTitle"),
Messages.getString("BaseStepDialog.FailedToGetFieldsPrevious.DialogMessage"),ke);
}
}
}
|
package org.intermine.dwr;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeMap;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.lucene.queryParser.ParseException;
import org.apache.struts.Globals;
import org.apache.struts.util.MessageResources;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;
import org.intermine.InterMineException;
import org.intermine.metadata.FieldDescriptor;
import org.intermine.metadata.Model;
import org.intermine.model.userprofile.Tag;
import org.intermine.objectstore.ObjectStore;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.objectstore.ObjectStoreWriter;
import org.intermine.objectstore.intermine.ObjectStoreInterMineImpl;
import org.intermine.objectstore.query.Query;
import org.intermine.objectstore.query.QuerySelectable;
import org.intermine.objectstore.query.Results;
import org.intermine.path.Path;
import org.intermine.pathquery.PathQuery;
import org.intermine.util.StringUtil;
import org.intermine.util.TypeUtil;
import org.intermine.web.autocompletion.AutoCompleter;
import org.intermine.web.logic.Constants;
import org.intermine.web.logic.WebUtil;
import org.intermine.web.logic.bag.BagHelper;
import org.intermine.web.logic.bag.BagQueryConfig;
import org.intermine.web.logic.bag.BagQueryRunner;
import org.intermine.web.logic.bag.InterMineBag;
import org.intermine.web.logic.bag.TypeConverter;
import org.intermine.web.logic.config.Type;
import org.intermine.web.logic.config.WebConfig;
import org.intermine.web.logic.profile.Profile;
import org.intermine.web.logic.profile.ProfileManager;
import org.intermine.web.logic.query.MainHelper;
import org.intermine.web.logic.query.PageTableQueryMonitor;
import org.intermine.web.logic.query.QueryMonitorTimeout;
import org.intermine.web.logic.query.SavedQuery;
import org.intermine.web.logic.results.PagedTable;
import org.intermine.web.logic.results.WebResultsSimple;
import org.intermine.web.logic.results.WebState;
import org.intermine.web.logic.results.WebTable;
import org.intermine.web.logic.search.SearchRepository;
import org.intermine.web.logic.search.WebSearchable;
import org.intermine.web.logic.session.QueryCountQueryMonitor;
import org.intermine.web.logic.session.SessionMethods;
import org.intermine.web.logic.tagging.TagNames;
import org.intermine.web.logic.tagging.TagTypes;
import org.intermine.web.logic.template.TemplateHelper;
import org.intermine.web.logic.template.TemplateQuery;
import org.intermine.web.logic.widget.EnrichmentWidget;
import org.intermine.web.logic.widget.GraphWidget;
import org.intermine.web.logic.widget.GridWidget;
import org.intermine.web.logic.widget.TableWidget;
import org.intermine.web.logic.widget.config.EnrichmentWidgetConfig;
import org.intermine.web.logic.widget.config.GraphWidgetConfig;
import org.intermine.web.logic.widget.config.GridWidgetConfig;
import org.intermine.web.logic.widget.config.TableWidgetConfig;
import org.intermine.web.logic.widget.config.WidgetConfig;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;
/**
* This class contains the methods called through DWR Ajax
*
* @author Xavier Watkins
*
*/
public class AjaxServices
{
protected static final Logger LOG = Logger.getLogger(AjaxServices.class);
private static final Object ERROR_MSG = "Error happened during DWR ajax service.";
/**
* Creates a favourite Tag for the given templateName
*
* @param name the name of the template we want to set as a favourite
* @param type type of tag (bag or template)
* @param isFavourite whether or not this item is currently a favourite
*/
public void setFavourite(String name, String type, boolean isFavourite) {
try {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
Profile profile = (Profile) session.getAttribute(Constants.PROFILE);
HttpServletRequest request = ctx.getHttpServletRequest();
String nameCopy = name.replaceAll("#039;", "'");
ProfileManager pm = getProfileManager(request);
// already a favourite. turning off.
if (isFavourite) {
List<Tag> tags;
Tag tag;
if (type.equals(TagTypes.TEMPLATE)) {
tags = pm.getTags("favourite", nameCopy, TagTypes.TEMPLATE,
profile.getUsername());
} else if (type.equals(TagTypes.BAG)) {
tags = pm.getTags("favourite", nameCopy, TagTypes.BAG, profile.getUsername());
} else {
throw new RuntimeException("Unknown tag type.");
}
if (tags.isEmpty()) {
throw new RuntimeException("User tried to mark a non-existent template "
+ "as favourite");
}
tag = tags.get(0);
pm.deleteTag(tag);
// not a favourite. turning on.
} else {
if (type.equals(TagTypes.TEMPLATE)) {
pm.addTag("favourite", nameCopy, TagTypes.TEMPLATE, profile.getUsername());
} else if (type.equals(TagTypes.BAG)) {
pm.addTag("favourite", nameCopy, TagTypes.BAG, profile.getUsername());
} else {
throw new RuntimeException("Unknown tag type.");
}
}
} catch (RuntimeException e) {
processException(e);
}
}
private static void processException(Exception e) {
LOG.error(ERROR_MSG, e);
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
}
throw new RuntimeException(e);
}
/**
* Precomputes the given template query
* @param templateName the template query name
* @return a String to guarantee the service ran properly
*/
public String preCompute(String templateName) {
try {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
ServletContext servletContext = ctx.getServletContext();
Profile profile = (Profile) session.getAttribute(Constants.PROFILE);
Map<String, TemplateQuery> templates = profile.getSavedTemplates();
TemplateQuery template = templates.get(templateName);
ObjectStoreInterMineImpl os = (ObjectStoreInterMineImpl) servletContext
.getAttribute(Constants.OBJECTSTORE);
List<QuerySelectable> indexes = new ArrayList<QuerySelectable>();
Query query = TemplateHelper.getPrecomputeQuery(template, indexes, null);
try {
if (!os.isPrecomputed(query, "template")) {
session.setAttribute("precomputing_" + templateName, "true");
os.precompute(query, indexes, "template");
}
} catch (ObjectStoreException e) {
LOG.error(e);
} finally {
session.removeAttribute("precomputing_" + templateName);
}
} catch (RuntimeException e) {
processException(e);
}
return "precomputed";
}
/**
* Summarises the given template query.
*
* @param templateName the template query name
* @return a String to guarantee the service ran properly
*/
public String summarise(String templateName) {
try {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
ServletContext servletContext = ctx.getServletContext();
Profile profile = (Profile) session.getAttribute(Constants.PROFILE);
Map<String, TemplateQuery> templates = profile.getSavedTemplates();
TemplateQuery template = templates.get(templateName);
ObjectStoreInterMineImpl os = (ObjectStoreInterMineImpl) servletContext
.getAttribute(Constants.OBJECTSTORE);
ObjectStoreWriter osw = ((ProfileManager) servletContext.getAttribute(
Constants.PROFILE_MANAGER)).getUserProfileObjectStore();
try {
session.setAttribute("summarising_" + templateName, "true");
template.summarise(os, osw);
} catch (ObjectStoreException e) {
LOG.error("Failed to summarise " + templateName, e);
} catch (NullPointerException e) {
NullPointerException e2 = new NullPointerException("No such template "
+ templateName);
e2.initCause(e);
throw e2;
} finally {
session.removeAttribute("summarising_" + templateName);
}
} catch (RuntimeException e) {
processException(e);
}
return "summarised";
}
/**
* Rename a element such as history, name, bag
* @param name the name of the element
* @param type history, saved, bag
* @param reName the new name for the element
* @return the new name of the element as a String
* @exception Exception if the application business logic throws
* an exception
*/
public String rename(String name, String type, String reName)
throws Exception {
String newName;
try {
newName = reName.trim();
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
Profile profile = (Profile) session.getAttribute(Constants.PROFILE);
ServletContext servletContext = ctx.getServletContext();
ObjectStoreWriter uosw = ((ProfileManager) servletContext.getAttribute(
Constants.PROFILE_MANAGER)).getUserProfileObjectStore();
SavedQuery sq;
if (name.equals(newName) || StringUtils.isEmpty(newName)) {
return name;
}
// TODO get error text from properties file
if (!WebUtil.isValidName(newName)) {
String errorMsg = "<i>Invalid name. Names may only contain letters, "
+ "numbers, spaces, and underscores.</i>";
return errorMsg;
}
if (type.equals("history")) {
if (profile.getHistory().get(name) == null) {
return "<i>" + name + " does not exist</i>";
}
if (profile.getHistory().get(newName) != null) {
return "<i>" + newName + " already exists</i>";
}
profile.renameHistory(name, newName);
} else if (type.equals("saved")) {
if (profile.getSavedQueries().get(name) == null) {
return "<i>" + name + " does not exist</i>";
}
if (profile.getSavedQueries().get(newName) != null) {
return "<i>" + newName + " already exists</i>";
}
sq = profile.getSavedQueries().get(name);
profile.deleteQuery(sq.getName());
sq = new SavedQuery(newName, sq.getDateCreated(), sq.getPathQuery());
profile.saveQuery(sq.getName(), sq);
} else if (type.equals("bag")) {
if (profile.getSavedBags().get(name) == null) {
return "<i>" + name + " does not exist</i>";
}
if (profile.getSavedBags().get(newName) != null) {
return "<i>" + newName + " already exists</i>";
}
InterMineBag bag = profile.getSavedBags().get(name);
bag.setName(newName, uosw);
profile.deleteBag(name);
profile.saveBag(newName, bag);
} else {
return "Type unknown";
}
return newName;
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* For a given bag, set its description
* @param bagName the bag
* @param description the description as entered by the user
* @return the description for display on the jsp page
* @throws Exception an exception
*/
public String saveBagDescription(String bagName, String description) throws Exception {
try {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
Profile profile = (Profile) session.getAttribute(Constants.PROFILE);
ServletContext servletContext = ctx.getServletContext();
ObjectStoreWriter uosw = ((ProfileManager) servletContext.getAttribute(
Constants.PROFILE_MANAGER)).getUserProfileObjectStore();
InterMineBag bag = profile.getSavedBags().get(bagName);
if (bag == null) {
throw new InterMineException("List \"" + bagName + "\" not found.");
}
bag.setDescription(description, uosw);
profile.getSearchRepository().descriptionChanged(bag);
return description;
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* Set the description of a view path.
* @param pathString the string representation of the path
* @param description the new description
* @return the description, or null if the description was empty
*/
public String changeViewPathDescription(String pathString, String description) {
try {
String descr = description;
if (description.trim().length() == 0) {
descr = null;
}
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
PathQuery query = (PathQuery) session.getAttribute(Constants.QUERY);
Path path = PathQuery.makePath(query.getModel(), query, pathString);
Path prefixPath = path.getPrefix();
if (descr == null) {
query.getPathDescriptions().remove(prefixPath);
} else {
query.getPathDescriptions().put(prefixPath, descr);
}
return descr;
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/*
* Cannot be refactored from AjaxServices, else WebContextFactory.get() returns null
*/
private static WebState getWebState() {
HttpSession session = WebContextFactory.get().getSession();
return SessionMethods.getWebState(session);
}
/**
* Get the summary for the given column
* @param summaryPath the path for the column as a String
* @param tableName name of column-owning table
* @return a collection of rows
* @throws Exception an exception
*/
public static List getColumnSummary(String tableName, String summaryPath) throws Exception {
try {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
ServletContext servletContext = session.getServletContext();
ObjectStore os = (ObjectStore) servletContext.getAttribute(Constants.OBJECTSTORE);
WebTable webTable = (SessionMethods.getResultsTable(session, tableName))
.getWebTable();
PathQuery pathQuery = webTable.getPathQuery();
SearchRepository globalRepository =
(SearchRepository) servletContext.getAttribute(Constants.
GLOBAL_SEARCH_REPOSITORY);
Profile currentProfile = (Profile) session.getAttribute(Constants.PROFILE);
SearchRepository userSearchRepository = currentProfile.getSearchRepository();
Map<String, InterMineBag> userWsMap =
(Map<String, InterMineBag>) userSearchRepository.getWebSearchableMap(TagTypes.BAG);
Map<String, InterMineBag> globalWsMap =
(Map<String, InterMineBag>) globalRepository.getWebSearchableMap(TagTypes.BAG);
Map<String, InterMineBag> allBags = new HashMap<String, InterMineBag>(userWsMap);
allBags.putAll(globalWsMap);
Query distinctQuery = MainHelper.makeSummaryQuery(pathQuery, allBags,
new HashMap<String, QuerySelectable>(), summaryPath, servletContext);
Results results = os.execute(distinctQuery);
WebResultsSimple webResults = new WebResultsSimple(results,
Arrays.asList(new String[] {"col1", "col2"}));
PagedTable pagedTable = new PagedTable(webResults);
// Start the count of results
Query countQuery = MainHelper.makeSummaryQuery(pathQuery, allBags,
new HashMap<String, QuerySelectable>(), summaryPath, servletContext);
QueryCountQueryMonitor clientState
= new QueryCountQueryMonitor(Constants.QUERY_TIMEOUT_SECONDS * 1000, countQuery);
MessageResources messages = (MessageResources) ctx.getHttpServletRequest()
.getAttribute(Globals.MESSAGES_KEY);
String qid = SessionMethods.startQueryCount(clientState, session, messages);
return Arrays.asList(new Object[] {
pagedTable.getRows(), qid, new Integer(pagedTable.getExactSize())
});
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* Return the number of rows of results from the query with the given query id. If the size
* isn't yet available, return null. The query must be started with
* SessionMethods.startPagedTableCount().
* @param qid the id
* @return the row count or null if not yet available
*/
public static Integer getResultsSize(String qid) {
try {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
QueryMonitorTimeout controller = (QueryMonitorTimeout)
SessionMethods.getRunningQueryController(qid, session);
// this could happen if the user navigates away then back to the page
if (controller == null) {
return null;
}
// First tickle the controller to avoid timeout
controller.tickle();
if (controller.isCancelledWithError()) {
LOG.debug("query qid " + qid + " error");
return null;
} else if (controller.isCancelled()) {
LOG.debug("query qid " + qid + " cancelled");
return null;
} else if (controller.isCompleted()) {
LOG.debug("query qid " + qid + " complete");
if (controller instanceof PageTableQueryMonitor) {
PagedTable pt = ((PageTableQueryMonitor) controller).getPagedTable();
return new Integer(pt.getExactSize());
}
if (controller instanceof QueryCountQueryMonitor) {
return new Integer(((QueryCountQueryMonitor) controller).getCount());
}
LOG.debug("query qid " + qid + " - unknown controller type");
return null;
} else {
// query still running
LOG.debug("query qid " + qid + " still running, making client wait");
return null;
}
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* Given a scope, type, tags and some filter text, produce a list of matching WebSearchable, in
* a format useful in JavaScript. Each element of the returned List is a List containing a
* WebSearchable name, a score (from Lucene) and a string with the matching parts of the
* description highlighted.
* @param scope the scope (from TemplateHelper.GLOBAL_TEMPLATE or TemplateHelper.USER_TEMPLATE,
* even though not all WebSearchables are templates)
* @param type the type (from TagTypes)
* @param tags the tags to filter on
* @param filterText the text to pass to Lucene
* @param filterAction toggles favourites filter off an on; will be blank or 'favourites'
* @param callId unique id
* @return a List of Lists
*/
public static List<String> filterWebSearchables(String scope, String type,
List<String> tags, String filterText,
String filterAction, String callId) {
try {
ServletContext servletContext = WebContextFactory.get().getServletContext();
ProfileManager pm = SessionMethods.getProfileManager(servletContext);
HttpSession session = WebContextFactory.get().getSession();
Profile profile = (Profile) session.getAttribute(Constants.PROFILE);
Map<String, WebSearchable> wsMap;
Map<WebSearchable, Float> hitMap = new LinkedHashMap<WebSearchable, Float>();
Map<WebSearchable, String> highlightedDescMap = new HashMap<WebSearchable, String>();
if (filterText != null && filterText.length() > 1) {
wsMap = new LinkedHashMap<String, WebSearchable>();
Map<WebSearchable, String> scopeMap = new LinkedHashMap<WebSearchable, String>();
try {
long time =
SearchRepository.runLeuceneSearch(filterText, scope, type, profile,
servletContext,
hitMap, scopeMap, null, highlightedDescMap);
LOG.info("Lucene search took " + time + " milliseconds");
} catch (ParseException e) {
LOG.error("couldn't run lucene filter", e);
ArrayList<String> emptyList = new ArrayList<String>();
emptyList.add(callId);
return emptyList;
} catch (IOException e) {
LOG.error("couldn't run lucene filter", e);
ArrayList<String> emptyList = new ArrayList<String>();
emptyList.add(callId);
return emptyList;
}
//long time = System.currentTimeMillis();
for (WebSearchable ws: hitMap.keySet()) {
wsMap.put(ws.getName(), ws);
}
} else {
if (scope.equals("user")) {
SearchRepository searchRepository = profile.getSearchRepository();
wsMap = (Map<String, WebSearchable>) searchRepository.getWebSearchableMap(type);
} else {
SearchRepository globalRepository =
(SearchRepository) servletContext.getAttribute(Constants.
GLOBAL_SEARCH_REPOSITORY);
if (scope.equals("global")) {
wsMap = (Map<String, WebSearchable>) globalRepository.
getWebSearchableMap(type);
} else {
// must be "all"
SearchRepository userSearchRepository = profile.getSearchRepository();
Map<String, ? extends WebSearchable> userWsMap =
userSearchRepository.getWebSearchableMap(type);
Map<String, ? extends WebSearchable> globalWsMap =
globalRepository.getWebSearchableMap(type);
wsMap = new HashMap<String, WebSearchable>(userWsMap);
wsMap.putAll(globalWsMap);
}
}
}
Map<String, ? extends WebSearchable> filteredWsMap
= new LinkedHashMap<String, WebSearchable>();
//Filter by aspects (defined in superuser account)
List<String> aspectTags = new ArrayList<String>();
List<String> userTags = new ArrayList<String>();
for (String tag :tags) {
if (tag.startsWith("aspect:")) {
aspectTags.add(tag);
} else {
userTags.add(tag);
}
}
if (aspectTags.size() > 0) {
wsMap = pm.filterByTags(wsMap, aspectTags, type,
(String) servletContext.getAttribute(Constants.SUPERUSER_ACCOUNT));
}
if (profile.getUsername() != null && userTags.size() > 0) {
filteredWsMap = pm.filterByTags(wsMap, userTags, type, profile.getUsername());
} else {
filteredWsMap = wsMap;
}
List returnList = new ArrayList<String>();
returnList.add(callId);
SearchRepository.filterOutInvalidTemplates(filteredWsMap);
for (WebSearchable ws: filteredWsMap.values()) {
List row = new ArrayList();
row.add(ws.getName());
if (filterText != null && filterText.length() > 1) {
row.add(highlightedDescMap.get(ws));
row.add(hitMap.get(ws));
} else {
row.add(ws.getDescription());
}
returnList.add(row);
}
return returnList;
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* For a given bag name and a type different from the bag type, give the number of
* converted objects
*
* @param bagName the name of the bag
* @param type the type to convert to
* @return the number of converted objects
*/
public static int getConvertCountForBag(String bagName, String type) {
try {
ServletContext servletContext = WebContextFactory.get().getServletContext();
HttpSession session = WebContextFactory.get().getSession();
ObjectStore os = (ObjectStore) servletContext.getAttribute(Constants.OBJECTSTORE);
String pckName = os.getModel().getPackageName();
Profile profile = (Profile) session.getAttribute(Constants.PROFILE);
SearchRepository searchRepository =
SearchRepository.getGlobalSearchRepository(servletContext);
InterMineBag imBag = null;
int count = 0;
try {
imBag = BagHelper.getBag(profile, searchRepository, bagName);
Map<String, QuerySelectable> pathToQueryNode = new HashMap();
Map<String, InterMineBag> bagMap = new HashMap<String, InterMineBag>();
bagMap.put(imBag.getName(), imBag);
PathQuery pathQuery = TypeConverter.getConversionQuery(BagQueryRunner.
getConversionTemplates(servletContext),
TypeUtil.instantiate(pckName + "." + imBag.getType()),
TypeUtil.instantiate(pckName + "." + type), imBag);
Query query = MainHelper.makeQuery(pathQuery, bagMap, pathToQueryNode,
servletContext, null, false,
(ObjectStore) servletContext.getAttribute(Constants.OBJECTSTORE),
getClassKeys(servletContext),
(BagQueryConfig) servletContext.getAttribute(Constants.BAG_QUERY_CONFIG));
count = os.count(query, ObjectStore.SEQUENCE_IGNORE);
} catch (Exception e) {
throw new RuntimeException(e);
}
return count;
} catch (RuntimeException e) {
processException(e);
return 0;
}
}
/**
* Saves information, that some element was toggled - displayed or hidden.
*
* @param elementId element id
* @param opened new aspect state
*/
public static void saveToggleState(String elementId, boolean opened) {
try {
AjaxServices.getWebState().getToggledElements().put(elementId,
Boolean.valueOf(opened));
} catch (RuntimeException e) {
processException(e);
}
}
/**
* Set state that should be saved during the session.
* @param name name of state
* @param value value of state
*/
public static void setState(String name, String value) {
try {
AjaxServices.getWebState().setState(name, value);
} catch (RuntimeException e) {
processException(e);
}
}
/**
* Get state.
* @param name name of state
* @return value if state was set before during the session else null
*/
public static String getState(String name) {
try {
return (String) AjaxServices.getWebState().getState(name);
} catch (RuntimeException e) {
processException(e);
}
return null;
}
/**
* validate bag upload
* @param bagName name of new bag to be validated
* @return error msg to display, if any
*/
public static String validateBagName(String bagName) {
try {
ServletContext servletContext = WebContextFactory.get().getServletContext();
HttpSession session = WebContextFactory.get().getSession();
Profile profile = (Profile) session.getAttribute(Constants.PROFILE);
// TODO get message text from the properties file
if (bagName.equals("")) {
return "You cannot save a list with a blank name";
}
if (!WebUtil.isValidName(bagName)) {
return "Invalid name. Names can only contain letters, numbers, spaces, "
+ "and underscores.";
}
if (profile.getSavedBags().get(bagName) != null) {
return "The list name you have chosen is already in use";
}
SearchRepository searchRepository =
SearchRepository.getGlobalSearchRepository(servletContext);
Map<String, ? extends WebSearchable> publicBagMap =
searchRepository.getWebSearchableMap(TagTypes.BAG);
if (publicBagMap.get(bagName) != null) {
return "The list name you have chosen is already in use -"
+ " there is a public list called " + bagName;
}
return "";
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* validation that happens before new bag is saved
* @param bagName name of new bag
* @param selectedBags bags involved in operation
* @param operation which operation is taking place - delete, union, intersect or subtract
* @return error msg, if any
*/
public static String validateBagOperations(String bagName, String[] selectedBags,
String operation) {
try {
ServletContext servletContext = WebContextFactory.get().getServletContext();
HttpSession session = WebContextFactory.get().getSession();
Profile profile = (Profile) session.getAttribute(Constants.PROFILE);
// TODO get error text from the properties file
if (selectedBags.length == 0) {
return "No lists are selected";
}
if (operation.equals("delete")) {
for (int i = 0; i < selectedBags.length; i++) {
Set<String> queries = new HashSet<String>();
queries.addAll(queriesThatMentionBag(profile.getSavedQueries(),
selectedBags[i]));
queries.addAll(queriesThatMentionBag(profile.getHistory(),
selectedBags[i]));
if (queries.size() > 0) {
return "List " + selectedBags[i] + " cannot be deleted as it is referenced "
+ "by other queries " + queries;
}
}
} else {
Properties properties = (Properties)
servletContext.getAttribute(Constants.WEB_PROPERTIES);
String defaultName = properties.getProperty("lists.input.example");
if (!operation.equals("copy") && (bagName.equals("")
|| (bagName.equalsIgnoreCase(defaultName)))) {
return "New list name is required";
} else if (!WebUtil.isValidName(bagName)) {
return "Invalid name. Names can only contain letters, numbers, spaces, "
+ "and underscores.";
}
}
return "";
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* Provide a list of queries that mention a named bag
* @param savedQueries a saved queries map (name -> query)
* @param bagName the name of a bag
* @return the list of queries
*/
public static List<String> queriesThatMentionBag(Map savedQueries, String bagName) {
try {
List<String> queries = new ArrayList<String>();
for (Iterator i = savedQueries.keySet().iterator(); i.hasNext();) {
String queryName = (String) i.next();
SavedQuery query = (SavedQuery) savedQueries.get(queryName);
if (query.getPathQuery().getBagNames().contains(bagName)) {
queries.add(queryName);
}
}
return queries;
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* @param widgetId unique id for this widget
* @param bagName name of list
* @param selectedExtraAttribute extra attribute (like organism)
* @return graph widget
*/
public static GraphWidget getProcessGraphWidget(String widgetId, String bagName,
String selectedExtraAttribute) {
try {
ServletContext servletContext = WebContextFactory.get().getServletContext();
HttpSession session = WebContextFactory.get().getSession();
WebConfig webConfig = (WebConfig) servletContext.getAttribute(Constants.WEBCONFIG);
ObjectStore os = (ObjectStore) servletContext.getAttribute(Constants.OBJECTSTORE);
Model model = os.getModel();
Profile profile = (Profile) session.getAttribute(Constants.PROFILE);
SearchRepository searchRepository =
SearchRepository.getGlobalSearchRepository(servletContext);
InterMineBag imBag = BagHelper.getBag(profile, searchRepository, bagName);
Type type = (Type) webConfig.getTypes().get(model.getPackageName()
+ "." + imBag.getType());
List<WidgetConfig> widgets = type.getWidgets();
for (WidgetConfig widget: widgets) {
if (widget.getId().equals(widgetId)) {
GraphWidgetConfig graphWidgetConf = (GraphWidgetConfig) widget;
graphWidgetConf.setSession(session);
GraphWidget graphWidget = new GraphWidget(graphWidgetConf, imBag, os,
selectedExtraAttribute);
return graphWidget;
}
}
} catch (RuntimeException e) {
processException(e);
} catch (InterMineException e) {
processException(e);
}
return null;
}
/**
*
* @param widgetId unique ID for this widget
* @param bagName name of list
* @return table widget
*/
public static TableWidget getProcessTableWidget(String widgetId, String bagName) {
try {
ServletContext servletContext = WebContextFactory.get().getServletContext();
HttpSession session = WebContextFactory.get().getSession();
WebConfig webConfig = (WebConfig) servletContext.getAttribute(Constants.WEBCONFIG);
ObjectStore os = (ObjectStore) servletContext.getAttribute(Constants.OBJECTSTORE);
Model model = os.getModel();
Profile profile = (Profile) session.getAttribute(Constants.PROFILE);
SearchRepository searchRepository =
SearchRepository.getGlobalSearchRepository(servletContext);
InterMineBag imBag = BagHelper.getBag(profile, searchRepository, bagName);
Map classKeys = getClassKeys(servletContext);
Type type = (Type) webConfig.getTypes().get(model.getPackageName()
+ "." + imBag.getType());
List<WidgetConfig> widgets = type.getWidgets();
for (WidgetConfig widgetConfig: widgets) {
if (widgetConfig.getId().equals(widgetId)) {
TableWidgetConfig tableWidgetConfig = (TableWidgetConfig) widgetConfig;
tableWidgetConfig.setClassKeys(classKeys);
tableWidgetConfig.setWebConfig(webConfig);
TableWidget tableWidget = new TableWidget(tableWidgetConfig, imBag, os, null);
return tableWidget;
}
}
} catch (RuntimeException e) {
processException(e);
} catch (InterMineException e) {
processException(e);
}
return null;
}
/**
*
* @param widgetId unique ID for each widget
* @param bagName name of list
* @param errorCorrection error correction method to use
* @param max maximum value to display
* @param filters list of strings used to filter widget results, ie Ontology
* @param externalLink link to external datasource
* @param externalLinkLabel name of external datasource.
* @return enrichment widget
*/
public static EnrichmentWidget getProcessEnrichmentWidget(String widgetId, String bagName,
String errorCorrection, String max,
String filters,
String externalLink,
String externalLinkLabel) {
try {
ServletContext servletContext = WebContextFactory.get().getServletContext();
HttpSession session = WebContextFactory.get().getSession();
WebConfig webConfig = (WebConfig) servletContext.getAttribute(Constants.WEBCONFIG);
ObjectStore os = (ObjectStore) servletContext.getAttribute(Constants.OBJECTSTORE);
Model model = os.getModel();
Profile profile = (Profile) session.getAttribute(Constants.PROFILE);
SearchRepository searchRepository = SearchRepository
.getGlobalSearchRepository(servletContext);
InterMineBag imBag = BagHelper.getBag(profile, searchRepository, bagName);
Type type = (Type) webConfig.getTypes().get(model.getPackageName()
+ "." + imBag.getType());
List<WidgetConfig> widgets = type.getWidgets();
for (WidgetConfig widgetConfig : widgets) {
if (widgetConfig.getId().equals(widgetId)) {
EnrichmentWidgetConfig enrichmentWidgetConfig =
(EnrichmentWidgetConfig) widgetConfig;
enrichmentWidgetConfig.setExternalLink(externalLink);
enrichmentWidgetConfig.setExternalLinkLabel(externalLinkLabel);
EnrichmentWidget enrichmentWidget = new EnrichmentWidget(
enrichmentWidgetConfig, imBag, os, filters, max,
errorCorrection);
return enrichmentWidget;
}
}
} catch (RuntimeException e) {
processException(e);
} catch (InterMineException e) {
processException(e);
}
return null;
}
/**
*
* @param widgetId unique ID for each widget
* @param bagName name of list
* @param highlight for highlighting
* @param pValue pValue
* @param numberOpt numberOpt
* @param externalLink link to external datasource
* @param externalLinkLabel name of external datasource.
* @return enrichment widget
*/
public static GridWidget getProcessGridWidget(String widgetId, String bagName,
String highlight,
String pValue,
String numberOpt,
String externalLink,
String externalLinkLabel) {
try {
ServletContext servletContext = WebContextFactory.get().getServletContext();
HttpSession session = WebContextFactory.get().getSession();
WebConfig webConfig = (WebConfig) servletContext.getAttribute(Constants.WEBCONFIG);
ObjectStore os = (ObjectStore) servletContext.getAttribute(Constants.OBJECTSTORE);
Model model = os.getModel();
Profile profile = (Profile) session.getAttribute(Constants.PROFILE);
SearchRepository searchRepository = SearchRepository
.getGlobalSearchRepository(servletContext);
InterMineBag imBag = BagHelper.getBag(profile, searchRepository, bagName);
Type type = (Type) webConfig.getTypes().get(model.getPackageName()
+ "." + imBag.getType());
List<WidgetConfig> widgets = type.getWidgets();
for (WidgetConfig widgetConfig : widgets) {
if (widgetConfig.getId().equals(widgetId)) {
GridWidgetConfig gridWidgetConfig =
(GridWidgetConfig) widgetConfig;
gridWidgetConfig.setExternalLink(externalLink);
gridWidgetConfig.setExternalLinkLabel(externalLinkLabel);
GridWidget gridWidget = new GridWidget(
gridWidgetConfig, imBag, os, null, highlight, pValue, numberOpt);
return gridWidget;
}
}
} catch (RuntimeException e) {
processException(e);
} catch (InterMineException e) {
processException(e);
}
return null;
}
/**
* Add an ID to the PagedTable selection
* @param selectedId the id
* @param tableId the identifier for the PagedTable
* @param columnIndex the column of the selected id
* @return the field values of the first selected objects
*/
public static List<String> selectId(String selectedId, String tableId, String columnIndex) {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
ServletContext servletContext = ctx.getServletContext();
PagedTable pt = SessionMethods.getResultsTable(session, tableId);
pt.selectId(new Integer(selectedId), (new Integer(columnIndex)).intValue());
Map<String, List<FieldDescriptor>> classKeys = getClassKeys(servletContext);
ObjectStore os = (ObjectStore) servletContext.getAttribute(Constants.OBJECTSTORE);
return pt.getFirstSelectedFields(os, classKeys);
}
/**
* remove an Id from the PagedTable
* @param deSelectId the ID to remove from the selection
* @param tableId the PagedTable identifier
* @return the field values of the first selected objects
*/
public static List<String> deSelectId(String deSelectId, String tableId) {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
ServletContext servletContext = ctx.getServletContext();
PagedTable pt = SessionMethods.getResultsTable(session, tableId);
pt.deSelectId(new Integer(deSelectId));
Map<String, List<FieldDescriptor>> classKeys = getClassKeys(servletContext);
ObjectStore os = (ObjectStore) servletContext.getAttribute(Constants.OBJECTSTORE);
return pt.getFirstSelectedFields(os, classKeys);
}
/**
*
* @param servletContext
* @return
*/
@SuppressWarnings("unchecked")
private static Map<String, List<FieldDescriptor>> getClassKeys(ServletContext servletContext) {
return (Map) servletContext.getAttribute(Constants.CLASS_KEYS);
}
/**
* Select all the elements in a PagedTable
* @param index the index of the selected column
* @param tableId the PagedTable identifier
*/
public static void selectAll(int index, String tableId) {
HttpSession session = WebContextFactory.get().getSession();
PagedTable pt = SessionMethods.getResultsTable(session, tableId);
pt.clearSelectIds();
pt.setAllSelectedColumn(index);
}
public String[] getContent(String suffix, boolean wholeList, String field, String className) {
ServletContext servletContext = WebContextFactory.get().getServletContext();
AutoCompleter ac = (AutoCompleter) servletContext.getAttribute(Constants.AUTO_COMPLETER);
ac.createRAMIndex(className + "." + field);
if (!wholeList && suffix.length() > 0) {
String[] shortList = ac.getFastList(suffix, field, 31);
return shortList;
} else if (suffix.length() > 2 && wholeList) {
String[] longList = ac.getList(suffix, field);
return longList;
}
String[] defaultList = {""};
return defaultList;
}
/**
* AJAX request - reorder view.
*/
public void reorder(String newOrder, String oldOrder) {
HttpSession session = WebContextFactory.get().getSession();
List<String> newOrderList = new LinkedList<String>(StringUtil
.serializedSortOrderToMap(newOrder).values());
List<String> oldOrderList = new LinkedList<String>(StringUtil
.serializedSortOrderToMap(oldOrder).values());
List view = SessionMethods.getEditingView(session);
ArrayList newView = new ArrayList();
for (int i = 0; i < view.size(); i++) {
String newi = newOrderList.get(i);
int oldi = oldOrderList.indexOf(newi);
newView.add(view.get(oldi));
}
view.clear();
view.addAll(newView);
}
/**
* @return
* @throws MalformedURLException
* @throws FeedException
*/
public static String getNewsRead(String rssURI) {
try {
URL feedUrl = new URL(rssURI);
SyndFeedInput input = new SyndFeedInput();
XmlReader reader;
try {
reader = new XmlReader(feedUrl);
} catch (Throwable e) {
// xml document at this url doesn't exist or is invalid, so the news cannot be read
return "<i>No news</i>";
}
SyndFeed feed = input.build(reader);
List<SyndEntry> entries = feed.getEntries();
StringBuffer html = new StringBuffer("<ol id=\"news\">");
int counter = 0;
for (SyndEntry syndEntry : entries) {
if (counter > 4) {
break;
}
// NB: apparently, the only accepted formats for getPublishedDate are
// Fri, 28 Jan 2008 11:02 GMT
// Fri, 8 Jan 2008 11:02 GMT
// Fri, 8 Jan 08 11:02 GMT
// an annoying error appears if the format is not followed, and news tile hangs.
// the following is used to display the date without timestamp.
// this should always work since the retrieved date has a fixed format,
// independent of the one used in the xml.
String longDate = syndEntry.getPublishedDate().toString();
String dayMonth = longDate.substring(0, 10);
String year = longDate.substring(24);
html.append("<li>");
html.append("<strong>" + syndEntry.getTitle() + "</strong>");
html.append(" - <em>" + dayMonth + " " + year + "</em><br/>");
// html.append("- <em>" + syndEntry.getPublishedDate().toString() + "</em><br/>");
html.append(syndEntry.getDescription().getValue());
html.append("</li>");
counter++;
}
html.append("</ol>");
return html.toString();
} catch (MalformedURLException e) {
return "<i>No news at specified URL</i>";
} catch (IllegalArgumentException e) {
return "<i>No news at specified URL</i>";
} catch (FeedException e) {
return "<i>No news at specified URL</i>";
}
}
/**
* Returns all objects names tagged with specified tag type and tag name.
* @param type tag type
* @param tag tag name
* @return objects names
*/
public static Set<String> filterByTag(String type, String tag) {
Profile profile = getProfile();
// implementation of hierarchical tag structure
// if user selects tag 'bio' than it automatically includes all tags with bio prefix like
// 'bio:experiment1', 'bio:experiment2'
List<String> tags = getAllPrefixTags(type, tag);
SearchRepository searchRepository = profile.getSearchRepository();
Map<String, WebSearchable> map = (Map<String, WebSearchable>) searchRepository.getWebSearchableMap(type);
if (map == null) {
return null;
}
Map<String, WebSearchable> filteredMap = new TreeMap<String, WebSearchable>();
for (String currentTag : tags) {
List<String> tagList = new ArrayList<String>();
tagList.add(currentTag);
filteredMap.putAll(profile.getProfileManager().filterByTags(map, tagList, type, profile.getUsername()));
}
return filteredMap.keySet();
}
/** Returns all tags of specified type and starting at specified prefix.
* @param type type
* @param prefix prefix
* @return tags
*/
private static List<String> getAllPrefixTags(String type, String prefix) {
List<String> tags = getDatabaseTags(type);
List<String> ret = new ArrayList<String>();
for (String tag : tags) {
if (tag.startsWith(prefix)) {
ret.add(tag);
}
}
return ret;
}
private static List<String> getDatabaseTags(String type) {
return getDatabaseTags(null, null, type);
}
private static List<String> getDatabaseTags(String tagName, String objectIdentifier, String type) {
HttpServletRequest request = getRequest();
ProfileManager pm = getProfileManager(request);
Profile profile = getProfile(request);
List<String> ret = new ArrayList<String>();
if (profile != null && pm != null) {
List<Tag> tags = pm.getTags(tagName, objectIdentifier, type, profile.getUsername());
tags = ProfileManager.filterOutReservedTags(tags);
for (Tag tag : tags) {
ret.add(tag.getTagName());
}
}
return ret;
}
private static ProfileManager getProfileManager(HttpServletRequest request) {
ProfileManager pm = (ProfileManager) request.getSession()
.getServletContext().getAttribute(Constants.PROFILE_MANAGER);
return pm;
}
public static boolean addTag(String tag, String taggedObject, String type) {
try {
HttpServletRequest request = getRequest();
ProfileManager pm = getProfileManager(request);
Profile profile = getProfile(request);
String tagName = tag.trim();
if (profile.getUsername() != null
&& !StringUtils.isEmpty(tagName)
&& !StringUtils.isEmpty(type)
&& !StringUtils.isEmpty(taggedObject)) {
Tag createdTag = pm.addTag(tagName, taggedObject, type, profile.getUsername());
HttpSession session = request.getSession();
ServletContext servletContext = session.getServletContext();
Boolean isSuperUser = (Boolean) session.getAttribute(Constants.IS_SUPERUSER);
if (isSuperUser != null && isSuperUser.booleanValue()) {
SearchRepository tr = SearchRepository.getGlobalSearchRepository(servletContext);
tr.webSearchableTagged(createdTag);
}
}
return true;
} catch (Throwable e) {
LOG.error("Adding tag failed", e);
return false;
}
}
public static boolean deleteTag(String tagId) {
try {
HttpServletRequest request = getRequest();
ProfileManager pm = getProfileManager(request);
Profile profile = getProfile(request);
if (!StringUtils.isEmpty(tagId)) {
Tag tag = pm.getTagById(Integer.parseInt(tagId));
// only let users delete their own tags
if (tag.getUserProfile().getUsername().equals(profile.getUsername())) {
pm.deleteTag(tag);
HttpSession session = request.getSession();
ServletContext servletContext = session.getServletContext();
Boolean isSuperUser = (Boolean) session.getAttribute(Constants.IS_SUPERUSER);
if (isSuperUser != null && isSuperUser.booleanValue()) {
SearchRepository tr =
SearchRepository.getGlobalSearchRepository(servletContext);
tr.webSearchableUnTagged(tag);
}
}
}
return true;
} catch (Throwable e) {
LOG.error("Deleting tag failed", e);
return false;
}
}
private static Profile getProfile(HttpServletRequest request) {
return (Profile) request.getSession().getAttribute(Constants.PROFILE);
}
private static Profile getProfile() {
return (Profile) getRequest().getSession().getAttribute(Constants.PROFILE);
}
private static HttpServletRequest getRequest() {
return WebContextFactory.get().getHttpServletRequest();
}
/**
* Returns all tags of specified tag type together with prefixes of these tags.
* For instance: for tag 'bio:experiment' it automatically adds 'bio' tag.
* @param tag type
* @return tags
*/
public static Set<String> getTags(String type) {
List<String> tags = getDatabaseTags(type);
Set<String> ret = new LinkedHashSet<String>();
for (String tag : tags) {
if (tag.contains(TagNames.SEPARATOR)) {
ret.addAll(getPrefixes(tag));
} else {
ret.add(tag);
}
}
return ret;
}
private static List<String> getPrefixes(String s) {
List<String> ret = new ArrayList<String>();
String[] parts = s.split(TagNames.SEPARATOR);
String prefix = "";
for (int i = 0; i < parts.length; i++) {
String part = parts[i];
prefix += part;
ret.add(prefix);
if (i != (parts.length - 1)) {
prefix += TagNames.SEPARATOR;
}
}
return ret;
}
}
|
package sample.javafx.property;
import javafx.beans.property.SimpleDoubleProperty;
public class Main {
public static void main(String[] args) {
SimpleDoubleProperty a = new SimpleDoubleProperty();
SimpleDoubleProperty b = new SimpleDoubleProperty();
System.out.println(b.get());
a.set(1.0);
b.bind(a);
System.out.println(b.get());
a.set(2.0);
System.out.println(b.get());
}
}
|
public static void main(String[] args) throws Exception {
{
class InsecureTrustManager implements X509TrustManager {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
// BAD: Does not verify the certificate chain, allowing any certificate.
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
}
SSLContext context = SSLContext.getInstance("TLS");
TrustManager[] trustManager = new TrustManager[] { new InsecureTrustManager() };
context.init(null, trustManager, null);
}
{
SSLContext context = SSLContext.getInstance("TLS");
File certificateFile = new File("path/to/self-signed-certificate");
// Create a `KeyStore` with default type
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
// `keyStore` is initially empty
keyStore.load(null, null);
X509Certificate generatedCertificate;
try (InputStream cert = new FileInputStream(certificateFile)) {
generatedCertificate = (X509Certificate) CertificateFactory.getInstance("X509")
.generateCertificate(cert);
}
// Add the self-signed certificate to the key store
keyStore.setCertificateEntry(certificateFile.getName(), generatedCertificate);
// Get default `TrustManagerFactory`
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
// Use it with our key store that trusts our self-signed certificate
tmf.init(keyStore);
TrustManager[] trustManagers = tmf.getTrustManagers();
context.init(null, trustManagers, null); // GOOD, we are not using a custom `TrustManager` but instead have
// added the self-signed certificate we want to trust to the key
// store. Note, the `trustManagers` will **only** trust this one
// certificate.
URL url = new URL("https://self-signed.badssl.com/");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(context.getSocketFactory());
}
}
|
package org.javatari.atari.network;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.javatari.atari.cartridge.Cartridge;
import org.javatari.atari.console.Console;
import org.javatari.atari.console.savestate.ConsoleState;
import org.javatari.atari.console.savestate.SaveStateMedia;
import org.javatari.atari.controls.ConsoleControlsSocket;
import org.javatari.atari.controls.ConsoleControls.Control;
import org.javatari.general.board.ClockDriven;
public final class ClientConsole extends Console implements ClockDriven {
public ClientConsole(RemoteReceiver receiver) {
super();
setupReceiver(receiver);
}
public RemoteReceiver remoteReceiver() {
return remoteReceiver;
}
@Override
public synchronized void go() {
// Clock is controlled remotely, but signal unpause to unblock clock pulses
isPaused = false;
}
@Override
public synchronized void pause() {
// Clock is controlled remotely, but signal pause to block clock pulses
isPaused = true;
}
@Override
public void extendedPowerOff() {
try {
remoteReceiver.disconnect();
} catch (IOException e) {
// Ignore
}
super.extendedPowerOff();
}
@Override
protected void mainClockCreate() {
// Ignore, the clock is controlled remotely
}
@Override
protected void mainClockAdjustToNormal() {
// Ignore, the clock is controlled remotely
}
@Override
protected void mainClockAdjustToFast() {
// Ignore, the clock is controlled remotely
}
@Override
protected void mainClockDestroy() {
// Ignore, the clock is controlled remotely
}
@Override
protected void socketsCreate() {
controlsSocket = new ClientConsoleControlsSocketAdapter();
controlsSocket.addForwardedInput(new ConsoleControlsInputAdapter());
controlsSocket.addForwardedInput(tia);
controlsSocket.addForwardedInput(pia);
cartridgeSocket = new ClientConsoleCartridgeSocketAdapter();
saveStateSocket = new ClientConsoleSaveStateSocketAdapter();
}
@Override
public void clockPulse() {
// Block clock pulses until Console is unpaused (go) is turned off
// Important while Screen is dettached in Applet mode,
// so no indeterministic behavior is introduced while the Screen is off!
while(isPaused && powerOn) try {
Thread.sleep(1000/120); // Half a frame
} catch (InterruptedException e) {}
synchronized(this) {
tia.clockPulse();
}
}
@Override
protected void cycleCartridgeFormat() {
// Ignore, the new Cartridge state will come from the Server
}
@Override
protected void powerFry() {
// Ignore, the new RAM state will come from the Server
}
void connected() {
showOSD("Connected to Player 1 Server", true);
}
void disconnected(){
powerOff();
showOSD("Disconnected from Player 1 Server", true);
}
void receiveServerUpdate(ServerUpdate update) {
if (update.powerChange != null)
receiveServerPower(update.powerChange);
if (update.consoleState != null)
receiveServerState(update.consoleState );
if (update.controlChanges != null)
((ClientConsoleControlsSocketAdapter) controlsSocket).serverControlChanges(update.controlChanges);
if (powerOn)
clockPulse();
}
List<ControlChange> controlChangesToSend() {
return ((ClientConsoleControlsSocketAdapter) controlsSocket).getChangesToSend();
}
private void receiveServerPower(boolean serverPowerOn) {
if (serverPowerOn && !powerOn) powerOn();
else if (!serverPowerOn && powerOn) powerOff();
}
private void receiveServerState(ConsoleState state) {
loadState(state);
}
private void setupReceiver(RemoteReceiver receiver) {
remoteReceiver = receiver;
remoteReceiver.clientConsole(this);
}
private RemoteReceiver remoteReceiver;
private boolean isPaused = false; // To control the pause/go mechanism
private class ClientConsoleControlsSocketAdapter extends ConsoleControlsSocket {
@Override
public void controlStateChanged(Control control, boolean state) {
if (DISABLED_CONTROLS.contains(control)) {
showOSD("Only the Server can change Cartridge Formats", true);
return;
}
synchronized (queuedChanges) {
queuedChanges.add(new ControlChange(control, state));
}
}
@Override
public void controlStateChanged(Control control, int position) {
synchronized (queuedChanges) {
queuedChanges.add(new ControlChangeForPaddle(control, position));
}
}
public List<ControlChange> getChangesToSend() {
List<ControlChange> changesToSend;
synchronized (queuedChanges) {
if (queuedChanges.isEmpty())
return null;
else {
changesToSend = new ArrayList<ControlChange>(queuedChanges);
queuedChanges.clear();
return changesToSend;
}
}
}
public void serverControlChanges(List<ControlChange> changes) {
// Effectively accepts the control changes, received from the server
for (ControlChange change : changes)
if (change instanceof ControlChangeForPaddle)
super.controlStateChanged(change.control, ((ControlChangeForPaddle)change).position);
else
super.controlStateChanged(change.control, change.state);
}
private List<ControlChange> queuedChanges = new ArrayList<ControlChange>();
}
// Cartridge insertion is controlled only by the Server
private class ClientConsoleCartridgeSocketAdapter extends CartridgeSocketAdapter {
@Override
public void insert(Cartridge cartridge, boolean autoPower) {
showOSD("Only the Server can change Cartridges", true);
}
}
private class ClientConsoleSaveStateSocketAdapter extends SaveStateSocketAdapter {
@Override
public void connectMedia(SaveStateMedia media) {
// Ignore, savestates are controlled by the Server
}
@Override
public void connectCartridge(Cartridge cartridge) {
// No socket, savestates are controlled by the Server
cartridge.connectSaveStateSocket(null);
}
}
private static List<Control> DISABLED_CONTROLS = Arrays.asList(new Control[] {
Control.CARTRIDGE_FORMAT
});
}
|
package nl.sense_os.service;
import nl.sense_os.service.commonsense.SenseApi;
import nl.sense_os.service.constants.SensePrefs;
import nl.sense_os.service.constants.SensePrefs.Auth;
import nl.sense_os.service.constants.SensePrefs.Main.Advanced;
import nl.sense_os.service.constants.SensePrefs.Main.Motion;
import nl.sense_os.service.constants.SensePrefs.Status;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Binder;
import android.os.RemoteException;
import android.util.Log;
/**
* Implementation of the service's AIDL interface. Very closely linked with {@link SenseService}.
*
* @author Steven Mulder <steven@sense-os.nl>
*/
public class SenseServiceStub extends Binder {
private static final String TAG = "SenseServiceStub";
private SenseService service;
public SenseServiceStub(SenseService service) {
super();
this.service = service;
}
public SenseService getSenseService() {
return service;
}
public void changeLogin(final String username, final String password,
final ISenseServiceCallback callback) {
// Log.v(TAG, "Change login");
// perform login on separate thread and respond via callback
new Thread() {
@Override
public void run() {
int result = service.changeLogin(username, password);
try {
callback.onChangeLoginResult(result);
} catch (RemoteException e) {
Log.e(TAG, "Failed to call back to bound activity after login change: " + e);
}
}
}.start();
}
public boolean getPrefBool(String key, boolean defValue) {
// Log.v(TAG, "Get preference: " + key);
SharedPreferences prefs;
if (key.equals(Status.AMBIENCE) || key.equals(Status.DEV_PROX)
|| key.equals(Status.EXTERNAL) || key.equals(Status.LOCATION)
|| key.equals(Status.MAIN) || key.equals(Status.MOTION)
|| key.equals(Status.PHONESTATE) || key.equals(Status.AUTOSTART)) {
prefs = service.getSharedPreferences(SensePrefs.STATUS_PREFS, Context.MODE_PRIVATE);
} else {
prefs = service.getSharedPreferences(SensePrefs.MAIN_PREFS, Context.MODE_PRIVATE);
}
// return the preference value
try {
return prefs.getBoolean(key, defValue);
} catch (ClassCastException e) {
return defValue;
}
}
public float getPrefFloat(String key, float defValue) {
// Log.v(TAG, "Get preference: " + key);
SharedPreferences prefs = service.getSharedPreferences(SensePrefs.MAIN_PREFS,
Context.MODE_PRIVATE);
try {
return prefs.getFloat(key, defValue);
} catch (ClassCastException e) {
return defValue;
}
}
public int getPrefInt(String key, int defValue) {
// Log.v(TAG, "Get preference: " + key);
SharedPreferences prefs = service.getSharedPreferences(SensePrefs.MAIN_PREFS,
Context.MODE_PRIVATE);
try {
return prefs.getInt(key, defValue);
} catch (ClassCastException e) {
return defValue;
}
}
public long getPrefLong(String key, long defValue) {
// Log.v(TAG, "Get preference: " + key);
SharedPreferences prefs;
if (key.equals(Auth.SENSOR_LIST_COMPLETE_TIME)) {
prefs = service.getSharedPreferences(SensePrefs.AUTH_PREFS, Context.MODE_PRIVATE);
} else {
prefs = service.getSharedPreferences(SensePrefs.MAIN_PREFS, Context.MODE_PRIVATE);
}
try {
return prefs.getLong(key, defValue);
} catch (ClassCastException e) {
return defValue;
}
}
public String getPrefString(String key, String defValue) {
// Log.v(TAG, "Get preference: " + key);
SharedPreferences prefs;
if (key.equals(Auth.LOGIN_COOKIE) || key.equals(Auth.LOGIN_PASS) || key.equals(Auth.LOGIN_SESSION_ID)
|| key.equals(Auth.LOGIN_USERNAME) || key.equals(Auth.SENSOR_LIST_COMPLETE)
|| key.equals(Auth.DEVICE_ID) || key.equals(Auth.PHONE_IMEI)
|| key.equals(Auth.PHONE_TYPE)) {
prefs = service.getSharedPreferences(SensePrefs.AUTH_PREFS, Context.MODE_PRIVATE);
} else {
// all other preferences
prefs = service.getSharedPreferences(SensePrefs.MAIN_PREFS, Context.MODE_PRIVATE);
}
// return the preference value
try {
String value = prefs.getString(key, defValue);
if ((key.equals(Auth.LOGIN_USERNAME) || key.equals(Auth.LOGIN_PASS)
|| key.equals(Auth.LOGIN_COOKIE) || key.equals(Auth.LOGIN_SESSION_ID))
&& value != defValue) {
boolean encrypt_credential = service.getSharedPreferences(SensePrefs.MAIN_PREFS, Context.MODE_PRIVATE)
.getBoolean(Advanced.ENCRYPT_CREDENTIAL, false);
if (encrypt_credential) {
EncryptionHelper decryptor = new EncryptionHelper(service);
try {
value = decryptor.decrypt(value);
} catch (EncryptionHelper.EncryptionHelperException e) {
Log.w(TAG, "Error decrypting" + key + ". Assume data is not encrypted");
}
}
}
return value;
} catch (ClassCastException e) {
return defValue;
}
}
public String getCookie() throws IllegalAccessException {
return SenseApi.getCookie(service);
}
public String getSessionId() throws IllegalAccessException {
return SenseApi.getSessionId(service);
}
public void getStatus(ISenseServiceCallback callback) throws RemoteException {
callback.statusReport(ServiceStateHelper.getInstance(service).getStatusCode());
}
public void logout() {
service.logout();
}
public void register(final String username, final String password, final String email,
final String address, final String zipCode, final String country, final String name,
final String surname, final String mobile, final ISenseServiceCallback callback) {
// Log.v(TAG, "Register: '" + username + "'");
// perform registration on separate thread and respond via callback
new Thread() {
@Override
public void run() {
int result = service.register(username, password, email, address, zipCode, country,
name, surname, mobile);
try {
callback.onRegisterResult(result);
} catch (RemoteException e) {
Log.e(TAG, "Failed to call back to bound activity after registration: " + e);
}
}
}.start();
}
public void setPrefBool(String key, final boolean value) {
Log.v(TAG, "Set preference: '" + key + "': '" + value + "'");
SharedPreferences prefs;
if (key.equals(Status.AMBIENCE) || key.equals(Status.DEV_PROX)
|| key.equals(Status.EXTERNAL) || key.equals(Status.LOCATION)
|| key.equals(Status.MAIN) || key.equals(Status.MOTION)
|| key.equals(Status.PHONESTATE) || key.equals(Status.AUTOSTART)) {
prefs = service.getSharedPreferences(SensePrefs.STATUS_PREFS, Context.MODE_PRIVATE);
} else {
prefs = service.getSharedPreferences(SensePrefs.MAIN_PREFS, Context.MODE_PRIVATE);
}
// compare with original preference value
boolean oldValue = prefs.getBoolean(key, !value);
if (value == oldValue) {
// value unchanged
return;
}
// store value
boolean stored = prefs.edit().putBoolean(key, value).commit();
if (stored == false) {
Log.w(TAG, "Preference '" + key + "' not stored!");
} else if (key.equals(Advanced.DEV_MODE)
&& ServiceStateHelper.getInstance(service).isLoggedIn()) {
logout();
// reset GCM id
SharedPreferences authPrefs = service.getSharedPreferences(SensePrefs.AUTH_PREFS,
Context.MODE_PRIVATE);
authPrefs.edit().putString(Auth.GCM_REGISTRATION_ID, "").commit();
} else if (key.equals(Advanced.USE_COMMONSENSE)) {
// login on a separate thread
new Thread() {
@Override
public void run() {
if (value) {
Log.w(TAG, "USE_COMMONSENSE setting changed: try to log in");
service.login();
} else {
Log.w(TAG, "USE_COMMONSENSE setting changed: logging out");
service.logout();
}
}
}.start();
} else if (key.equals(Motion.ACCELEROMETER) || key.equals(Motion.LINEAR_ACCELERATION)
|| key.equals(Motion.GYROSCOPE) || key.equals(Motion.ORIENTATION)
|| key.equals(Motion.MOTION_ENERGY) || key.equals(Motion.BURSTMODE)
|| key.equals(Motion.FALL_DETECT) || key.equals(Motion.FALL_DETECT_DEMO)) {
ServiceStateHelper ssh = ServiceStateHelper.getInstance(service);
if (ssh.isMotionActive()) {
// restart motion
service.toggleMotion(false);
service.toggleMotion(true);
}
}
}
public void setPrefFloat(String key, float value) {
// Log.v(TAG, "Set preference: " + key + ": \'" + value + "\'");
SharedPreferences prefs = service.getSharedPreferences(SensePrefs.MAIN_PREFS,
Context.MODE_PRIVATE);
// store value
boolean stored = prefs.edit().putFloat(key, value).commit();
if (stored == false) {
Log.w(TAG, "Preference " + key + " not stored!");
}
}
public void setPrefInt(String key, int value) {
// Log.v(TAG, "Set preference: " + key + ": \'" + value + "\'");
SharedPreferences prefs = service.getSharedPreferences(SensePrefs.MAIN_PREFS,
Context.MODE_PRIVATE);
// store value
boolean stored = prefs.edit().putInt(key, value).commit();
if (stored == false) {
Log.w(TAG, "Preference " + key + " not stored!");
}
}
public void setPrefLong(String key, long value) {
// Log.v(TAG, "Set preference: " + key + ": \'" + value + "\'");
SharedPreferences prefs;
if (key.equals(Auth.SENSOR_LIST_COMPLETE_TIME)) {
prefs = service.getSharedPreferences(SensePrefs.AUTH_PREFS, Context.MODE_PRIVATE);
} else {
prefs = service.getSharedPreferences(SensePrefs.MAIN_PREFS, Context.MODE_PRIVATE);
}
// store value
boolean stored = prefs.edit().putLong(key, value).commit();
if (stored == false) {
Log.w(TAG, "Preference " + key + " not stored!");
}
}
public void setPrefString(String key, String value) {
Log.v(TAG, "Set preference: " + key + ": \'" + value + "\'");
SharedPreferences prefs;
if (key.equals(Auth.LOGIN_COOKIE) || key.equals(Auth.LOGIN_PASS) || key.equals(Auth.LOGIN_SESSION_ID)
|| key.equals(Auth.LOGIN_USERNAME) || key.equals(Auth.SENSOR_LIST_COMPLETE)
|| key.equals(Auth.DEVICE_ID) || key.equals(Auth.PHONE_IMEI)
|| key.equals(Auth.PHONE_TYPE)) {
prefs = service.getSharedPreferences(SensePrefs.AUTH_PREFS, Context.MODE_PRIVATE);
} else {
// all other preferences
prefs = service.getSharedPreferences(SensePrefs.MAIN_PREFS, Context.MODE_PRIVATE);
}
boolean encrypt_credential = false;
if (key.equals(Auth.LOGIN_USERNAME) || key.equals(Auth.LOGIN_PASS)
|| key.equals(Auth.LOGIN_COOKIE) || key.equals(Auth.LOGIN_SESSION_ID)) {
encrypt_credential = service.getSharedPreferences(SensePrefs.MAIN_PREFS, Context.MODE_PRIVATE)
.getBoolean(Advanced.ENCRYPT_CREDENTIAL, false);
}
// store value
String oldValue = prefs.getString(key, null);
if (encrypt_credential && oldValue != null) {
EncryptionHelper decryptor = new EncryptionHelper(service);
try {
oldValue = decryptor.decrypt(oldValue);
} catch (EncryptionHelper.EncryptionHelperException e) {
Log.w(TAG, "Error decrypting " + key + ". Assume data is not encrypted");
}
}
if (value == null || value != oldValue) {
if (encrypt_credential && value != null) {
EncryptionHelper encryptor = new EncryptionHelper(service);
value = encryptor.encrypt(value);
}
boolean stored = prefs.edit().putString(key, value).commit();
if (stored == false) {
Log.w(TAG, "Preference " + key + " not stored!");
}
// special check for sync and sample rate changes
if (key.equals(SensePrefs.Main.SAMPLE_RATE)) {
service.onSampleRateChange();
} else if (key.equals(SensePrefs.Main.SYNC_RATE)) {
service.onSyncRateChange();
}
}
}
public void toggleAmbience(boolean active) {
// Log.v(TAG, "Toggle ambience: " + active);
SharedPreferences prefs = service.getSharedPreferences(SensePrefs.STATUS_PREFS,
Context.MODE_PRIVATE);
prefs.edit().putBoolean(Status.AMBIENCE, active).commit();
service.toggleAmbience(active);
}
public void toggleDeviceProx(boolean active) {
// Log.v(TAG, "Toggle neighboring devices: " + active);
SharedPreferences prefs = service.getSharedPreferences(SensePrefs.STATUS_PREFS,
Context.MODE_PRIVATE);
prefs.edit().putBoolean(Status.DEV_PROX, active).commit();
service.toggleDeviceProx(active);
}
public void toggleExternalSensors(boolean active) {
// Log.v(TAG, "Toggle external sensors: " + active);
SharedPreferences prefs = service.getSharedPreferences(SensePrefs.STATUS_PREFS,
Context.MODE_PRIVATE);
prefs.edit().putBoolean(Status.EXTERNAL, active).commit();
service.toggleExternalSensors(active);
}
public void toggleLocation(boolean active) {
// Log.v(TAG, "Toggle location: " + active);
SharedPreferences prefs = service.getSharedPreferences(SensePrefs.STATUS_PREFS,
Context.MODE_PRIVATE);
prefs.edit().putBoolean(Status.LOCATION, active).commit();
service.toggleLocation(active);
}
public void toggleMain(boolean active) {
// Log.v(TAG, "Toggle main: " + active);
SharedPreferences prefs = service.getSharedPreferences(SensePrefs.STATUS_PREFS,
Context.MODE_PRIVATE);
prefs.edit().putBoolean(Status.MAIN, active).commit();
service.toggleMain(active);
}
public void toggleMotion(boolean active) {
// Log.v(TAG, "Toggle motion: " + active);
SharedPreferences prefs = service.getSharedPreferences(SensePrefs.STATUS_PREFS,
Context.MODE_PRIVATE);
prefs.edit().putBoolean(Status.MOTION, active).commit();
service.toggleMotion(active);
}
public void togglePhoneState(boolean active) {
// Log.v(TAG, "Toggle phone state: " + active);
SharedPreferences prefs = service.getSharedPreferences(SensePrefs.STATUS_PREFS,
Context.MODE_PRIVATE);
prefs.edit().putBoolean(Status.PHONESTATE, active).commit();
service.togglePhoneState(active);
}
public void togglePopQuiz(boolean active) {
Log.w(TAG, "Toggle questionnaire ignored: this functionality is no longer supported!");
}
}
|
package com.cloud.network.lb;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.ejb.Local;
import javax.naming.ConfigurationException;
import org.apache.log4j.Logger;
import com.cloud.agent.AgentManager;
import com.cloud.agent.AgentManager.OnError;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.StopAnswer;
import com.cloud.agent.api.check.CheckSshAnswer;
import com.cloud.agent.api.check.CheckSshCommand;
import com.cloud.agent.api.routing.LoadBalancerConfigCommand;
import com.cloud.agent.api.routing.NetworkElementCommand;
import com.cloud.agent.api.to.LoadBalancerTO;
import com.cloud.agent.manager.Commands;
import com.cloud.api.commands.CreateLoadBalancerRuleCmd;
import com.cloud.configuration.Config;
import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.dc.DataCenter;
import com.cloud.dc.DataCenter.NetworkType;
import com.cloud.dc.DataCenterVO;
import com.cloud.dc.Pod;
import com.cloud.dc.PodVlanMapVO;
import com.cloud.dc.Vlan.VlanType;
import com.cloud.dc.dao.ClusterDao;
import com.cloud.dc.dao.DataCenterDao;
import com.cloud.dc.dao.HostPodDao;
import com.cloud.dc.dao.PodVlanMapDao;
import com.cloud.dc.dao.VlanDao;
import com.cloud.deploy.DataCenterDeployment;
import com.cloud.deploy.DeployDestination;
import com.cloud.exception.AgentUnavailableException;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientAddressCapacityException;
import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.NetworkRuleConflictException;
import com.cloud.exception.OperationTimedoutException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.exception.StorageUnavailableException;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.network.ElasticLbVmMapVO;
import com.cloud.network.IPAddressVO;
import com.cloud.network.LoadBalancerVO;
import com.cloud.network.Network;
import com.cloud.network.Network.GuestIpType;
import com.cloud.network.NetworkManager;
import com.cloud.network.NetworkVO;
import com.cloud.network.Networks.TrafficType;
import com.cloud.network.addr.PublicIp;
import com.cloud.network.dao.IPAddressDao;
import com.cloud.network.dao.LoadBalancerDao;
import com.cloud.network.dao.NetworkDao;
import com.cloud.network.lb.LoadBalancingRule.LbDestination;
import com.cloud.network.lb.dao.ElasticLbVmMapDao;
import com.cloud.network.router.VirtualNetworkApplianceManager;
import com.cloud.network.router.VirtualRouter;
import com.cloud.network.router.VirtualRouter.RedundantState;
import com.cloud.network.router.VirtualRouter.Role;
import com.cloud.network.rules.FirewallRule;
import com.cloud.network.rules.FirewallRule.Purpose;
import com.cloud.network.rules.LoadBalancer;
import com.cloud.offering.NetworkOffering;
import com.cloud.offerings.NetworkOfferingVO;
import com.cloud.offerings.dao.NetworkOfferingDao;
import com.cloud.service.ServiceOfferingVO;
import com.cloud.service.dao.ServiceOfferingDao;
import com.cloud.storage.VMTemplateVO;
import com.cloud.storage.dao.VMTemplateDao;
import com.cloud.user.Account;
import com.cloud.user.AccountService;
import com.cloud.user.User;
import com.cloud.user.UserContext;
import com.cloud.user.dao.AccountDao;
import com.cloud.utils.NumbersUtil;
import com.cloud.utils.Pair;
import com.cloud.utils.component.Inject;
import com.cloud.utils.component.Manager;
import com.cloud.utils.concurrency.NamedThreadFactory;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.vm.DomainRouterVO;
import com.cloud.vm.NicProfile;
import com.cloud.vm.ReservationContext;
import com.cloud.vm.VMInstanceVO;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VirtualMachineGuru;
import com.cloud.vm.VirtualMachine.State;
import com.cloud.vm.VirtualMachineGuru;
import com.cloud.vm.VirtualMachineManager;
import com.cloud.vm.VirtualMachineName;
import com.cloud.vm.VirtualMachineProfile;
import com.cloud.vm.VirtualMachineProfile.Param;
import com.cloud.vm.dao.DomainRouterDao;
@Local(value = { ElasticLoadBalancerManager.class })
public class ElasticLoadBalancerManagerImpl implements
ElasticLoadBalancerManager, Manager, VirtualMachineGuru<DomainRouterVO> {
private static final Logger s_logger = Logger
.getLogger(ElasticLoadBalancerManagerImpl.class);
@Inject
IPAddressDao _ipAddressDao;
@Inject
AgentManager _agentMgr;
@Inject
NetworkManager _networkMgr;
@Inject
LoadBalancerDao _loadBalancerDao = null;
@Inject
LoadBalancingRulesManager _lbMgr;
@Inject
VirtualNetworkApplianceManager _routerMgr;
@Inject
DomainRouterDao _routerDao = null;
@Inject
protected HostPodDao _podDao = null;
@Inject
protected ClusterDao _clusterDao;
@Inject
DataCenterDao _dcDao = null;
@Inject
protected NetworkDao _networkDao;
@Inject
protected NetworkOfferingDao _networkOfferingDao;
@Inject
VMTemplateDao _templateDao = null;
@Inject
VirtualMachineManager _itMgr;
@Inject
ConfigurationDao _configDao;
@Inject
ServiceOfferingDao _serviceOfferingDao = null;
@Inject
AccountService _accountService;
@Inject
LoadBalancerDao _lbDao;
@Inject
VlanDao _vlanDao;
@Inject
PodVlanMapDao _podVlanMapDao;
@Inject
ElasticLbVmMapDao _elbVmMapDao;
@Inject
NetworkDao _networksDao;
@Inject
AccountDao _accountDao;
String _name;
String _instance;
static final private String _elbVmNamePrefix = "l";
static final private String _systemVmType = "elbvm";
boolean _enabled;
TrafficType _frontendTrafficType = TrafficType.Guest;
Account _systemAcct;
ServiceOfferingVO _elasticLbVmOffering;
ScheduledExecutorService _gcThreadPool;
String _mgmtCidr;
String _mgmtHost;
Set<Long> _gcCandidateElbVmIds = Collections.newSetFromMap(new ConcurrentHashMap<Long,Boolean>());
int _elasticLbVmRamSize;
int _elasticLbvmCpuMHz;
int _elasticLbvmNumCpu;
private Long getPodIdForDirectIp(IPAddressVO ipAddr) {
List<PodVlanMapVO> podVlanMaps = _podVlanMapDao.listPodVlanMapsByVlan(ipAddr.getVlanId());
if (podVlanMaps.isEmpty()) {
return null;
} else {
return podVlanMaps.get(0).getPodId();
}
}
public DomainRouterVO deployLoadBalancerVM(Long networkId, IPAddressVO ipAddr, Long accountId) {
NetworkVO network = _networkDao.findById(networkId);
DataCenter dc = _dcDao.findById(network.getDataCenterId());
Long podId = getPodIdForDirectIp(ipAddr);
Pod pod = podId == null?null:_podDao.findById(podId);
Map<VirtualMachineProfile.Param, Object> params = new HashMap<VirtualMachineProfile.Param, Object>(
1);
params.put(VirtualMachineProfile.Param.RestartNetwork, true);
Account owner = _accountService.getActiveAccount("system", new Long(1));
DeployDestination dest = new DeployDestination(dc, pod, null, null);
s_logger.debug("About to deploy ELB vm ");
try {
DomainRouterVO elbVm = deployELBVm(network, dest, owner, params);
if (elbVm == null) {
throw new InvalidParameterValueException("Could not deploy or find existing ELB VM");
}
s_logger.debug("Deployed ELB vm = " + elbVm);
return elbVm;
} catch (Throwable t) {
s_logger.warn("Error while deploying ELB VM: ", t);
return null;
}
}
private boolean sendCommandsToRouter(final DomainRouterVO elbVm,
Commands cmds) throws AgentUnavailableException {
Answer[] answers = null;
try {
answers = _agentMgr.send(elbVm.getHostId(), cmds);
} catch (OperationTimedoutException e) {
s_logger.warn("ELB: Timed Out", e);
throw new AgentUnavailableException(
"Unable to send commands to virtual elbVm ",
elbVm.getHostId(), e);
}
if (answers == null) {
return false;
}
if (answers.length != cmds.size()) {
return false;
}
// FIXME: Have to return state for individual command in the future
if (answers.length > 0) {
Answer ans = answers[0];
return ans.getResult();
}
return true;
}
private void createApplyLoadBalancingRulesCommands(
List<LoadBalancingRule> rules, DomainRouterVO elbVm, Commands cmds) {
LoadBalancerTO[] lbs = new LoadBalancerTO[rules.size()];
int i = 0;
for (LoadBalancingRule rule : rules) {
boolean revoked = (rule.getState()
.equals(FirewallRule.State.Revoke));
String protocol = rule.getProtocol();
String algorithm = rule.getAlgorithm();
String elbIp = _networkMgr.getIp(rule.getSourceIpAddressId()).getAddress()
.addr();
int srcPort = rule.getSourcePortStart();
List<LbDestination> destinations = rule.getDestinations();
LoadBalancerTO lb = new LoadBalancerTO(elbIp, srcPort, protocol, algorithm, revoked, false, destinations);
lbs[i++] = lb;
}
LoadBalancerConfigCommand cmd = new LoadBalancerConfigCommand(lbs);
cmd.setAccessDetail(NetworkElementCommand.ROUTER_IP,
elbVm.getPrivateIpAddress());
cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME,
elbVm.getInstanceName());
//FIXME: why are we setting attributes directly? Ick!! There should be accessors and
//the constructor should set defaults.
cmd.lbStatsVisibility = _configDao.getValue(Config.NetworkLBHaproxyStatsVisbility.key());
cmd.lbStatsUri = _configDao.getValue(Config.NetworkLBHaproxyStatsUri.key());
cmd.lbStatsAuth = _configDao.getValue(Config.NetworkLBHaproxyStatsAuth.key());
cmd.lbStatsPort = _configDao.getValue(Config.NetworkLBHaproxyStatsPort.key());
cmd.lbStatsIp = elbVm.getGuestIpAddress();
cmds.addCommand(cmd);
}
protected boolean applyLBRules(DomainRouterVO elbVm,
List<LoadBalancingRule> rules) throws ResourceUnavailableException {
Commands cmds = new Commands(OnError.Continue);
createApplyLoadBalancingRulesCommands(rules, elbVm, cmds);
// Send commands to elbVm
return sendCommandsToRouter(elbVm, cmds);
}
protected DomainRouterVO findElbVmForLb(FirewallRule lb) {//TODO: use a table to lookup
ElasticLbVmMapVO map = _elbVmMapDao.findOneByIp(lb.getSourceIpAddressId());
if (map == null) {
return null;
}
DomainRouterVO elbVm = _routerDao.findById(map.getElbVmId());
return elbVm;
}
public boolean applyLoadBalancerRules(Network network,
List<? extends FirewallRule> rules)
throws ResourceUnavailableException {
if (rules == null || rules.isEmpty()) {
return true;
}
if (rules.get(0).getPurpose() != Purpose.LoadBalancing) {
s_logger.warn("ELB: Not handling non-LB firewall rules");
return false;
}
DomainRouterVO elbVm = findElbVmForLb(rules.get(0));
if (elbVm == null) {
s_logger.warn("Unable to apply lb rules, ELB vm doesn't exist in the network "
+ network.getId());
throw new ResourceUnavailableException("Unable to apply lb rules",
DataCenter.class, network.getDataCenterId());
}
if (elbVm.getState() == State.Running) {
//resend all rules for the public ip
List<LoadBalancerVO> lbs = _lbDao.listByIpAddress(rules.get(0).getSourceIpAddressId());
List<LoadBalancingRule> lbRules = new ArrayList<LoadBalancingRule>();
for (LoadBalancerVO lb : lbs) {
List<LbDestination> dstList = _lbMgr.getExistingDestinations(lb.getId());
LoadBalancingRule loadBalancing = new LoadBalancingRule(
lb, dstList);
lbRules.add(loadBalancing);
}
return applyLBRules(elbVm, lbRules);
} else if (elbVm.getState() == State.Stopped
|| elbVm.getState() == State.Stopping) {
s_logger.debug("ELB VM is in "
+ elbVm.getState()
+ ", so not sending apply LoadBalancing rules commands to the backend");
return true;
} else {
s_logger.warn("Unable to apply loadbalancing rules, ELB VM is not in the right state "
+ elbVm.getState());
throw new ResourceUnavailableException(
"Unable to apply loadbalancing rules, ELB VM is not in the right state",
VirtualRouter.class, elbVm.getId());
}
}
@Override
public boolean configure(String name, Map<String, Object> params)
throws ConfigurationException {
_name = name;
final Map<String, String> configs = _configDao.getConfiguration("AgentManager", params);
_systemAcct = _accountService.getSystemAccount();
_instance = configs.get("instance.name");
if (_instance == null) {
_instance = "VM";
}
_mgmtCidr = _configDao.getValue(Config.ManagementNetwork.key());
_mgmtHost = _configDao.getValue(Config.ManagementHostIPAdr.key());
boolean useLocalStorage = Boolean.parseBoolean(configs.get(Config.SystemVMUseLocalStorage.key()));
_elasticLbVmRamSize = NumbersUtil.parseInt(configs.get(Config.ElasticLoadBalancerVmMemory.key()), DEFAULT_ELB_VM_RAMSIZE);
_elasticLbvmCpuMHz = NumbersUtil.parseInt(configs.get(Config.ElasticLoadBalancerVmCpuMhz.key()), DEFAULT_ELB_VM_CPU_MHZ);
_elasticLbvmNumCpu = NumbersUtil.parseInt(configs.get(Config.ElasticLoadBalancerVmNumVcpu.key()), 1);
_elasticLbVmOffering = new ServiceOfferingVO("System Offering For Elastic LB VM", _elasticLbvmNumCpu,
_elasticLbVmRamSize, _elasticLbvmCpuMHz, 0, 0, true, null, useLocalStorage,
true, null, true, VirtualMachine.Type.ElasticLoadBalancerVm, true);
_elasticLbVmOffering.setUniqueName("Cloud.Com-ElasticLBVm");
_elasticLbVmOffering = _serviceOfferingDao.persistSystemServiceOffering(_elasticLbVmOffering);
String enabled = _configDao.getValue(Config.ElasticLoadBalancerEnabled.key());
_enabled = (enabled == null) ? false: Boolean.parseBoolean(enabled);
s_logger.info("Elastic Load balancer enabled: " + _enabled);
if (_enabled) {
String traffType = _configDao.getValue(Config.ElasticLoadBalancerNetwork.key());
if ("guest".equalsIgnoreCase(traffType)) {
_frontendTrafficType = TrafficType.Guest;
} else if ("public".equalsIgnoreCase(traffType)){
_frontendTrafficType = TrafficType.Public;
} else
throw new ConfigurationException("ELB: Traffic type for front end of load balancer has to be guest or public; found : " + traffType);
s_logger.info("ELB: Elastic Load Balancer: will balance on " + traffType );
int gcIntervalMinutes = NumbersUtil.parseInt(configs.get(Config.ElasticLoadBalancerVmGcInterval.key()), 5);
if (gcIntervalMinutes < 5)
gcIntervalMinutes = 5;
s_logger.info("ELB: Elastic Load Balancer: scheduling GC to run every " + gcIntervalMinutes + " minutes" );
_gcThreadPool = Executors.newScheduledThreadPool(1, new NamedThreadFactory("ELBVM-GC"));
_gcThreadPool.scheduleAtFixedRate(new CleanupThread(), gcIntervalMinutes, gcIntervalMinutes, TimeUnit.MINUTES);
_itMgr.registerGuru(VirtualMachine.Type.ElasticLoadBalancerVm, this);
}
return true;
}
@Override
public boolean start() {
return true;
}
@Override
public boolean stop() {
return true;
}
@Override
public String getName() {
return _name;
}
private DomainRouterVO findELBVmWithCapacity(Network guestNetwork, IPAddressVO ipAddr) {
List<DomainRouterVO> unusedElbVms = _elbVmMapDao.listUnusedElbVms();
if (unusedElbVms.size() > 0) {
List<DomainRouterVO> candidateVms = new ArrayList<DomainRouterVO>();
for (DomainRouterVO candidateVm: unusedElbVms) {
if (candidateVm.getPodIdToDeployIn() == getPodIdForDirectIp(ipAddr))
candidateVms.add(candidateVm);
}
return candidateVms.size()==0?null:candidateVms.get(new Random().nextInt(candidateVms.size()));
}
return null;
}
public DomainRouterVO deployELBVm(Network guestNetwork, DeployDestination dest, Account owner, Map<Param, Object> params) throws
ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException {
long dcId = dest.getDataCenter().getId();
// lock guest network
Long guestNetworkId = guestNetwork.getId();
guestNetwork = _networkDao.acquireInLockTable(guestNetworkId);
if (guestNetwork == null) {
throw new ConcurrentOperationException("Unable to acquire network lock: " + guestNetworkId);
}
try {
NetworkOffering offering = _networkOfferingDao.findByIdIncludingRemoved(guestNetwork.getNetworkOfferingId());
if (offering.isSystemOnly() || guestNetwork.getIsShared()) {
owner = _accountService.getSystemAccount();
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Starting a ELB vm for network configurations: " + guestNetwork + " in " + dest);
}
assert guestNetwork.getState() == Network.State.Implemented
|| guestNetwork.getState() == Network.State.Setup
|| guestNetwork.getState() == Network.State.Implementing
: "Network is not yet fully implemented: "+ guestNetwork;
DataCenterDeployment plan = null;
DomainRouterVO elbVm = null;
plan = new DataCenterDeployment(dcId, dest.getPod().getId(), null, null, null);
if (elbVm == null) {
long id = _routerDao.getNextInSequence(Long.class, "id");
if (s_logger.isDebugEnabled()) {
s_logger.debug("Creating the ELB vm " + id);
}
List<NetworkOfferingVO> offerings = _networkMgr.getSystemAccountNetworkOfferings(NetworkOfferingVO.SystemControlNetwork);
NetworkOfferingVO controlOffering = offerings.get(0);
NetworkVO controlConfig = _networkMgr.setupNetwork(_systemAcct, controlOffering, plan, null, null, false, false).get(0);
List<Pair<NetworkVO, NicProfile>> networks = new ArrayList<Pair<NetworkVO, NicProfile>>(2);
NicProfile guestNic = new NicProfile();
guestNic.setDefaultNic(true);
networks.add(new Pair<NetworkVO, NicProfile>((NetworkVO) guestNetwork, guestNic));
networks.add(new Pair<NetworkVO, NicProfile>(controlConfig, null));
VMTemplateVO template = _templateDao.findSystemVMTemplate(dcId);
elbVm = new DomainRouterVO(id, _elasticLbVmOffering.getId(), VirtualMachineName.getSystemVmName(id, _instance, _elbVmNamePrefix), template.getId(), template.getHypervisorType(), template.getGuestOSId(),
owner.getDomainId(), owner.getId(), guestNetwork.getId(), false, 0, RedundantState.UNKNOWN, _elasticLbVmOffering.getOfferHA(), VirtualMachine.Type.ElasticLoadBalancerVm);
elbVm.setRole(Role.LB);
elbVm = _itMgr.allocate(elbVm, template, _elasticLbVmOffering, networks, plan, null, owner);
//TODO: create usage stats
}
State state = elbVm.getState();
if (state != State.Running) {
elbVm = this.start(elbVm, _accountService.getSystemUser(), _accountService.getSystemAccount(), params);
}
return elbVm;
} finally {
_networkDao.releaseFromLockTable(guestNetworkId);
}
}
private DomainRouterVO start(DomainRouterVO elbVm, User user, Account caller, Map<Param, Object> params) throws StorageUnavailableException, InsufficientCapacityException,
ConcurrentOperationException, ResourceUnavailableException {
s_logger.debug("Starting ELB VM " + elbVm);
if (_itMgr.start(elbVm, params, user, caller) != null) {
return _routerDao.findById(elbVm.getId());
} else {
return null;
}
}
private DomainRouterVO stop(DomainRouterVO elbVm, boolean forced, User user, Account caller) throws ConcurrentOperationException, ResourceUnavailableException {
s_logger.debug("Stopping ELB vm " + elbVm);
try {
if (_itMgr.advanceStop( elbVm, forced, user, caller)) {
return _routerDao.findById(elbVm.getId());
} else {
return null;
}
} catch (OperationTimedoutException e) {
throw new CloudRuntimeException("Unable to stop " + elbVm, e);
}
}
protected List<LoadBalancerVO> findExistingLoadBalancers(String lbName, Long ipId, Long accountId, Long domainId, Integer publicPort) {
SearchBuilder<LoadBalancerVO> sb = _lbDao.createSearchBuilder();
sb.and("name", sb.entity().getName(), SearchCriteria.Op.EQ);
sb.and("accountId", sb.entity().getAccountId(), SearchCriteria.Op.EQ);
sb.and("publicPort", sb.entity().getSourcePortStart(), SearchCriteria.Op.EQ);
if (ipId != null) {
sb.and("sourceIpAddress", sb.entity().getSourceIpAddressId(), SearchCriteria.Op.EQ);
}
if (domainId != null) {
sb.and("domainId", sb.entity().getDomainId(), SearchCriteria.Op.EQ);
}
if (publicPort != null) {
sb.and("publicPort", sb.entity().getSourcePortStart(), SearchCriteria.Op.EQ);
}
SearchCriteria<LoadBalancerVO> sc = sb.create();
sc.setParameters("name", lbName);
sc.setParameters("accountId", accountId);
if (ipId != null) {
sc.setParameters("sourceIpAddress", ipId);
}
if (domainId != null) {
sc.setParameters("domainId",domainId);
}
if (publicPort != null) {
sc.setParameters("publicPort", publicPort);
}
List<LoadBalancerVO> lbs = _lbDao.search(sc, null);
return lbs == null || lbs.size()==0 ? null: lbs;
}
@DB
public PublicIp allocIp(CreateLoadBalancerRuleCmd lb, Account account) throws InsufficientAddressCapacityException {
//TODO: this only works in the guest network. Handle the public network case also.
List<NetworkOfferingVO> offerings = _networkOfferingDao.listByTrafficTypeAndGuestType(true, _frontendTrafficType, GuestIpType.Direct);
if (offerings == null || offerings.size() == 0) {
s_logger.warn("ELB: Could not find system offering for direct networks of type " + _frontendTrafficType);
return null;
}
NetworkOffering frontEndOffering = offerings.get(0);
List<NetworkVO> networks = _networksDao.listBy(Account.ACCOUNT_ID_SYSTEM, frontEndOffering.getId(), lb.getZoneId());
if (networks == null || networks.size() == 0) {
s_logger.warn("ELB: Could not find network of offering type " + frontEndOffering + " in zone " + lb.getZoneId());
return null;
}
Network frontEndNetwork = networks.get(0);
Transaction txn = Transaction.currentTxn();
txn.start();
PublicIp ip = _networkMgr.assignPublicIpAddress(lb.getZoneId(), null, account, VlanType.DirectAttached, frontEndNetwork.getId(), null);
IPAddressVO ipvo = _ipAddressDao.findById(ip.getId());
ipvo.setAssociatedWithNetworkId(frontEndNetwork.getId());
_ipAddressDao.update(ipvo.getId(), ipvo);
txn.commit();
s_logger.info("Acquired frontend IP for ELB " + ip);
return ip;
}
public void releaseIp(long ipId, long userId, Account caller) {
s_logger.info("ELB: Release public IP for loadbalancing " + ipId);
IPAddressVO ipvo = _ipAddressDao.findById(ipId);
ipvo.setAssociatedWithNetworkId(null);
_ipAddressDao.update(ipvo.getId(), ipvo);
_networkMgr.releasePublicIpAddress(ipId, userId, caller);
_ipAddressDao.unassignIpAddress(ipId);
}
protected NetworkVO getNetworkToDeployLb(Long ipId) {
IPAddressVO ipAddr = _ipAddressDao.findById(ipId);
Long networkId= ipAddr.getSourceNetworkId();
NetworkVO network=_networkDao.findById(networkId);
if (network.getGuestType() != GuestIpType.Direct) {
s_logger.info("ELB: not handling guest traffic of type " + network.getGuestType());
return null;
}
return network;
}
@Override
@DB
public LoadBalancer handleCreateLoadBalancerRule( CreateLoadBalancerRuleCmd lb, Account account) throws InsufficientAddressCapacityException, NetworkRuleConflictException {
Long ipId = lb.getSourceIpAddressId();
if (ipId != null && getNetworkToDeployLb(ipId) == null) {
return null;
}
boolean newIp = false;
account = _accountDao.acquireInLockTable(account.getId());
if (account == null) {
s_logger.warn("ELB: CreateLoadBalancer: Failed to acquire lock on account");
throw new CloudRuntimeException("Failed to acquire lock on account");
}
try {
List<LoadBalancerVO> existingLbs = findExistingLoadBalancers(lb.getName(), lb.getSourceIpAddressId(), lb.getAccountId(), lb.getDomainId(), lb.getSourcePortStart());
if (existingLbs == null ){
existingLbs = findExistingLoadBalancers(lb.getName(), lb.getSourceIpAddressId(), lb.getAccountId(), lb.getDomainId(), null);
if (existingLbs == null) {
if (lb.getSourceIpAddressId() != null) {
existingLbs = findExistingLoadBalancers(lb.getName(), null, lb.getAccountId(), lb.getDomainId(), null);
if (existingLbs != null) {
throw new InvalidParameterValueException("Supplied LB name " + lb.getName() + " is not associated with IP " + lb.getSourceIpAddressId() );
}
} else {
s_logger.debug("Could not find any existing frontend ips for this account for this LB rule, acquiring a new frontent IP for ELB");
PublicIp ip = allocIp(lb, account);
ipId = ip.getId();
newIp = true;
}
} else {
ipId = existingLbs.get(0).getSourceIpAddressId();
s_logger.debug("ELB: Found existing frontend ip for this account for this LB rule " + ipId);
}
} else {
s_logger.warn("ELB: Found existing load balancers matching requested new LB");
throw new NetworkRuleConflictException("ELB: Found existing load balancers matching requested new LB");
}
NetworkVO network = getNetworkToDeployLb(ipId);
IPAddressVO ipAddr = _ipAddressDao.findById(ipId);
long networkId = network.getId();
LoadBalancer result = null;
try {
lb.setSourceIpAddressId(ipId);
result = _lbMgr.createLoadBalancer(lb, false);
} catch (NetworkRuleConflictException e) {
s_logger.warn("Failed to create LB rule, not continuing with ELB deployment");
if (newIp) {
releaseIp(ipId, UserContext.current().getCallerUserId(), account);
}
throw e;
}
DomainRouterVO elbVm = null;
if (existingLbs == null) {
elbVm = findELBVmWithCapacity(network, ipAddr);
if (elbVm == null) {
elbVm = deployLoadBalancerVM(networkId, ipAddr, account.getId());
if (elbVm == null) {
s_logger.warn("Failed to deploy a new ELB vm for ip " + ipAddr + " in network " + network + "lb name=" + lb.getName());
if (newIp)
releaseIp(ipId, UserContext.current().getCallerUserId(), account);
}
}
} else {
ElasticLbVmMapVO elbVmMap = _elbVmMapDao.findOneByIp(ipId);
if (elbVmMap != null) {
elbVm = _routerDao.findById(elbVmMap.getElbVmId());
}
}
if (elbVm == null) {
s_logger.warn("No ELB VM can be found or deployed");
s_logger.warn("Deleting LB since we failed to deploy ELB VM");
_lbDao.remove(result.getId());
return null;
}
ElasticLbVmMapVO mapping = new ElasticLbVmMapVO(ipId, elbVm.getId(), result.getId());
_elbVmMapDao.persist(mapping);
return result;
} finally {
if (account != null) {
_accountDao.releaseFromLockTable(account.getId());
}
}
}
void garbageCollectUnusedElbVms() {
List<DomainRouterVO> unusedElbVms = _elbVmMapDao.listUnusedElbVms();
if (unusedElbVms != null && unusedElbVms.size() > 0)
s_logger.info("Found " + unusedElbVms.size() + " unused ELB vms");
Set<Long> currentGcCandidates = new HashSet<Long>();
for (DomainRouterVO elbVm: unusedElbVms) {
currentGcCandidates.add(elbVm.getId());
}
_gcCandidateElbVmIds.retainAll(currentGcCandidates);
currentGcCandidates.removeAll(_gcCandidateElbVmIds);
User user = _accountService.getSystemUser();
for (Long elbVmId : _gcCandidateElbVmIds) {
DomainRouterVO elbVm = _routerDao.findById(elbVmId);
boolean gceed = false;
try {
s_logger.info("Attempting to stop ELB VM: " + elbVm);
stop(elbVm, true, user, _systemAcct);
gceed = true;
} catch (ConcurrentOperationException e) {
s_logger.warn("Unable to stop unused ELB vm " + elbVm + " due to ", e);
} catch (ResourceUnavailableException e) {
s_logger.warn("Unable to stop unused ELB vm " + elbVm + " due to ", e);
continue;
}
if (gceed) {
try {
s_logger.info("Attempting to destroy ELB VM: " + elbVm);
_itMgr.expunge(elbVm, user, _systemAcct);
} catch (ResourceUnavailableException e) {
s_logger.warn("Unable to destroy unused ELB vm " + elbVm + " due to ", e);
gceed = false;
}
}
if (!gceed) {
currentGcCandidates.add(elbVm.getId());
}
}
_gcCandidateElbVmIds = currentGcCandidates;
}
public class CleanupThread implements Runnable {
@Override
public void run() {
garbageCollectUnusedElbVms();
}
CleanupThread() {
}
}
@Override
public void handleDeleteLoadBalancerRule(LoadBalancer lb, long userId, Account caller) {
if (!_enabled) {
return;
}
List<LoadBalancerVO> remainingLbs = _loadBalancerDao.listByIpAddress(lb.getSourceIpAddressId());
if (remainingLbs.size() == 0) {
s_logger.debug("ELB mgr: releasing ip " + lb.getSourceIpAddressId() + " since no LB rules remain for this ip address");
releaseIp(lb.getSourceIpAddressId(), userId, caller);
}
}
@Override
public DomainRouterVO findByName(String name) {
if (!VirtualMachineName.isValidSystemVmName(name, _instance, _elbVmNamePrefix)) {
return null;
}
return _routerDao.findById(VirtualMachineName.getSystemVmId(name));
}
@Override
public DomainRouterVO findById(long id) {
return _routerDao.findById(id);
}
@Override
public DomainRouterVO persist(DomainRouterVO elbVm) {
return _routerDao.persist(elbVm);
}
@Override
public boolean finalizeVirtualMachineProfile(VirtualMachineProfile<DomainRouterVO> profile, DeployDestination dest, ReservationContext context) {
DomainRouterVO elbVm = profile.getVirtualMachine();
NetworkVO network = _networkDao.findById(elbVm.getNetworkId());
DataCenter dc = dest.getDataCenter();
StringBuilder buf = profile.getBootArgsBuilder();
buf.append(" template=domP type=" + _systemVmType);
buf.append(" name=").append(profile.getHostName());
NicProfile controlNic = null;
String defaultDns1 = null;
String defaultDns2 = null;
for (NicProfile nic : profile.getNics()) {
int deviceId = nic.getDeviceId();
buf.append(" eth").append(deviceId).append("ip=").append(nic.getIp4Address());
buf.append(" eth").append(deviceId).append("mask=").append(nic.getNetmask());
if (nic.isDefaultNic()) {
buf.append(" gateway=").append(nic.getGateway());
defaultDns1 = nic.getDns1();
defaultDns2 = nic.getDns2();
}
if (nic.getTrafficType() == TrafficType.Management) {
buf.append(" localgw=").append(dest.getPod().getGateway());
} else if (nic.getTrafficType() == TrafficType.Control) {
// control command is sent over management network in VMware
if (dest.getHost().getHypervisorType() == HypervisorType.VMware) {
if (s_logger.isInfoEnabled()) {
s_logger.info("Check if we need to add management server explicit route to ELB vm. pod cidr: " + dest.getPod().getCidrAddress() + "/" + dest.getPod().getCidrSize()
+ ", pod gateway: " + dest.getPod().getGateway() + ", management host: " + _mgmtHost);
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Added management server explicit route to ELB vm.");
}
// always add management explicit route, for basic networking setup
buf.append(" mgmtcidr=").append(_mgmtCidr);
buf.append(" localgw=").append(dest.getPod().getGateway());
if (dc.getNetworkType() == NetworkType.Basic) {
// ask elb vm to setup SSH on guest network
buf.append(" sshonguest=true");
}
}
controlNic = nic;
}
}
String domain = network.getNetworkDomain();
if (domain != null) {
buf.append(" domain=" + domain);
}
buf.append(" dns1=").append(defaultDns1);
if (defaultDns2 != null) {
buf.append(" dns2=").append(defaultDns2);
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Boot Args for " + profile + ": " + buf.toString());
}
if (controlNic == null) {
throw new CloudRuntimeException("Didn't start a control port");
}
return true;
}
@Override
public boolean finalizeDeployment(Commands cmds, VirtualMachineProfile<DomainRouterVO> profile, DeployDestination dest, ReservationContext context) throws ResourceUnavailableException {
DomainRouterVO elbVm = profile.getVirtualMachine();
List<NicProfile> nics = profile.getNics();
for (NicProfile nic : nics) {
if (nic.getTrafficType() == TrafficType.Public) {
elbVm.setPublicIpAddress(nic.getIp4Address());
elbVm.setPublicNetmask(nic.getNetmask());
elbVm.setPublicMacAddress(nic.getMacAddress());
} else if (nic.getTrafficType() == TrafficType.Guest) {
elbVm.setGuestIpAddress(nic.getIp4Address());
} else if (nic.getTrafficType() == TrafficType.Control) {
elbVm.setPrivateIpAddress(nic.getIp4Address());
elbVm.setPrivateMacAddress(nic.getMacAddress());
}
}
_routerDao.update(elbVm.getId(), elbVm);
finalizeCommandsOnStart(cmds, profile);
return true;
}
@Override
public boolean finalizeStart(VirtualMachineProfile<DomainRouterVO> profile, long hostId, Commands cmds, ReservationContext context) {
CheckSshAnswer answer = (CheckSshAnswer) cmds.getAnswer("checkSsh");
if (answer == null || !answer.getResult()) {
s_logger.warn("Unable to ssh to the ELB VM: " + answer.getDetails());
return false;
}
return true;
}
@Override
public boolean finalizeCommandsOnStart(Commands cmds, VirtualMachineProfile<DomainRouterVO> profile) {
DomainRouterVO elbVm = profile.getVirtualMachine();
DataCenterVO dcVo = _dcDao.findById(elbVm.getDataCenterIdToDeployIn());
NicProfile controlNic = null;
if(profile.getHypervisorType() == HypervisorType.VMware && dcVo.getNetworkType() == NetworkType.Basic) {
// TODO this is a ugly to test hypervisor type here
// for basic network mode, we will use the guest NIC for control NIC
for (NicProfile nic : profile.getNics()) {
if (nic.getTrafficType() == TrafficType.Guest && nic.getIp4Address() != null) {
controlNic = nic;
}
}
} else {
for (NicProfile nic : profile.getNics()) {
if (nic.getTrafficType() == TrafficType.Control && nic.getIp4Address() != null) {
controlNic = nic;
}
}
}
if (controlNic == null) {
s_logger.error("Control network doesn't exist for the ELB vm " + elbVm);
return false;
}
cmds.addCommand("checkSsh", new CheckSshCommand(profile.getInstanceName(), controlNic.getIp4Address(), 3922, 5, 20));
// Re-apply load balancing rules
List<LoadBalancerVO> lbs = _elbVmMapDao.listLbsForElbVm(elbVm.getId());
List<LoadBalancingRule> lbRules = new ArrayList<LoadBalancingRule>();
for (LoadBalancerVO lb : lbs) {
List<LbDestination> dstList = _lbMgr.getExistingDestinations(lb.getId());
LoadBalancingRule loadBalancing = new LoadBalancingRule(lb, dstList);
lbRules.add(loadBalancing);
}
s_logger.debug("Found " + lbRules.size() + " load balancing rule(s) to apply as a part of ELB vm " + elbVm + " start.");
if (!lbRules.isEmpty()) {
createApplyLoadBalancingRulesCommands(lbRules, elbVm, cmds);
}
return true;
}
@Override
public void finalizeStop(VirtualMachineProfile<DomainRouterVO> profile, StopAnswer answer) {
if (answer != null) {
VMInstanceVO vm = profile.getVirtualMachine();
DomainRouterVO elbVm = _routerDao.findById(vm.getId());
processStopOrRebootAnswer(elbVm, answer);
}
}
public void processStopOrRebootAnswer(final DomainRouterVO elbVm, Answer answer) {
//TODO: process network usage stats
}
@Override
public void finalizeExpunge(DomainRouterVO vm) {
// no-op
}
@Override
public Long convertToId(String vmName) {
if (!VirtualMachineName.isValidSystemVmName(vmName, _instance, _elbVmNamePrefix)) {
return null;
}
return VirtualMachineName.getSystemVmId(vmName);
}
}
|
package gw2trades.server.frontend;
import gw2trades.repository.api.ItemRepository;
import gw2trades.repository.api.Order;
import gw2trades.repository.api.Query;
import gw2trades.repository.api.model.ListingStatistics;
import gw2trades.repository.api.model.SearchResult;
import gw2trades.server.model.SeoMeta;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Locale;
/**
* @author Stefan Lotties (slotties@gmail.com)
*/
@Controller
public class IndexController {
private ItemRepository itemRepository;
private int pageSize = 30;
@Autowired
public IndexController(ItemRepository itemRepository) {
this.itemRepository = itemRepository;
}
@RequestMapping("/")
public RedirectView root(HttpServletRequest request) {
Locale locale = request.getLocale();
if (isUnknownLocale(locale)) {
locale = Locale.ENGLISH;
}
RedirectView redirectView = new RedirectView("/" + locale.getLanguage() + "/index.html");
redirectView.setStatusCode(HttpStatus.MOVED_PERMANENTLY);
return redirectView;
}
private boolean isUnknownLocale(Locale locale) {
return !(Locale.GERMAN.equals(locale) || Locale.ENGLISH.equals(locale));
}
@RequestMapping("**/index.html")
public ModelAndView index(
@RequestParam(required = false) String orderBy,
@RequestParam(required = false) String orderDir,
@RequestParam(defaultValue = "1") int page,
@RequestParam(required = false) String name) throws IOException {
if (page < 1) {
return new ModelAndView(new RedirectView("/index.html?page=1"));
}
ModelAndView model = new ModelAndView("frame");
Query query = createQuery(name);
Order order = orderBy != null ? Order.by(orderBy, !"asc".equals(orderDir)) : null;
SearchResult<ListingStatistics> results = getStatistics(query, order, page);
int lastPage = (int) Math.ceil((float) results.getTotalResults() / (float) this.pageSize);
model.addObject("seoMeta", new SeoMeta("index.title.default"));
model.addObject("view", "index");
model.addObject("lastPage", lastPage);
model.addObject("currentPage", page);
model.addObject("listingStatistics", results.getResults());
model.addObject("orderBy", orderBy);
model.addObject("orderDir", orderDir);
model.addObject("query", query);
return model;
}
private Query createQuery(String name) {
Query query = null;
if (name != null) {
query = new Query();
query.setName(name);
}
return query;
}
private SearchResult<ListingStatistics> getStatistics(Query query, Order order, int forPage) throws IOException {
// forPage is 1-based, for easier readability in the URL.
int fromPage = (forPage - 1) * this.pageSize;
int toPage = fromPage + this.pageSize;
return this.itemRepository.listStatistics(query, order, fromPage, toPage);
}
}
|
package io.spine.server.storage;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableSet;
import com.google.protobuf.Message;
import io.spine.annotation.Internal;
import io.spine.query.ColumnName;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import static com.google.common.base.Preconditions.checkNotNull;
import static io.spine.util.Exceptions.newIllegalStateException;
/**
* A value of some message record along with the values
* of its {@linkplain io.spine.query.Column columns}.
*
* @param <I>
* the type of the record identifiers
* @param <R>
* the type of the stored records
*/
public class RecordWithColumns<I, R extends Message> {
private final I id;
private final R record;
/**
* A map of column names to the corresponding column values.
*
* @implNote It's impossible to use an {@link com.google.common.collect.ImmutableMap
* ImmutableMap}, as the values may contain {@code null}s.
*/
private final Map<ColumnName, @Nullable Object> storageFields;
protected RecordWithColumns(I identifier, R record, Map<ColumnName, Object> storageFields) {
this.id = checkNotNull(identifier);
this.record = checkNotNull(record);
this.storageFields = new HashMap<>(storageFields);
}
/**
* Creates a new record extracting the column values from the passed {@code Message} and setting
* the passed identifier value as the record identifier.
*/
public static <I, R extends Message>
RecordWithColumns<I, R> create(I identifier, R record, RecordSpec<I, R, R> recordSpec) {
checkNotNull(identifier);
checkNotNull(record);
checkNotNull(recordSpec);
Map<ColumnName, @Nullable Object> storageFields = recordSpec.valuesIn(record);
return of(identifier, record, storageFields);
}
/**
* Creates a new record extracting the column values from the passed {@code Message}.
*/
public static <I, R extends Message>
RecordWithColumns<I, R> create(R record, RecordSpec<I, R, R> recordSpec) {
checkNotNull(record);
checkNotNull(recordSpec);
Map<ColumnName, @Nullable Object> storageFields = recordSpec.valuesIn(record);
I identifier = recordSpec.idValueIn(record);
return of(identifier, record, storageFields);
}
/**
* Wraps a passed record.
*
* <p>Such instance of {@code RecordWithColumns} will contain no storage fields.
*/
@Internal
public static <I, R extends Message> RecordWithColumns<I, R> of(I id, R record) {
return new RecordWithColumns<>(id, record, Collections.emptyMap());
}
/**
* Creates a new instance from the passed record and storage fields.
*/
@VisibleForTesting
public static <I, R extends Message>
RecordWithColumns<I, R> of(I identifier, R record, Map<ColumnName, Object> storageFields) {
return new RecordWithColumns<>(identifier, record, storageFields);
}
/**
* Returns the identifier of the record.
*/
public final I id() {
return id;
}
/**
* Returns the message of the record.
*/
public final R record() {
return record;
}
/**
* Obtains the names of storage fields in the record.
*
* @return the storage field names
*/
public ImmutableSet<ColumnName> columnNames() {
return ImmutableSet.copyOf(storageFields.keySet());
}
public @Nullable Object columnValue(ColumnName columnName) {
return columnValue(columnName, DefaultColumnMapping.INSTANCE);
}
/**
* Obtains the value of the storage field by the specified column name.
*
* <p>The specified column mapping will be used to do the column value conversion.
*/
public <V> V columnValue(ColumnName columnName, ColumnMapping<V> columnMapping) {
checkNotNull(columnName);
checkNotNull(columnMapping);
if (!storageFields.containsKey(columnName)) {
throw newIllegalStateException("Column with the name `%s` was not found.",
columnName);
}
Object columnValue = storageFields.get(columnName);
if (columnValue == null) {
V result = columnMapping.ofNull()
.apply(null);
return result;
}
V result = columnMapping.of(columnValue.getClass())
.applyTo(columnValue);
return result;
}
/**
* Tells if there are any {@linkplain io.spine.query.Column columns}
* associated with this record.
*/
public boolean hasColumns() {
return !storageFields.isEmpty();
}
/**
* Determines if there is a column with the specified name among the storage fields.
*/
public boolean hasColumn(ColumnName name) {
boolean result = storageFields.containsKey(name);
return result;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof RecordWithColumns)) {
return false;
}
RecordWithColumns<?, ?> columns = (RecordWithColumns<?, ?>) o;
return Objects.equals(record, columns.record) &&
Objects.equals(id, columns.id) &&
Objects.equals(storageFields, columns.storageFields);
}
@Override
public int hashCode() {
return Objects.hash(record, id, storageFields);
}
}
|
package org.spine3.server.stand;
import com.google.protobuf.Any;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.ArgumentMatchers;
import org.spine3.testdata.TestStandFactory;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
/**
* @author Alex Tymchenko
* @author Dmytro Dashenkov
*/
public class StandFunnelShould {
/**
* - deliver mock updates to the stand (invoke proper methods with particular arguments) - test the delivery only.
*/
@Test
public void initialize_properly_with_stand_only() {
final Stand stand = TestStandFactory.create();
final StandFunnel.Builder builder = StandFunnel.newBuilder()
.setStand(stand);
final StandFunnel standFunnel = builder.build();
Assert.assertNotNull(standFunnel);
}
@Test
public void initialize_properly_with_various_builder_options() {
final Stand stand = TestStandFactory.create();
final Executor executor = Executors.newSingleThreadExecutor(new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
return Thread.currentThread();
}
});
final StandFunnel blockingFunnel = StandFunnel.newBuilder()
.setStand(stand)
.setExecutor(executor)
.build();
Assert.assertNotNull(blockingFunnel);
final StandFunnel funnelForBusyStand = StandFunnel.newBuilder()
.setStand(stand)
.setExecutor(Executors.newSingleThreadExecutor())
.build();
Assert.assertNotNull(funnelForBusyStand);
final StandFunnel emptyExecutorFunnel = StandFunnel.newBuilder()
.setStand(TestStandFactory.create())
.setExecutor(new Executor() {
@Override
public void execute(Runnable neverCalled) { }
})
.build();
Assert.assertNotNull(emptyExecutorFunnel);
}
@Test
public void deliver_mock_updates_to_stand() {
final Object id = new Object();
final Any state = Any.getDefaultInstance();
final Stand stand = mock(Stand.class);
doNothing().when(stand).update(id, state);
final StandFunnel funnel = StandFunnel.newBuilder()
.setStand(stand)
.build();
funnel.post(id, state);
verify(stand).update(id, state);
}
@Test
public void use_executor_from_builder() {
final Stand stand = spy(TestStandFactory.create());
final Executor executor = spy(new Executor() {
@Override
public void execute(Runnable command) {
}
});
final StandFunnel.Builder builder = StandFunnel.newBuilder()
.setStand(stand)
.setExecutor(executor);
final StandFunnel standFunnel = builder.build();
Assert.assertNotNull(standFunnel);
final Any someState = Any.getDefaultInstance();
final Object someId = new Object();
standFunnel.post(someId, someState);
verify(executor).execute(any(Runnable.class));
}
@SuppressWarnings("ResultOfMethodCallIgnored")
@Test(expected = NullPointerException.class)
public void fail_to_initialize_with_inproper_stand() {
@SuppressWarnings("ConstantConditions")
final StandFunnel.Builder builder = StandFunnel.newBuilder().setStand(null);
builder.build();
}
@SuppressWarnings("ResultOfMethodCallIgnored")
@Test(expected = IllegalStateException.class)
public void fail_to_initialize_from_empty_builder() {
final StandFunnel.Builder builder = StandFunnel.newBuilder();
builder.build();
}
/**
* - Deliver updates from projection repo on update;
* - deliver updates from aggregate repo on update;
* - deliver the updates from several projection and aggregate repositories.
*/
@SuppressWarnings("MethodWithMultipleLoops")
@Test
public void deliver_updates_through_several_threads() throws InterruptedException {
final int threadsCount = 10;
final int threadExecuteionMaxAwaitSeconds = 2;
final Map<String, Object> threadInvakationRegistry = new ConcurrentHashMap<>(threadsCount);
final Stand stand = mock(Stand.class);
doNothing().when(stand).update(ArgumentMatchers.any(), any(Any.class));
final StandFunnel standFunnel = StandFunnel.newBuilder()
.setStand(stand)
.build();
final ExecutorService processes = Executors.newFixedThreadPool(threadsCount);
final Runnable task = new Runnable() {
@Override
public void run() {
final String threadName = Thread.currentThread().getName();
Assert.assertFalse(threadInvakationRegistry.containsKey(threadName));
standFunnel.post(new Object(), Any.getDefaultInstance());
threadInvakationRegistry.put(threadName, new Object());
}
};
for (int i = 0; i < threadsCount; i++) {
processes.execute(task);
}
processes.awaitTermination(threadExecuteionMaxAwaitSeconds, TimeUnit.SECONDS);
Assert.assertEquals(threadInvakationRegistry.size(), threadsCount);
}
}
|
package cz.muni.fi.pa165.service;
import java.util.List;
import javax.inject.Inject;
import org.springframework.stereotype.Service;
import cz.muni.fi.pa165.dao.BookDao;
import cz.muni.fi.pa165.entity.Book;
import cz.muni.fi.pa165.enums.BookState;
import cz.muni.fi.pa165.exceptions.LibraryServiceException;
/**
* Implementation of BookService
*
* @author Michael Simacek
*
*/
@Service
public class BookServiceImpl implements BookService {
@Inject
BookDao bookDao;
@Override
public void create(Book book) {
bookDao.create(book);
}
@Override
public Book findById(Long id) {
return bookDao.findById(id);
}
@Override
public List<Book> findAll() {
return bookDao.findAll();
}
@Override
public void setState(Book book, BookState newState) {
if (book.getState().compareTo(newState) > 0) {
throw new LibraryServiceException("Book cannot be set to less damaged state than it already was");
}
book.setState(newState);
bookDao.update(book);
}
@Override
public void delete(Book book) {
bookDao.delete(book);
}
@Override
public List<Book> findByName(String name) {
return bookDao.findByName(name);
}
}
|
package com.github.letsdrink.intellijplugin;
import com.google.common.base.Function;
import com.google.common.base.Predicates;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.Iterables;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.psi.util.PsiTreeUtil;
import com.jetbrains.php.lang.PhpLanguage;
import com.jetbrains.php.lang.psi.elements.Method;
import com.jetbrains.php.lang.psi.elements.MethodReference;
import com.jetbrains.php.lang.psi.elements.PhpClass;
import javax.annotation.Nullable;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
public class OuzoUtils {
public static final String OUZO_VIEW_RENDER_FQN = "\\Ouzo\\View.render";
public static final String OUZO_ROUTE_RESOURCE_FQN = "\\Ouzo\\Routing\\Route.resource";
public static final String OUZO_ROUTE_GET_FQN = "\\Ouzo\\Routing\\Route.get";
public static final String OUZO_ROUTE_POST_FQN = "\\Ouzo\\Routing\\Route.post";
public static final String OUZO_ROUTE_DELETE_FQN = "\\Ouzo\\Routing\\Route.delete";
public static final String OUZO_ROUTE_PUT_FQN = "\\Ouzo\\Routing\\Route.put";
public static boolean isInViewDir(PsiFile file) {
VirtualFile ouzoProjectRoot = Settings.getInstance(file.getProject()).getOuzoProjectRoot();
String relativePath = VfsUtil.getRelativePath(file.getVirtualFile(), ouzoProjectRoot, '/');
return relativePath != null && relativePath.startsWith("application/view");
}
public static PsiFile getViewPsiFile(Project project, String viewName) {
VirtualFile virtualFile = Settings.getInstance(project).getOuzoProjectRoot().findFileByRelativePath("/application/view/" + viewName + ".phtml");
if (virtualFile == null) {
return null;
}
return PsiManager.getInstance(project).findFile(virtualFile);
}
public static List<PsiFile> getViewPsiFiles(PsiElement psiElement) {
if (psiElement.getLanguage() != PhpLanguage.INSTANCE) {
return Collections.emptyList();
}
Method containingMethod = PsiTreeUtil.getParentOfType(psiElement, Method.class);
if (containingMethod == null) {
return Collections.emptyList();
}
PhpClass controllerClass = containingMethod.getContainingClass();
if (containingMethod == null || !controllerClass.getName().endsWith("Controller")) {
return Collections.emptyList();
}
Collection<MethodReference> methodCalls = PsiTreeUtil.collectElementsOfType(containingMethod, MethodReference.class);
Project project = psiElement.getProject();
FluentIterable<String> viewNames = FluentIterable.from(methodCalls)
.filter(PsiFunctions.isCallTo(OuzoUtils.OUZO_VIEW_RENDER_FQN))
.transform(PsiFunctions.extractFirstArgumentStringContent());
String resource = controllerClass.getName().replaceAll("Controller", "");
return FluentIterable.from(Iterables.concat(viewNames, Arrays.asList(resource + "/" + containingMethod.getName())))
.transform(getViewPsiFileFunction(project))
.filter(Predicates.notNull())
.toList();
}
private static Function<String, PsiFile> getViewPsiFileFunction(final Project project) {
return new Function<String, PsiFile>() {
@Nullable
@Override
public PsiFile apply(@Nullable String viewName) {
return getViewPsiFile(project, viewName);
}
};
}
public static boolean isExpectedFile(PsiElement psiElement, String filename) {
return PsiUtils.getContainingFilename(psiElement).equals(filename);
}
}
|
import java.util.*;
/**
* Loop through the tiles and find out how many of them have matching edges. Then,
* based upon the number of shared edges we do the following:
*
* 0: ERROR!!
* 1: If a tile has only one matching edge, then it's easy to say where it needs
* to be placed.
* 2: Work outwards from the centre.
*/
public class Solver
{
public Solver (boolean debug)
{
_debug = debug;
}
/*
* This time we need to solve the image and return the entire
* thing assembled, i.e., not just the corners.
*/
public Vector<Tile> solve (Vector<Tile> tiles)
{
HashMap<Long, Integer> tileTable = new HashMap<Long, Integer>();
for (int i = 0; i < tiles.size(); i++)
{
Tile t = tiles.elementAt(i);
tileTable.put(t.getID(), i);
}
System.out.println("**GOT "+tileTable);
HashSet<Tile> visited = new HashSet<Tile>();
LinkedList<Tile> queue = new LinkedList<Tile>();
queue.add(tiles.get(0));
while (!queue.isEmpty())
{
Tile current = queue.poll();
visited.add(current);
for (int j = 0; j < tiles.size(); j++)
{
Tile t = tiles.elementAt(j);
if (!visited.contains(t) && !current.equals(t))
{
if (connects(current, t))
queue.add(t);
}
}
}
System.out.println("**NOW have "+visited);
return null;
}
private boolean connects (Tile theTile, Tile toCheck)
{
if (_debug)
System.out.println("Checking "+toCheck.getID()+" against "+theTile.getID());
for (int i = 0; i < 4; i++)
{
if (theTile.connectBottomToTop(toCheck) || theTile.connectTopToBottom(toCheck) ||
theTile.connectLeftToRight(toCheck) || theTile.connectRightToLeft(toCheck))
{
return true;
}
if (!toCheck.isFrozen())
toCheck.rotate();
}
if (!toCheck.isFrozen())
toCheck.invert();
for (int i = 0; i < 4; i++)
{
if (theTile.connectBottomToTop(toCheck) || theTile.connectTopToBottom(toCheck) ||
theTile.connectLeftToRight(toCheck) || theTile.connectRightToLeft(toCheck))
{
return true;
}
if (!toCheck.isFrozen())
toCheck.rotate();
}
return false;
}
private boolean _debug;
}
|
package com.slooce.smpp;
import static com.slooce.smpp.SlooceSMPPUtil.sanitizeCharacters;
import org.jsmpp.DefaultPDUReader;
import org.jsmpp.DefaultPDUSender;
import org.jsmpp.InvalidResponseException;
import org.jsmpp.PDUException;
import org.jsmpp.SynchronizedPDUSender;
import org.jsmpp.bean.AlertNotification;
import org.jsmpp.bean.Alphabet;
import org.jsmpp.bean.BindType;
import org.jsmpp.bean.DataCodings;
import org.jsmpp.bean.DataSm;
import org.jsmpp.bean.DeliverSm;
import org.jsmpp.bean.DeliveryReceipt;
import org.jsmpp.bean.ESMClass;
import org.jsmpp.bean.GSMSpecificFeature;
import org.jsmpp.bean.MessageType;
import org.jsmpp.bean.NumberingPlanIndicator;
import org.jsmpp.bean.OptionalParameter;
import org.jsmpp.bean.OptionalParameters;
import org.jsmpp.bean.RegisteredDelivery;
import org.jsmpp.bean.SMSCDeliveryReceipt;
import org.jsmpp.bean.TypeOfNumber;
import org.jsmpp.extra.NegativeResponseException;
import org.jsmpp.extra.ProcessRequestException;
import org.jsmpp.extra.ResponseTimeoutException;
import org.jsmpp.extra.SessionState;
import org.jsmpp.session.BindParameter;
import org.jsmpp.session.DataSmResult;
import org.jsmpp.session.MessageReceiverListener;
import org.jsmpp.session.SMPPSession;
import org.jsmpp.session.Session;
import org.jsmpp.session.SessionStateListener;
import org.jsmpp.util.DefaultComposer;
import org.jsmpp.util.InvalidDeliveryReceiptException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.jsmpp.util.HexUtil.conventBytesToHexString;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
/**
* An SMPP Session with more familiar methods to connect, send MT messages, and to receive MO messages ({@link SlooceSMPPReceiver})).
*/
public class SlooceSMPPSession {
private static final Logger logger = LoggerFactory.getLogger(SlooceSMPPSession.class);
private SlooceSMPPProvider provider;
private String serviceId;
private String serviceType;
private boolean useSSL;
private String host;
private int port;
private String systemId;
private String password;
private String systemType;
private boolean stripSystemType;
private SlooceSMPPReceiver receiver;
private SMPPSession smppSession = null;
private boolean connected = false;
public SlooceSMPPSession() {
this.provider = SlooceSMPPProvider.OPEN_MARKET;
this.serviceId = null;
this.serviceType = SlooceSMPPConstants.SERVICE_TYPE_CELLULAR_MESSAGING;
this.useSSL = false;
this.host = null;
this.port = 0;
this.systemId = null;
this.password = null;
this.systemType = null;
this.stripSystemType = false;
this.receiver = null;
}
public SlooceSMPPSession(final SlooceSMPPProvider provider,
final String serviceId, final String serviceType,
final boolean useSSL, final String host, final int port,
final String systemId, final String password,
final String systemType, final boolean stripSystemType,
final SlooceSMPPReceiver receiver) {
this.provider = provider;
this.serviceId = serviceId;
this.serviceType = serviceType;
this.useSSL = useSSL;
this.host = host;
this.port = port;
this.systemId = systemId;
this.password = password;
this.systemType = systemType;
this.stripSystemType = stripSystemType;
this.receiver = receiver;
}
public void reconfigure(final SlooceSMPPProvider provider,
final String serviceId, final String serviceType,
final boolean useSSL, final String host, final int port,
final String systemId, final String password,
final String systemType, final boolean stripSystemType,
final SlooceSMPPReceiver receiver) {
this.provider = provider;
this.serviceId = serviceId;
this.serviceType = serviceType;
this.useSSL = useSSL;
this.host = host;
this.port = port;
this.systemId = systemId;
this.password = password;
this.systemType = systemType;
this.stripSystemType = stripSystemType;
this.receiver = receiver;
}
public boolean isConnected() {
return connected;
}
public void close() {
connected = false;
if (smppSession != null) {
smppSession.close();
smppSession = null;
}
}
public void connect(final int attempts, final int retryInterval) throws IOException {
int attempt = 0;
while (!connected && attempt < attempts) {
try {
++attempt;
logger.info("SlooceSMPPSession.connect - Connect attempt #{}... {}", attempt, this);
connect();
} catch (Exception e) {
logger.error("SlooceSMPPSession.connect - Failed to connect - " + this, e);
// wait before retrying
try { Thread.sleep(retryInterval * attempt); } catch (Exception ignored) {
// ignore exceptions
}
}
}
if (!connected) {
logger.error("SlooceSMPPSession.connect - Failed to initialize after {} attempts - {}", attempt, this);
}
}
private void connect()
throws IOException {
if (connected) {
return;
}
final SlooceSMPPSession smpp = this;
smppSession = new SMPPSession(
new SynchronizedPDUSender(new DefaultPDUSender(new DefaultComposer())),
new DefaultPDUReader(),
new SlooceSMPPSocketConnectionFactory(useSSL));
smppSession.setEnquireLinkTimer(provider.getEnquireLinkTimer()); // Depends on the provider's inactivity timeout (actually, this is the SMPP Socket Read Timeout before enquiring to keep the link alive)
smppSession.setTransactionTimer(provider.getTransactionTimer()); // Depends on the provider's response timeout (responses should be returned within a second)
smppSession.setMessageReceiverListener(new MessageReceiverListener() {
@Override
public void onAcceptDeliverSm(final DeliverSm deliverSm) throws ProcessRequestException {
final Alphabet alphabet = smpp.provider.getAlphabet(deliverSm, logger);
if (MessageType.SMSC_DEL_RECEIPT.containedIn(deliverSm.getEsmClass())) {
// this message is a delivery receipt
try {
final DeliveryReceipt delReceipt = deliverSm.getShortMessageAsDeliveryReceipt();
String messageId = delReceipt.getId();
if (smpp.provider.isMessageIdDecimal()) {
// Provider sends the messageId in a delivery receipt as a decimal value string per the SMPP spec.
// Convert it to hex to match the messageId hex string returned when submitting the MT.
messageId = Long.toHexString(Long.valueOf(messageId));
}
final String operator = getOptionalParameterValueAsString(OptionalParameters.get(smpp.provider.getOperatorTag(), deliverSm.getOptionalParameters()));
final SlooceSMPPMessage mt = new SlooceSMPPMessage(messageId, deliverSm.getSourceAddr(), operator, deliverSm.getDestAddress());
String message;
if (alphabet == Alphabet.ALPHA_DEFAULT) {
message = SlooceSMPPUtil.fromGSMCharset(delReceipt.getText().getBytes());
} else {
message = delReceipt.getText();
}
mt.setMessage(message);
logger.info("Received delivery receipt - mt:{} dataCoding:{} alphabet:{} esmClass:0x{} {}{} - {}",
mt, deliverSm.getDataCoding(), alphabet, conventBytesToHexString(new byte[]{deliverSm.getEsmClass()}),
sanitizeCharacters(delReceipt.toString()), paramsToString(deliverSm.getOptionalParameters()), smpp.toShortString());
if (smpp.receiver != null) {
smpp.receiver.deliveryReceipt(mt, delReceipt.getFinalStatus(), delReceipt.getError(), smpp);
}
} catch (InvalidDeliveryReceiptException e) {
logger.error("Failed getting delivery receipt - " + smpp.toShortString(), e);
}
} else {
// this message is an incoming MO
final String messageId = getOptionalParameterValueAsString(deliverSm.getOptionalParameter(OptionalParameter.Tag.RECEIPTED_MESSAGE_ID));
final String operator = getOptionalParameterValueAsString(OptionalParameters.get(smpp.provider.getOperatorTag(), deliverSm.getOptionalParameters()));
byte[] messageBytes = deliverSm.getShortMessage();
byte[] udhBytes = new byte[0];
final SlooceSMPPMessage mo = new SlooceSMPPMessage(messageId, deliverSm.getSourceAddr(), operator, deliverSm.getDestAddress());
final boolean hasUDHI = GSMSpecificFeature.UDHI.containedIn(deliverSm.getEsmClass());
if (hasUDHI) {
final int udhLength = messageBytes[0];
udhBytes = new byte[udhLength + 1];
System.arraycopy(messageBytes, 0, udhBytes, 0, udhLength + 1);
byte[] messageBytesCopy = new byte[messageBytes.length - udhLength - 1];
System.arraycopy(messageBytes, udhLength + 1, messageBytesCopy, 0, messageBytes.length - udhLength - 1);
messageBytes = messageBytesCopy;
if (udhBytes[1] == 0x00) { // Concatenated short messages, 8-bit reference number
mo.setCsmsReference(udhBytes[3] & 0xff);
mo.setCsmsTotalParts(udhBytes[4] & 0xff);
mo.setCsmsPartNumber(udhBytes[5] & 0xff);
} else if (udhBytes[1] == 0x08) { // Concatenated short messages, 16-bit reference number
mo.setCsmsReference(((udhBytes[3] & 0xff) << 8) | (udhBytes[4] & 0xff));
mo.setCsmsTotalParts(udhBytes[5] & 0xff);
mo.setCsmsPartNumber(udhBytes[6] & 0xff);
} else { // unsupported
logger.warn("Unsupported udh:{}", conventBytesToHexString(udhBytes));
}
}
String message;
if (alphabet == Alphabet.ALPHA_DEFAULT) {
message = SlooceSMPPUtil.fromGSMCharset(messageBytes);
} else if (alphabet == Alphabet.ALPHA_UCS2) {
try {
message = new String(messageBytes, "UTF-16");
} catch (UnsupportedEncodingException e) {
logger.warn(e.getMessage());
message = new String(messageBytes);
}
} else {
try {
message = new String(messageBytes, "ISO-8859-1");
} catch (UnsupportedEncodingException e) {
logger.warn(e.getMessage());
message = new String(messageBytes);
}
}
if (smpp.stripSystemType && smpp.systemType != null) {
message = Pattern.compile(smpp.systemType + "\\s*", Pattern.CASE_INSENSITIVE).matcher(message).replaceFirst("");
}
mo.setMessage(message);
logger.info("Received message - mo:{} dataCoding:{} alphabet:{} esmClass:0x{} udh:0x{}{} - {}",
mo, deliverSm.getDataCoding(), alphabet, conventBytesToHexString(new byte[]{deliverSm.getEsmClass()}), conventBytesToHexString(udhBytes),
paramsToString(deliverSm.getOptionalParameters()), smpp.toShortString());
if (smpp.receiver != null) {
smpp.receiver.mo(mo, smpp);
}
}
}
private String getOptionalParameterValueAsString(final OptionalParameter optionalParameter) {
if (optionalParameter == null) {
return null;
}
if (optionalParameter instanceof OptionalParameter.OctetString) {
return ((OptionalParameter.OctetString) optionalParameter).getValueAsString();
} else {
throw new RuntimeException("OptionalParameter type is not yet supported: " + optionalParameter.getClass());
}
}
@Override
public void onAcceptAlertNotification(final AlertNotification alertNotification) {
}
@Override
public DataSmResult onAcceptDataSm(final DataSm dataSm, final Session source) throws ProcessRequestException {
return null;
}
});
smppSession.addSessionStateListener(new SessionStateListener() {
@Override
public void onStateChange(final SessionState newState, final SessionState oldState, final Session source) {
if (newState.equals(SessionState.CLOSED)) {
if (smpp.connected) {
logger.warn("Session closed - {}", smpp);
smpp.connected = false;
new Thread() {
@Override
public void run() {
smpp.receiver.onClose(smpp);
}
}.start();
} else {
logger.info("Session was already closed - {}", smpp);
}
}
}
});
smppSession.connectAndBind(host, port, new BindParameter(BindType.BIND_TRX, systemId, password, systemType, TypeOfNumber.UNKNOWN, NumberingPlanIndicator.UNKNOWN, null));
connected = true;
logger.info("Connected to {} using {}@{}:{} - {}", provider, systemId, host, port, smpp);
}
public String mt(final String message, final String subscriber, final String shortOrLongCode, final String operator)
throws InvalidResponseException, PDUException, IOException, NegativeResponseException,
ResponseTimeoutException {
if (provider == SlooceSMPPProvider.MBLOX) {
final List<OptionalParameter> optionalParameters = new ArrayList<OptionalParameter>();
// Mblox requires Operator and Tariff
optionalParameters.add(new OptionalParameter.OctetString(SlooceSMPPConstants.TAG_MBLOX_OPERATOR, operator));
optionalParameters.add(new OptionalParameter.OctetString(SlooceSMPPConstants.TAG_MBLOX_TARIFF, "0"));
// ServiceId is required for TMobile and Verizon
if (SlooceSMPPConstants.OPERATOR_MBLOX_T_MOBILE.equals(operator)
|| SlooceSMPPConstants.OPERATOR_MBLOX_VERIZON.equals(operator)) {
optionalParameters.add(new OptionalParameter.OctetString(SlooceSMPPConstants.TAG_MBLOX_SERVICEID, serviceId));
}
return sendMT(message,
shortOrLongCode.length() < 7 ? TypeOfNumber.NETWORK_SPECIFIC : TypeOfNumber.INTERNATIONAL, shortOrLongCode,
TypeOfNumber.INTERNATIONAL, subscriber,
optionalParameters.toArray(new OptionalParameter[optionalParameters.size()]));
} else {
return sendMT(message,
shortOrLongCode.length() < 7 ? TypeOfNumber.NETWORK_SPECIFIC : TypeOfNumber.INTERNATIONAL, shortOrLongCode,
TypeOfNumber.INTERNATIONAL, subscriber);
}
}
private String sendMT(final String message,
final TypeOfNumber sourceTon, final String source,
final TypeOfNumber destinationTon, final String destination,
OptionalParameter... optionalParameters)
throws InvalidResponseException, PDUException, IOException, NegativeResponseException,
ResponseTimeoutException {
try {
final String messageId = smppSession.submitShortMessage(serviceType, sourceTon, NumberingPlanIndicator.UNKNOWN, source, destinationTon, NumberingPlanIndicator.UNKNOWN, destination,
new ESMClass(), (byte) 0, (byte) 1, null, null, new RegisteredDelivery(SMSCDeliveryReceipt.SUCCESS_FAILURE), (byte) 0, DataCodings.ZERO, (byte) 0, message.getBytes("ISO-8859-1"),
optionalParameters);
logger.info("MT sent - messageId:{} to:{} from:{} text:{}{} - {}", messageId, destination, source, message, paramsToString(optionalParameters), this.toShortString());
return messageId;
} catch (final PDUException e) {
logger.error("Failed to send MT - to:" + destination + " from:" + source + " text:" + message + paramsToString(optionalParameters) + " - " + this.toShortString(), e);
throw e;
} catch (final ResponseTimeoutException e) {
logger.error("Failed to send MT - to:" + destination + " from:" + source + " text:" + message + paramsToString(optionalParameters) + " - " + this.toShortString(), e);
throw e;
} catch (final InvalidResponseException e) {
logger.error("Failed to send MT - to:" + destination + " from:" + source + " text:" + message + paramsToString(optionalParameters) + " - " + this.toShortString(), e);
throw e;
} catch (final NegativeResponseException e) {
logger.error("Failed to send MT - to:" + destination + " from:" + source + " text:" + message + paramsToString(optionalParameters) + " - " + this.toShortString(), e);
throw e;
} catch (final IOException e) {
logger.error("Failed to send MT - to:" + destination + " from:" + source + " text:" + message + paramsToString(optionalParameters) + " - " + this.toShortString(), e);
throw e;
} catch (final Throwable e) {
logger.error("Failed to send MT - to:" + destination + " from:" + source + " text:" + message + paramsToString(optionalParameters) + " - " + this.toShortString(), e);
throw new RuntimeException(e);
}
}
protected static String paramsToString(final OptionalParameter[] optionalParameters) {
final StringBuilder params = new StringBuilder();
try {
if (optionalParameters != null) {
for (final OptionalParameter op : optionalParameters) {
params.append(" tag:0x").append(Integer.toHexString(op.tag));
params.append(" serialized:0x").append(conventBytesToHexString(op.serialize()));
if (op instanceof OptionalParameter.OctetString) {
params.append(" stringValue:").append(sanitizeCharacters(((OptionalParameter.OctetString) op).getValueAsString()));
} else {
params.append(" stringValue:").append(sanitizeCharacters(op.toString()));
}
}
}
} catch (final Throwable t) {
logger.warn("Issue in OptionalParameters paramsToString", t);
}
return params.toString();
}
@Override
public String toString() {
return "SlooceSMPPSession{" +
"connected=" + connected +
", provider=" + provider +
", serviceId='" + serviceId + '\'' +
", serviceType='" + serviceType + '\'' +
", host='" + host + '\'' +
", port=" + port +
", systemId='" + systemId + '\'' +
", systemType='" + systemType + '\'' +
", stripSystemType=" + stripSystemType +
", receiver=" + receiver +
", smppSession=" + smppSession +
'}';
}
public String toShortString() {
return "SlooceSMPPSession{" +
"connected=" + connected +
", host='" + host + '\'' +
", systemId='" + systemId + '\'' +
", smppSession=" + smppSession +
'}';
}
public SlooceSMPPProvider getProvider() {
return provider;
}
public String getServiceId() {
return serviceId;
}
public String getServiceType() {
return serviceType;
}
public String getHost() {
return host;
}
public int getPort() {
return port;
}
public String getSystemId() {
return systemId;
}
public String getPassword() {
return password;
}
public String getSystemType() {
return systemType;
}
public boolean getStripSystemType() {
return stripSystemType;
}
public SMPPSession getSmppSession() {
return smppSession;
}
}
|
package org.jboss.forge.addon.shell;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PreDestroy;
import javax.enterprise.inject.Vetoed;
import org.jboss.aesh.console.Console;
import org.jboss.aesh.console.ConsoleOperation;
import org.jboss.aesh.console.Prompt;
import org.jboss.aesh.console.settings.Settings;
import org.jboss.aesh.terminal.CharacterType;
import org.jboss.aesh.terminal.Color;
import org.jboss.aesh.terminal.TerminalCharacter;
import org.jboss.forge.addon.convert.ConverterFactory;
import org.jboss.forge.addon.resource.FileResource;
import org.jboss.forge.addon.shell.aesh.AbstractShellInteraction;
import org.jboss.forge.addon.shell.aesh.ForgeConsoleCallback;
import org.jboss.forge.addon.shell.aesh.completion.ForgeCompletion;
import org.jboss.forge.addon.shell.ui.ShellContext;
import org.jboss.forge.addon.shell.ui.ShellContextImpl;
import org.jboss.forge.addon.ui.CommandExecutionListener;
import org.jboss.forge.addon.ui.result.Result;
import org.jboss.forge.addon.ui.result.Results;
import org.jboss.forge.furnace.addons.AddonRegistry;
import org.jboss.forge.furnace.spi.ListenerRegistration;
import org.jboss.forge.furnace.util.Assert;
import org.jboss.forge.furnace.util.Strings;
/**
* Implementation of the {@link Shell} interface.
*
* Use the {@link AddonRegistry#getServices(Class)} to retrieve an instance of this object
*
* @author <a href="ggastald@redhat.com">George Gastaldi</a>
* @author <a href="mailto:lincolnbaxter@gmail.com">Lincoln Baxter, III</a>
*/
@Vetoed
public class ShellImpl implements Shell
{
private static final Logger log = Logger.getLogger(ShellImpl.class.getName());
private final List<CommandExecutionListener> listeners = new ArrayList<CommandExecutionListener>();
private Console console;
private FileResource<?> currentResource;
private CommandManager commandManager;
public ShellImpl(FileResource<?> initialResource, CommandManager commandManager, Settings settings)
{
this.currentResource = initialResource;
this.commandManager = commandManager;
init(settings);
}
@Override
public ListenerRegistration<CommandExecutionListener> addCommandExecutionListener(
final CommandExecutionListener listener)
{
listeners.add(listener);
return new ListenerRegistration<CommandExecutionListener>()
{
@Override
public CommandExecutionListener removeListener()
{
listeners.remove(listener);
return listener;
}
};
}
void init(Settings settings)
{
if (console != null)
{
try
{
console.stop();
}
catch (IOException e)
{
log.log(Level.WARNING, "Error while closing previous console", e);
}
console = null;
}
console = new Console(settings);
console.addCompletion(new ForgeCompletion(this));
console.setConsoleCallback(new ForgeConsoleCallback(this));
updatePrompt();
try
{
console.start();
}
catch (IOException io)
{
throw new RuntimeException("Unable to start console", io);
}
}
private void updatePrompt()
{
try
{
console.setPrompt(createPrompt());
}
catch (IOException io)
{
throw new RuntimeException("Prompt unavailable", io);
}
}
@Override
public Console getConsole()
{
if (console == null)
{
throw new IllegalStateException("Console not set. Shell.init not yet called?");
}
return console;
}
/**
* Creates an initial prompt
*/
private Prompt createPrompt()
{
// [ currentdir]$
List<TerminalCharacter> prompt = new ArrayList<TerminalCharacter>();
prompt.add(new TerminalCharacter('[', Color.DEFAULT_BG, Color.BLUE_TEXT, CharacterType.BOLD));
for(char c : currentResource.getName().toCharArray())
prompt.add(new TerminalCharacter(c, Color.DEFAULT_BG, Color.RED_TEXT, CharacterType.PLAIN));
prompt.add(new TerminalCharacter(']', Color.DEFAULT_BG, Color.BLUE_TEXT, CharacterType.BOLD));
prompt.add(new TerminalCharacter('$', Color.DEFAULT_BG, Color.DEFAULT_TEXT));
prompt.add(new TerminalCharacter(' ', Color.DEFAULT_BG, Color.DEFAULT_TEXT));
return new Prompt(prompt);
}
/**
* Used in {@link ForgeCompletion} and {@link ForgeConsoleCallback}
*/
public AbstractShellInteraction findCommand(ShellContext shellContext, String line)
{
if (Strings.isNullOrEmpty(line))
{
return null;
}
return commandManager.findCommand(shellContext, line);
}
public Collection<AbstractShellInteraction> findMatchingCommands(ShellContext shellContext, String line)
{
return commandManager.findMatchingCommands(shellContext, line);
}
public Result execute(AbstractShellInteraction shellCommand)
{
Result result = null;
try
{
firePreCommandListeners(shellCommand);
result = shellCommand.execute();
}
catch (Exception e)
{
result = Results.fail(e.getMessage(), e);
}
finally
{
firePostCommandListeners(shellCommand, result);
}
return result;
}
/**
* @param shellCommand
*/
private void firePreCommandListeners(AbstractShellInteraction shellCommand)
{
for (CommandExecutionListener listener : listeners)
{
listener.preCommandExecuted(shellCommand.getSourceCommand(), shellCommand.getContext());
}
}
/**
* @param shellCommand
*/
private void firePostCommandListeners(AbstractShellInteraction shellCommand, Result result)
{
for (CommandExecutionListener listener : listeners)
{
listener.postCommandExecuted(shellCommand.getSourceCommand(), shellCommand.getContext(), result);
}
}
public ShellContext newShellContext(ConsoleOperation consoleOperation)
{
ShellContextImpl shellContextImpl = new ShellContextImpl(this, currentResource);
shellContextImpl.setConsoleOperation(consoleOperation);
return shellContextImpl;
}
@PreDestroy
@Override
public void close()
{
try
{
this.console.stop();
}
catch (Exception ignored)
{
// Exception is ignored
}
}
public ConverterFactory getConverterFactory()
{
return commandManager.getConverterFactory();
}
@Override
public FileResource<?> getCurrentResource()
{
return currentResource;
}
@Override
public void setCurrentResource(FileResource<?> resource)
{
Assert.notNull(resource, "Current resource should not be null");
this.currentResource = resource;
updatePrompt();
}
}
|
package com.intellij.diagnostic;
import com.intellij.util.containers.ObjectLongHashMap;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.function.Consumer;
public final class StartUpMeasurer {
// Use constants for better overview of existing phases (and preserve consistent naming).
// `what + noun` is used as scheme for name to make analyzing easier (to visually group - `components loading/initialization/etc`,
// not to put common part of name to end of).
// It is not serves only display purposes - it is IDs. Visualizer and another tools to analyze data uses phase IDs,
// so, any changes must be discussed across all involved and reflected in changelog (see `format-changelog.md`).
public static final class Phases {
public static final String LOAD_MAIN_CLASS = "load main class";
// this phase name is not fully clear - it is time from `PluginManager.start` to `IdeaApplication.initApplication`
public static final String PREPARE_TO_INIT_APP = "app initialization preparation";
public static final String CHECK_SYSTEM_DIR = "check system dirs";
public static final String LOCK_SYSTEM_DIRS = "lock system dirs";
public static final String START_LOGGING = "start logging";
public static final String WAIT_TASKS = "wait tasks";
public static final String CONFIGURE_LOGGING = "configure logging";
// this phase name is not fully clear - it is time from `IdeaApplication.initApplication` to `IdeaApplication.run`
public static final String INIT_APP = "app initialization";
public static final String PLACE_ON_EVENT_QUEUE = "place on event queue";
// actually, now it is also registers services, not only components,but it doesn't worth to rename
public static final String REGISTER_COMPONENTS_SUFFIX = "component registration";
public static final String CREATE_COMPONENTS_SUFFIX = "component creation";
public static final String APP_INITIALIZED_CALLBACK = "app initialized callback";
public static final String FRAME_INITIALIZATION = "frame initialization";
public static final String PROJECT_CONVERSION = "project conversion";
public static final String PROJECT_BEFORE_LOADED = "project before loaded callbacks";
public static final String PROJECT_INSTANTIATION = "project instantiation";
public static final String PROJECT_PRE_STARTUP = "project pre-startup";
public static final String PROJECT_STARTUP = "project startup";
public static final String PROJECT_DUMB_POST_STARTUP = "project dumb post-startup";
public static final String RUN_PROJECT_POST_STARTUP_ACTIVITIES_DUMB_AWARE = "project post-startup dumb-aware activities";
public static final String RUN_PROJECT_POST_STARTUP_ACTIVITIES_EDT = "project post-startup edt activities";
public static final String LOAD_MODULES = "module loading";
public static final String PROJECT_OPENED_CALLBACKS = "project opened callbacks";
public static final String RESTORING_EDITORS = "restoring editors";
}
@SuppressWarnings("StaticNonFinalField")
public static boolean measuringPluginStartupCosts = true;
public static void stopPluginCostMeasurement() {
measuringPluginStartupCosts = false;
}
// ExtensionAreas not available for ExtensionPointImpl
public enum Level {
APPLICATION("app"), PROJECT("project"), MODULE("module");
private final String jsonFieldNamePrefix;
Level(@NotNull String jsonFieldNamePrefix) {
this.jsonFieldNamePrefix = jsonFieldNamePrefix;
}
@NotNull
public String getJsonFieldNamePrefix() {
return jsonFieldNamePrefix;
}
}
private static final long classInitStartTime = System.nanoTime();
private static final ConcurrentLinkedQueue<ActivityImpl> items = new ConcurrentLinkedQueue<>();
private static boolean isEnabled = true;
public static boolean isEnabled() {
return isEnabled;
}
@ApiStatus.Internal
public static final Map<String, ObjectLongHashMap<String>> pluginCostMap = new HashMap<>();
public static long getCurrentTime() {
return System.nanoTime();
}
/**
* Since start in ms.
*/
public static long sinceStart() {
ActivityImpl first = items.iterator().next();
return (getCurrentTime() - first.getStart()) / 1_000_000;
}
@NotNull
public static Activity start(@NotNull String name, @Nullable String description) {
return new ActivityImpl(name, description, null, null);
}
@NotNull
public static Activity start(@NotNull String name) {
return new ActivityImpl(name, null, null, null);
}
@NotNull
public static Activity start(@NotNull String name, @NotNull Level level) {
return new ActivityImpl(name, null, level, null);
}
public static void processAndClear(boolean isContinueToCollect, @NotNull Consumer<? super ActivityImpl> consumer) {
isEnabled = isContinueToCollect;
while (true) {
ActivityImpl item = items.poll();
if (item == null) {
break;
}
consumer.accept(item);
}
}
@ApiStatus.Internal
public static long getClassInitStartTime() {
return classInitStartTime;
}
static void add(@NotNull ActivityImpl activity) {
if (isEnabled) {
items.add(activity);
}
}
public static void addTimings(@NotNull LinkedHashMap<String, Long> timings, @NotNull String groupName) {
if (timings.isEmpty()) {
return;
}
List<Map.Entry<String, Long>> entries = new ArrayList<>(timings.entrySet());
ActivityImpl parent = new ActivityImpl(groupName, null, entries.get(0).getValue(), null, Level.APPLICATION, null, null);
parent.setEnd(getCurrentTime());
for (int i = 0; i < entries.size(); i++) {
ActivityImpl activity = new ActivityImpl(entries.get(i).getKey(), null, entries.get(i).getValue(), parent, Level.APPLICATION, null, null);
activity.setEnd(i == entries.size() - 1 ? parent.getEnd() : entries.get(i + 1).getValue());
items.add(activity);
}
items.add(parent);
}
public static void addPluginCost(@NotNull String pluginId, @NotNull String phase, long timeNanos) {
if (!isMeasuringPluginStartupCosts()) {
return;
}
synchronized (pluginCostMap) {
doAddPluginCost(pluginId, phase, timeNanos, pluginCostMap);
}
}
public static boolean isMeasuringPluginStartupCosts() {
return measuringPluginStartupCosts;
}
@ApiStatus.Internal
public static void doAddPluginCost(@NotNull String pluginId, @NotNull String phase, long timeNanos, @NotNull Map<String, ObjectLongHashMap<String>> pluginCostMap) {
ObjectLongHashMap<String> costPerPhaseMap = pluginCostMap.get(pluginId);
if (costPerPhaseMap == null) {
costPerPhaseMap = new ObjectLongHashMap<>();
pluginCostMap.put(pluginId, costPerPhaseMap);
}
long oldCost = costPerPhaseMap.get(phase);
if (oldCost == -1) {
oldCost = 0L;
}
costPerPhaseMap.put(phase, oldCost + timeNanos);
}
}
|
package modules;
import java.util.HashSet;
import bot.Message;
public class Voting implements Module {
private boolean isvoting = false;
private HashSet<String> voted = new HashSet<String>();
private double yes = 0;
private double votes = 0;
private String voteroom;
private Message m;
private String topic;
private long lastvote = System.currentTimeMillis();
//private Thread votethread;
@Override
public void parse(Message message) {
m = message;
if((lastvote + 1000*60) < System.currentTimeMillis()) {
isvoting = false;
voted.clear();
}
String target = m.param();
if(!m.param().startsWith("#")) target = m.sender();
if(m.botCommand().equals("vote")){
if(!isvoting){
isvoting = true;
voteroom = target;
startVote();
topic = m.botParams();
m.say(target, "A vote has been started! Voting will last 60 seconds. The topic is: \"" + topic + "\". Vote with " + m.commandChar() + "voteyes and " + m.commandChar() + "voteno");
lastvote = System.currentTimeMillis();
}
else{
m.say(target,"A vote for \"" + topic + "\" is already in progress");
}
}
if(m.botCommand().equals("voteyes") || m.botCommand().equals("voteno")){
if(isvoting){
if(!voted.contains(m.sender())){
voted.add(m.sender());
if(m.botCommand().equals("voteyes")){
yes++;
votes++;
m.say(target,m.sender() + ": You have voted yes");
}
if(m.botCommand().equals("voteno")){
votes++;
m.say(target,m.sender() + ": You have voted no");
}
}
else{
m.say(target,m.sender() + ": You have already voted");
}
}
else{
m.say(target, "There is currently no vote being run");
}
}
if(m.botCommand().equals("votestop")){
m.say(target, "Vote Stopped");
isvoting = false;
yes = 0;
votes = 0;
lastvote -= 1000*60;
voted.clear();
}
}
private void startVote(){
new Thread(new Runnable(){
public void run(){
try {
Thread.sleep(1000*30);
if(!isvoting)return;
m.say(voteroom, "The vote will end in 30 seconds\r\n");
Thread.sleep(1000*20);
if(!isvoting)return;
m.say(voteroom, "The vote will end in 10 seconds\r\n");
Thread.sleep(1000*10);
if(!isvoting)return;
}
catch (InterruptedException e) {}
if(votes == 0) m.say(voteroom, "Voting finished! No votes were sent");
double percentyes = (yes/votes*100);
double percentno = 100 - percentyes;
String result = String.format("Voting finished! Results were %.0f yes (%.0f%%), %.0f no (%.0f%%) out of %.0f votes" , yes, percentyes, (votes-yes), percentno, votes);
m.say(voteroom, result);
yes = 0;
votes = 0;
}
}).start();
}
}
|
package com.interview.array;
public class SortedArrayTransformation {
public int[] sortTransformedArray(int[] nums, int a, int b, int c) {
int start = 0;
int end = nums.length - 1;
int[] result = new int[nums.length];
int index = (a >= 0 ? nums.length - 1 : 0);
while (start <= end) {
int x = apply(nums[start], a, b, c);
int y = apply(nums[end], a, b, c);
boolean condition = (a >= 0 ? x >= y : x <= y);
if (condition) {
result[index] = x;
start++;
} else {
result[index] = y;
end
}
index = index + (a >= 0 ? -1 : 1);
}
return result;
}
private int apply(int x, int a, int b, int c) {
return a*x*x + b * x + c;
}
}
|
package ch.uzh.fabric.controller;
import ch.uzh.fabric.config.ProfileProperties;
import ch.uzh.fabric.config.SecurityConfig;
import ch.uzh.fabric.model.*;
import ch.uzh.fabric.service.CarService;
import ch.uzh.fabric.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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.servlet.mvc.support.RedirectAttributes;
import javax.annotation.PostConstruct;
import java.text.SimpleDateFormat;
import java.util.*;
@Controller
public class AppController {
public static final SimpleDateFormat timeFormat = new SimpleDateFormat("dd.MM.yyyy, HH:mm");
@Autowired
private UserService userService;
@Autowired
private CarService carService;
@PostConstruct
public void AppController() {
timeFormat.setTimeZone(TimeZone.getTimeZone("Europe/Zurich"));
}
@RequestMapping("/")
public String root(Authentication authentication) {
try {
authentication.isAuthenticated();
return "redirect:/index";
} catch (Exception e) {
return "redirect:/login";
}
}
@RequestMapping(value = "/account", method = RequestMethod.GET)
public String account(Authentication auth, Model model) {
String username = auth.getName();
String role = userService.getRole(auth);
ProfileProperties.User user = userService.findOrCreateUser(username, role);
model.addAttribute("orgName", user.getOrganization());
model.addAttribute("role", role.toUpperCase());
return "account";
}
@RequestMapping(value = "/account", method = RequestMethod.POST)
public String accountChange(Authentication auth, Model model, @RequestParam("orgName") String orgName) {
String username = auth.getName();
String role = userService.getRole(auth);
ProfileProperties.User user = userService.findOrCreateUser(username, role);
user.setOrganization(orgName);
model.addAttribute("orgName", user.getOrganization());
model.addAttribute("role", role.toUpperCase());
return "account";
}
@RequestMapping("/index")
public String index(Authentication auth,
Model model,
RedirectAttributes redirAttr,
@RequestParam(required = false) String error,
@RequestParam(required = false) String success) {
String username = auth.getName();
String role = userService.getRole(auth);
if (role.equals("dot")) {
return "redirect:/dot/";
} else if (role.equals("insurer")) {
return "redirect:/insurance/";
}
Collection<Car> cars = new ArrayList<>();
try {
cars = carService.getCars(username, role);
} catch (Exception e) {
error = e.getMessage();
}
model.addAttribute("cars", cars);
model.addAttribute("role", role.toUpperCase());
model.addAttribute("success", success);
model.addAttribute("error", error);
return "index";
}
@RequestMapping(value = "/import", method = RequestMethod.GET)
public String importCar(Model model,
Authentication auth,
@RequestParam(required = false) String error,
@RequestParam(required = false) String success,
@ModelAttribute Car car,
@ModelAttribute ProposalData proposalData) {
String role = userService.getRole(auth);
model.addAttribute("role", role.toUpperCase());
model.addAttribute("success", success);
model.addAttribute("error", error);
return "import";
}
@RequestMapping(value = "/import", method = RequestMethod.POST)
public String importCar(Model model,
RedirectAttributes redirAttr,
Authentication auth,
@ModelAttribute Car car,
@ModelAttribute ProposalData proposalData) {
String username = auth.getName();
String role = userService.getRole(auth);
proposalData.setCar(car.getVin());
try {
carService.importCar(username, role, car, proposalData);
} catch (Exception e) {
redirAttr.addAttribute("error", e.getMessage());
return "redirect:/import";
}
model.addAttribute("role", role.toUpperCase());
redirAttr.addAttribute("success", "Successfully imported car with VIN '" + car.getVin() + "'");
return "redirect:/index";
}
@RequestMapping("/login")
public String login() {
return "login";
}
@RequestMapping("/login-error")
public String loginError(Model model) {
model.addAttribute("loginError", true);
return "login";
}
@RequestMapping("/revocationProposal")
public String revocationProposal(RedirectAttributes redirAttr, Authentication auth, @RequestParam String vin) {
String username = auth.getName();
String role = userService.getRole(auth);
try {
carService.revocationProposal(username, role, vin);
} catch (Exception e) {
redirAttr.addAttribute("error", e.getMessage());
return "redirect:/index";
}
redirAttr.addAttribute("success", "Request for revocation registered, DOT is notified.");
return "redirect:/index";
}
@RequestMapping(value = "/insure", method = RequestMethod.GET)
public String insure(Model model,
RedirectAttributes redirAttr,
Authentication auth,
@RequestParam(required = false) String success,
@RequestParam(required = false) String error,
@RequestParam(required = false) String activeVin) {
String username = auth.getName();
String role = userService.getRole(auth);
Collection<Car> cars = new ArrayList<>();
try {
cars = carService.getCars(username, role);
} catch (Exception e) {
error = e.getMessage();
}
model.addAttribute("activeVin", activeVin);
model.addAttribute("error", error);
model.addAttribute("success", success);
model.addAttribute("cars", cars);
model.addAttribute("role", role.toUpperCase());
return "insure";
}
@RequestMapping(value = "/insure", method = RequestMethod.POST)
public String insure(RedirectAttributes redirAttr, Authentication auth, @RequestParam String vin, @RequestParam String company) {
String username = auth.getName();
String role = userService.getRole(auth);
try {
carService.insureProposal(username, role, vin, company);
} catch (Exception e) {
redirAttr.addAttribute("error", e.getMessage());
return "redirect:/insure";
}
redirAttr.addAttribute("success", "Insurance proposal saved. '" + company + "' will get back to you for confirmation.");
return "redirect:/insure";
}
@RequestMapping(value = "/sell", method = RequestMethod.GET)
public String sell(Model model,
RedirectAttributes redirAttr,
Authentication auth,
@RequestParam(required = false) String success,
@RequestParam(required = false) String error,
@RequestParam(required = false) String activeVin) {
String username = auth.getName();
String role = userService.getRole(auth);
Collection<Car> cars = new ArrayList<>();
try {
cars = carService.getCars(username, role);
} catch (Exception e) {
error = e.getMessage();
}
model.addAttribute("activeVin", activeVin);
model.addAttribute("success", success);
model.addAttribute("error", error);
model.addAttribute("cars", cars);
model.addAttribute("role", role.toUpperCase());
return "sell";
}
@RequestMapping(value = "/sell", method = RequestMethod.POST)
public String sellOfferCreate(RedirectAttributes redirAttr,
Authentication auth,
@RequestParam String vin,
@RequestParam(required = false) String buyer,
@RequestParam(required = false) String price) {
String username = auth.getName();
String role = userService.getRole(auth);
try {
carService.createSellingOffer(username, role, price, vin, buyer);
} catch (Exception e) {
redirAttr.addAttribute("error", e.getMessage());
return "redirect:/sell";
}
redirAttr.addAttribute("success", "Successfully sent selling offer for car '" + vin + "' to user '" + buyer + "'");
return "redirect:/sell";
}
@RequestMapping(value = "/offers", method = RequestMethod.GET)
public String sellOfferShow(Model model,
Authentication auth,
@RequestParam(required = false) String success,
@RequestParam(required = false) String error) {
String username = auth.getName();
String role = userService.getRole(auth);
Collection<Offer> offers;
Collection<OfferAndCar> offersAndCars = new ArrayList<>();
try {
offers = carService.getSalesOffers(username, role);
for (Offer offer : offers) {
Car car = carService.getCar(offer.getSeller(), role, offer.getVin());
offersAndCars.add(new OfferAndCar(offer, car));
}
} catch (Exception e) {
error = e.getMessage();
}
model.addAttribute("success", success);
model.addAttribute("error", error);
model.addAttribute("offersAndCars", offersAndCars);
model.addAttribute("role", role.toUpperCase());
return "offers";
}
@RequestMapping(value = "/offers", method = RequestMethod.POST)
public String sellOfferAccept(RedirectAttributes redirAttr,
Authentication auth,
@RequestParam String vin,
@RequestParam String seller,
@RequestParam String price) {
String username = auth.getName();
String role = userService.getRole(auth);
try {
carService.sell(seller, role, vin, username);
} catch (Exception e) {
redirAttr.addAttribute("error", e.getMessage());
return "redirect:/offers";
}
redirAttr.addAttribute("success", "Successfully bought car '" + vin + "' from user '" + seller + "' at price '" + price + "'.");
return "redirect:/offers";
}
@RequestMapping(value = "/history", method = RequestMethod.GET)
public String history(Model model,
RedirectAttributes redirAttr,
Authentication auth,
@RequestParam String vin,
@RequestParam(required = false) String error) {
String username = auth.getName();
String role = userService.getRole(auth);
Map<Integer, Car> history = new HashMap<>();
try {
history = carService.getCarHistory(username, role, vin);
} catch (Exception e) {
error = e.getMessage();
}
model.addAttribute("error", error);
model.addAttribute("vin", vin);
model.addAttribute("history", history);
model.addAttribute("timeFmt", timeFormat);
model.addAttribute("role", role.toUpperCase());
return "history";
}
}
|
package com.miviclin.droidengine2d.scene;
import java.util.HashMap;
import java.util.Map;
import com.miviclin.droidengine2d.Game;
import com.miviclin.droidengine2d.graphics.Graphics;
/**
* SceneManager.
*
* @author Miguel Vicente Linares
*
*/
public class SceneManager {
private HashMap<String, Scene> scenes;
private Scene activeScene;
/**
* Constructor.
*/
public SceneManager() {
this(16);
}
/**
* Constructor.
*
* @param initialCapacity Initial capacity for Scenes. If this capacity is reached, the data structure that holds
* the Scenes will be resized automatically.
*/
public SceneManager(int initialCapacity) {
this.scenes = new HashMap<String, Scene>((int) ((initialCapacity / 0.75f) + 1));
this.activeScene = null;
}
/**
* Registers an Scene in this SceneManager using the specified sceneId.<br>
* If an Scene with the specified sceneId was previously registered in this SceneManager, it will be replaced by the
* new one.<br>
* The active Scene will not change.
*
* @param sceneId Identifier of the Scene. It can be used to get the Scene from this SceneManager later.
* @param scene Scene (can not be null).
*/
public void registerScene(String sceneId, Scene scene) {
registerScene(sceneId, scene, false);
}
/**
* Registers an Scene in this SceneManager using the specified sceneId.<br>
* If an Scene with the specified sceneId was previously registered in this SceneManager, it will be replaced by the
* new one.
*
* @param sceneId Identifier of the Scene. It can be used to get the Scene from this SceneManager later.
* @param scene Scene (can not be null).
* @param activate true to make the Scene the active Scene of this SceneManager.
*/
public void registerScene(String sceneId, Scene scene, boolean activate) {
if (scene == null) {
throw new IllegalArgumentException("The Scene can not be null");
}
scenes.put(sceneId, scene);
scene.onRegister();
if (activate) {
setActiveScene(sceneId);
}
}
/**
* Unregisters the specified Scene from this SceneManager.<br>
* If an Scene was registered with the specified sceneId, {@link Scene#dispose()} is called on the Scene before it
* is removed from this SceneManager.
*
* @param sceneId Identifier of the Scene.
* @return Removed Scene or null
*/
public Scene unregisterScene(String sceneId) {
Scene removedScene = scenes.remove(sceneId);
if (removedScene != null) {
removedScene.dispose();
}
return removedScene;
}
/**
* Returns the Scene associated with the specified sceneId.
*
* @param sceneId Identifier of the Scene.
* @return Scene or null
*/
public Scene getScene(String sceneId) {
return scenes.get(sceneId);
}
/**
* Returns the active Scene of this SceneManager.
*
* @return Scene or null
*/
public Scene getActiveScene() {
return activeScene;
}
/**
* Sets the active Scene of this SceneManager.<br>
* The Scene must have been previously registered with the specified sceneId.
*
* @param sceneId Identifier of the Scene we want to set as the active Scene.
*/
public void setActiveScene(String sceneId) {
if (activeScene != null) {
activeScene.onDeactivation();
}
this.activeScene = scenes.get(sceneId);
if (activeScene != null) {
activeScene.onActivation();
}
}
/**
* This method is called when the engine is paused, usually when the activity goes to background.<br>
* Calls {@link Scene#onPause()} on the active Scene.
*/
public void pause() {
if (activeScene != null) {
activeScene.onPause();
}
}
/**
* This method is called when the engine is resumed, usually when the activity comes to foreground.<br>
* Calls {@link Scene#onResume()} on the active Scene.
*/
public void resume() {
if (activeScene != null) {
activeScene.onResume();
}
}
/**
* Calls {@link Scene#dispose()} on all Scenes registered in this SceneManager and removes them from the
* SceneManager.<br>
* This SceneManager will be left empty.
*/
public void dispose() {
for (Map.Entry<String, Scene> entry : scenes.entrySet()) {
entry.getValue().dispose();
entry.setValue(null);
}
activeScene = null;
scenes.clear();
}
/**
* Calls {@link Scene#update(float)} on the active Scene .<br>
* This method is called from {@link Game#update(float)}.
*
* @param delta Elapsed time, in milliseconds, since the last update.
*/
public void update(float delta) {
if (activeScene != null) {
activeScene.update(delta);
}
}
/**
* Calls {@link Scene#draw(Graphics)} on the active Scene.<br>
* This method is called from {@link Game#draw(Graphics)}.<br>
* This method is called from the redering thread after {@link SceneManager#update(float)} has been executed in the
* game thread.
*/
public void draw(Graphics graphics) {
if (activeScene != null) {
activeScene.draw(graphics);
}
}
}
|
/*
* $Id$
* $URL$
*/
package org.subethamail.plugin.filter;
import java.io.UnsupportedEncodingException;
import java.util.Collections;
import java.util.Set;
import java.util.TreeSet;
import javax.annotation.security.RunAs;
import javax.mail.MessagingException;
import javax.mail.internet.MimeUtility;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.annotation.ejb.Service;
import org.jboss.annotation.security.SecurityDomain;
import org.subethamail.common.SubEthaMessage;
import org.subethamail.core.lists.i.ListData;
import org.subethamail.core.plugin.i.Filter;
import org.subethamail.core.plugin.i.IgnoreException;
import org.subethamail.core.plugin.i.SendFilterContext;
import org.subethamail.core.plugin.i.helper.GenericFilter;
import org.subethamail.core.plugin.i.helper.Lifecycle;
@Service
@SecurityDomain("subetha")
@RunAs("siteAdmin")
public class ListHeaderFilter extends GenericFilter implements Lifecycle
{
private static Log log = LogFactory.getLog(ListHeaderFilter.class);
public enum ListHeader
{
LIST_ID ("List-Id"),
LIST_HELP ("List-Help"),
LIST_UNSUBSCRIBE ("List-Unsubscribe"),
LIST_SUBSCRIBE ("List-Subscribe"),
LIST_POST ("List-Post"),
LIST_OWNER ("List-Owner"),
LIST_ARCHIVE ("List-Archive");
private String header;
/** A set that contains all listHeaders */
public static final Set<ListHeader> ALL;
static
{
Set<ListHeader> tmp = new TreeSet<ListHeader>();
for (ListHeader p: ListHeader.values())
tmp.add(p);
ALL = Collections.unmodifiableSet(tmp);
}
ListHeader(String header)
{
this.header = header;
}
public String getHeader()
{
return this.header;
}
}
/*
* (non-Javadoc)
* @see org.subethamail.core.plugin.i.Filter#getName()
*/
public String getName()
{
return "List Headers";
}
/*
* (non-Javadoc)
* @see org.subethamail.core.plugin.i.Filter#getDescription()
*/
public String getDescription()
{
return "Appends the List-* headers as defined in RFC2369.";
}
/**
* @see Filter#onSend(SubEthaMessage, SendFilterContext)
*/
@Override
public void onSend(SubEthaMessage msg, SendFilterContext ctx) throws IgnoreException, MessagingException
{
log.debug(this.getName() + " onSend()");
// Remove all RFC defined List-* headers then add our own...
// The RFC defines some logic for this, but for now
// let's just remove them unconditionally.
for (ListHeader listHeader : ListHeader.ALL)
{
msg.removeHeader(listHeader.getHeader());
}
ListData listData = ctx.getList();
try
{
msg.setHeader("List-Id", MimeUtility.encodeText(listData.getName()) + " <" + listData.getEmail() + ">");
}
catch (UnsupportedEncodingException e)
{
}
msg.setHeader("List-Help", "<" + listData.getUrl() + ">");
msg.setHeader("List-Unsubscribe", "<" + listData.getUrl() + ">");
msg.setHeader("List-Subscribe", "<" + listData.getUrl() + ">");
msg.setHeader("List-Post", "<mailto:" + listData.getEmail() + ">");
// TODO: this should be much more properly generated
msg.setHeader("List-Owner", "<mailto:" + listData.getEmail().replace("@", "-owner@") + ">");
// TODO: Need to have a way to figure out the URL to the archives.
// msg.setHeader("List-Archive", "<" + listData. + "> (Web Archive)");
}
}
|
package com.intellij.openapi.diagnostic;
import com.intellij.util.ArrayUtilRt;
import com.intellij.util.ExceptionUtil;
import com.intellij.util.containers.ContainerUtil;
import org.apache.log4j.Level;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.lang.reflect.Constructor;
import java.util.Collection;
import java.util.function.Function;
/**
* A standard interface to write to %system%/log/idea.log (or %system%/testlog/idea.log in tests).<p/>
*
* In addition to writing to log file, "error" methods result in showing "IDE fatal errors" dialog in the IDE,
* in EAP versions or if "idea.fatal.error.notification" system property is "true" (). See
* {@link com.intellij.diagnostic.DefaultIdeaErrorLogger#canHandle} for more details.<p/>
*
* Note that in production, a call to "error" doesn't throw exceptions so the execution continues. In tests, however, an {@link AssertionError} is thrown.<p/>
*
* In most non-performance tests, debug level is enabled by default, so that when a test fails the full contents of its log are printed to stdout.
*/
public abstract class Logger {
public interface Factory {
@NotNull Logger getLoggerInstance(@NotNull String category);
}
private static final class DefaultFactory implements Factory {
@Override
public @NotNull Logger getLoggerInstance(@NotNull String category) {
return new DefaultLogger(category);
}
}
private static Factory ourFactory = new DefaultFactory();
public static void setFactory(@NotNull Class<? extends Factory> factory) {
if (isInitialized()) {
if (factory.isInstance(ourFactory)) {
return;
}
logFactoryChanged(factory);
}
try {
Constructor<? extends Factory> constructor = factory.getDeclaredConstructor();
constructor.setAccessible(true);
ourFactory = constructor.newInstance();
}
catch (Exception e) {
//noinspection CallToPrintStackTrace
e.printStackTrace();
throw new RuntimeException(e);
}
}
public static void setFactory(@NotNull Factory factory) {
if (isInitialized()) {
logFactoryChanged(factory.getClass());
}
ourFactory = factory;
}
@SuppressWarnings("UseOfSystemOutOrSystemErr")
private static void logFactoryChanged(Class<? extends Factory> factory) {
System.out.println("Changing log factory from " + ourFactory.getClass().getCanonicalName() +
" to " + factory.getCanonicalName() + '\n' + ExceptionUtil.getThrowableText(new Throwable()));
}
public static Factory getFactory() {
return ourFactory;
}
public static boolean isInitialized() {
return !(ourFactory instanceof DefaultFactory);
}
public static @NotNull Logger getInstance(@NotNull String category) {
return ourFactory.getLoggerInstance(category);
}
public static @NotNull Logger getInstance(@NotNull Class<?> cl) {
return ourFactory.getLoggerInstance("#" + cl.getName());
}
public abstract boolean isDebugEnabled();
public abstract void debug(String message);
public abstract void debug(@Nullable Throwable t);
public abstract void debug(String message, @Nullable Throwable t);
public void debug(@NotNull String message, Object @NotNull ... details) {
if (isDebugEnabled()) {
StringBuilder sb = new StringBuilder();
sb.append(message);
for (Object detail : details) {
sb.append(detail);
}
debug(sb.toString());
}
}
public void debugValues(@NotNull String header, @NotNull Collection<?> values) {
if (isDebugEnabled()) {
StringBuilder text = new StringBuilder();
text.append(header).append(" (").append(values.size()).append(")");
if (!values.isEmpty()) {
text.append(":");
for (Object value : values) {
text.append("\n");
text.append(value);
}
}
debug(text.toString());
}
}
public boolean isTraceEnabled() {
return isDebugEnabled();
}
/**
* Log a message with 'trace' level which finer-grained than 'debug' level. Use this method instead of {@link #debug(String)} for internal
* events of a subsystem to avoid overwhelming the log if 'debug' level is enabled.
*/
public void trace(String message) {
debug(message);
}
public void trace(@Nullable Throwable t) {
debug(t);
}
public void info(@NotNull Throwable t) {
info(t.getMessage(), t);
}
public abstract void info(String message);
public abstract void info(String message, @Nullable Throwable t);
public void warn(String message) {
warn(message, null);
}
public void warn(@NotNull Throwable t) {
warn(t.getMessage(), t);
}
public abstract void warn(String message, @Nullable Throwable t);
public void error(String message) {
error(message, new Throwable(message), ArrayUtilRt.EMPTY_STRING_ARRAY);
}
public void error(Object message) {
error(String.valueOf(message));
}
static final Function<Attachment, String> ATTACHMENT_TO_STRING = attachment -> attachment.getPath() + "\n" + attachment.getDisplayText();
public void error(String message, Attachment @NotNull ... attachments) {
error(message, null, attachments);
}
public void error(String message, @Nullable Throwable t, Attachment @NotNull ... attachments) {
error(message, t, ContainerUtil.map2Array(attachments, String.class, ATTACHMENT_TO_STRING::apply));
}
public void error(String message, String @NotNull ... details) {
error(message, new Throwable(message), details);
}
public void error(String message, @Nullable Throwable t) {
error(message, t, ArrayUtilRt.EMPTY_STRING_ARRAY);
}
public void error(@NotNull Throwable t) {
error(t.getMessage(), t, ArrayUtilRt.EMPTY_STRING_ARRAY);
}
public abstract void error(String message, @Nullable Throwable t, String @NotNull ... details);
@Contract("false,_->fail") // wrong, but avoid quite a few warnings in the code
public boolean assertTrue(boolean value, @Nullable Object message) {
if (!value) {
String resultMessage = "Assertion failed";
if (message != null) resultMessage += ": " + message;
error(resultMessage, new Throwable(resultMessage));
}
return value;
}
@Contract("false->fail") // wrong, but avoid quite a few warnings in the code
public boolean assertTrue(boolean value) {
//noinspection ConstantConditions
return value || assertTrue(false, null);
}
public abstract void setLevel(@NotNull Level level);
protected static Throwable checkException(@Nullable Throwable t) {
boolean pce = t instanceof ControlFlowException;
return pce ? new Throwable("Control-flow exceptions (like " + t.getClass().getSimpleName() + ") should never be logged: " +
"ignore for explicitly started processes or rethrow to handle on the outer process level", t)
: t;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.