answer
stringlengths 17
10.2M
|
|---|
package org.realityforge.arez.api2;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;
import org.jetbrains.annotations.TestOnly;
/**
* The scheduler is responsible for scheduling observer reactions.
*
* <p>When state has changed or potentially changed, observers are en-queued onto {@link #_pendingObservers}.
* Observers are processed in rounds. Each round involves processing the number of observers that are
* pending at the start of the round. Processing observers can schedule more observers and thus another
* round is scheduled if more observers are scheduled during the round.</p>
*
* If {@link #_maxReactionRounds} is not <tt>0</tt> and the number of rounds exceeds the value of
* {@link #_maxReactionRounds} then it is assumed that we have a runaway observer that does not
* terminate or stabilize and a failure is triggered.
*/
final class ReactionScheduler
{
static final int DEFAULT_MAX_REACTION_ROUNDS = 100;
@Nonnull
private final ArezContext _context;
/**
* Observers that have been scheduled but are not yet running.
*
* In future this should be a circular buffer.
*/
@Nonnull
private final ArrayList<Observer> _pendingObservers = new ArrayList<>();
/**
* The current reaction round.
*/
@Nonnegative
private int _currentReactionRound;
/**
* The number of reactions left in the current round.
*/
@Nonnegative
private int _remainingReactionsInCurrentRound;
/**
* The maximum number of iterations that can be triggered in sequence without triggering an error. Set this
* to 0 to disable check, otherwise trigger
*/
@Nonnegative
private int _maxReactionRounds = DEFAULT_MAX_REACTION_ROUNDS;
ReactionScheduler( @Nonnull final ArezContext context )
{
_context = Objects.requireNonNull( context );
}
@Nonnegative
int getMaxReactionRounds()
{
return _maxReactionRounds;
}
void setMaxReactionRounds( @Nonnegative final int maxReactionRounds )
{
Guards.invariant( () -> maxReactionRounds >= 0,
() -> String.format( "Attempting to set maxReactionRounds to negative value %d.",
maxReactionRounds ) );
_maxReactionRounds = maxReactionRounds;
}
boolean isRunningReactions()
{
return 0 != _currentReactionRound;
}
void scheduleReaction( @Nonnull final Observer observer )
{
Guards.invariant( observer::hasReaction,
() -> String.format(
"Attempting to schedule observer named '%s' when observer has no reaction.",
observer.getName() ) );
Guards.invariant( () -> !_pendingObservers.contains( observer ),
() -> String.format(
"Attempting to schedule observer named '%s' when observer is already pending.",
observer.getName() ) );
_pendingObservers.add( Objects.requireNonNull( observer ) );
}
void runPendingObservers()
{
// If we are already running observers, then newly scheduled observers will
// be picked up by that process, otherwise lets start scheduler.
if ( 0 == _currentReactionRound )
{
observerScheduler();
}
}
boolean runObserver()
{
final int pendingObserverCount = _pendingObservers.size();
// If we have reached the last observer in this round then
// determine if we need any more rounds and if we do ensure
if ( 0 == _remainingReactionsInCurrentRound )
{
if ( 0 == pendingObserverCount )
{
_currentReactionRound = 0;
return false;
}
else if ( _currentReactionRound + 1 > _maxReactionRounds )
{
_currentReactionRound = 0;
onRunawayReactionsDetected();
return false;
}
else
{
_currentReactionRound = _currentReactionRound + 1;
_remainingReactionsInCurrentRound = pendingObserverCount;
}
}
/*
* If we get to here there are still observers that need processing and we have not
* exceeded our round budget. So we pop the last observer off the list and process it.
*
* NOTE: The selection of the "last" observer is arbitrary and we could choose the first
* or any other. However we select the last as it is the most efficient and does not
* involve any memory allocations or copies. If we were using a circular buffer we could
* easily have chosen the first. (This may be a better option as it means we could have a
* lower value for _maxReactionRounds as processing would be width first rather than depth
* first.)
*/
_remainingReactionsInCurrentRound
final Observer observer = _pendingObservers.remove( pendingObserverCount - 1 );
observer.clearScheduledFlag();
invokeObserver( observer );
return true;
}
void invokeObserver( @Nonnull final Observer observer )
{
final String name = ArezConfig.enableNames() ? observer.getName() : null;
final TransactionMode mode = observer.getMode();
final Reaction reaction = observer.getReaction();
assert null != reaction;
try
{
getContext().transaction( name, mode, observer, () -> reaction.react( observer ) );
}
catch ( final Throwable t )
{
getContext().getObserverErrorHandler().onObserverError( observer, ObserverError.REACTION_ERROR, t );
}
}
private void onRunawayReactionsDetected()
{
final List<String> observerNames =
ArezConfig.checkInvariants() && ArezConfig.verboseErrorMessages() ?
_pendingObservers.stream().map( Node::getName ).collect( Collectors.toList() ) :
null;
if ( ArezConfig.purgeReactionsWhenRunawayDetected() )
{
_pendingObservers.clear();
}
Guards.fail( () ->
String.format(
"Runaway reaction(s) detected. Observers still running after %d rounds. Current observers include: %s",
_maxReactionRounds,
String.valueOf( observerNames ) ) );
}
int observerScheduler()
{
int observersScheduled = 0;
while ( runObserver() )
{
observersScheduled++;
}
return observersScheduled;
}
@Nonnull
ArezContext getContext()
{
return _context;
}
@TestOnly
@Nonnull
ArrayList<Observer> getPendingObservers()
{
return _pendingObservers;
}
@TestOnly
int getCurrentReactionRound()
{
return _currentReactionRound;
}
@TestOnly
int getRemainingReactionsInCurrentRound()
{
return _remainingReactionsInCurrentRound;
}
}
|
package org.cubeengine.dirigent.parser;
import java.util.Arrays;
import java.util.List;
import org.cubeengine.dirigent.formatter.argument.Argument;
import org.cubeengine.dirigent.formatter.argument.Parameter;
import org.cubeengine.dirigent.formatter.argument.Value;
import org.cubeengine.dirigent.parser.element.CompleteMacro;
import org.cubeengine.dirigent.parser.element.Element;
import org.cubeengine.dirigent.parser.element.IndexedDefaultMacro;
import org.cubeengine.dirigent.parser.element.NamedMacro;
import org.junit.Test;
import static java.util.Arrays.asList;
import static org.cubeengine.dirigent.parser.Parser.parse;
import static org.cubeengine.dirigent.parser.Parser.unescape;
import static org.cubeengine.dirigent.parser.element.DefaultMacro.DEFAULT_MACRO;
import static org.junit.Assert.assertEquals;
public class ParserTest
{
public static List<Element> elems(Element... components)
{
return Arrays.asList(components);
}
public static Element txt(String s)
{
return new Text(s);
}
public static Element named(String name, Argument... args)
{
return new NamedMacro(name, asList(args));
}
public static Element indexed(int i)
{
return new IndexedDefaultMacro(i);
}
public static Element complete(int i, String name, Argument... args)
{
return new CompleteMacro(i, name, asList(args));
}
public static Argument arg(String name)
{
return new Value(name);
}
public static Argument arg(String name, String val)
{
return new Parameter(name, val);
}
public static Element err(String s)
{
return new InvalidMacro(s);
}
@Test
public void testReadMessage()
{
assertEquals(elems(txt("only text")), parse("only text"));
assertEquals(elems(DEFAULT_MACRO), parse("{}"));
assertEquals(elems(named("name")), parse("{name}"));
assertEquals(elems(indexed(0)), parse("{0}"));
assertEquals(elems(complete(1, "name")), parse("{1:name#with index and comment}"));
assertEquals(
elems(complete(1, "name", arg("and parameter"))),
parse("{1:name#with index and comment:and parameter}"));
assertEquals(
elems(complete(1, "name", arg("#parameterwithhash"))),
parse("{1:name#with index and comment:#parameterwithhash}"));
assertEquals(
elems(complete(1, "name", arg("and parameter", "with value"))),
parse("{1:name#with index and comment:and parameter=with value}"));
assertEquals(
elems(complete(1, "name", arg("and parameter", "with value"), arg("multiple"))),
parse("{1:name#with index and comment:and parameter=with value:multiple}"));
assertEquals(
elems(complete(1, "name", arg("and parameter", "with value"), arg("multiple"), arg("and one", "more"))),
parse("{1:name#with index and comment:and parameter=with value:multiple:and one=more}"));
assertEquals(
elems(txt("text and a macro "), complete(1, "name", arg("and parameter", "with value"), arg("multiple"), arg("and one", "more")), txt(" more text")),
parse("text and a macro {1:name#with index and comment:and parameter=with value:multiple:and one=more} more text"));
assertEquals(
elems(txt("empty "), named(" ")),
parse("empty { }"));
}
@Test
public void testInvalidTokens()
{
assertEquals(
elems(txt("illegal macro {starts but wont end")),
parse("illegal macro {starts but wont end"));
assertEquals(
elems(txt("illegal macro {starts:has arguments but wont end")),
parse("illegal macro {starts:has arguments but wont end"));
assertEquals(
elems(txt("illegal macro "), txt("{starts:has arguments }but wont end")),
parse("illegal macro {starts:has arguments \\}but wont end"));
assertEquals(
elems(txt("illegal macro "), txt("{starts#lab}el:has arguments but wont end")),
parse("illegal macro {starts#lab\\}el:has arguments but wont end"));
assertEquals(
elems(txt("illegal macro { text and "), named("second")),
parse("illegal macro { text and {second}"));
assertEquals(
elems(txt("illegal macro {0 text and "), named("second")),
parse("illegal macro {0 text and {second}"));
assertEquals(
elems(txt("illegal macro {text and "), named("second")),
parse("illegal macro {text and {second}"));
assertEquals(
elems(txt("illegal macro {0:text and "), named("second")),
parse("illegal macro {0:text and {second}"));
assertEquals(
elems(txt("illegal macro {0:text#label and "), named("second")),
parse("illegal macro {0:text#label and {second}"));
assertEquals(
elems(txt("illegal macro {0:text#label:arg and "), named("second")),
parse("illegal macro {0:text#label:arg and {second}"));
assertEquals(
elems(txt("illegal macro {text#label:arg and "), named("second")),
parse("illegal macro {text#label:arg and {second}"));
assertEquals(
elems(txt("illegal macro {text#label and "), named("second")),
parse("illegal macro {text#label and {second}"));
assertEquals(
elems(txt("illegal macro {text:arg and "), named("second")),
parse("illegal macro {text:arg and {second}"));
assertEquals(
elems(txt("illegal macro {0:text:arg and "), named("second")),
parse("illegal macro {0:text:arg and {second}"));
}
@Test
public void testReadMessageWithEscaping()
{
assertEquals(
elems(txt("some escape test {} or {name#label:mdmmd}")),
parse("some escape test \\{} or \\{name#label:mdmmd}"));
assertEquals(
elems(txt("some text with "),
named("text", arg("static \\\\ tex:t\\"), arg("moep")),
txt("!")),
parse("some text with {text:static \\\\\\\\ tex\\:t\\\\:moep}!"));
assertEquals(
elems(txt("escaping "), named("in", arg("arg"))),
parse("escaping {in#la\\:b\\el:arg}"));
assertEquals(
elems(txt("escaping "), named("in", arg("and#}=:\\arg"))),
parse("escaping {in#la#be\\}l:and#\\}\\=\\:\\\\arg}"));
}
@Test
public void testEmptyPartsOfAMacro() {
// TODO have a look at the tests; are they correct?
assertEquals(
elems(txt("empty {0:}")),
parse("empty {0:}"));
assertEquals(
elems(txt("empty {name
parse("empty {name
assertEquals(
elems(txt("empty {name#moep:}")),
parse("empty {name#moep:}"));
assertEquals(
elems(txt("empty {name:}")),
parse("empty {name:}"));
assertEquals(
elems(txt("empty "), named("name", arg(":"))),
parse("empty {name::}"));
assertEquals(
elems(txt("empty "), named("name")),
parse("empty {name
}
@Test
public void testStripBackslashes()
{
assertEquals("\\", convertAndUnescape("\\"));
assertEquals("sta\\:tic", convertAndUnescape("sta\\:tic"));
assertEquals("static", convertAndUnescape("static"));
assertEquals("static \\\\ tex\\:t\\", convertAndUnescape("static \\\\\\\\ tex\\:t\\\\"));
assertEquals("static \\\\ tex\\:t\\", convertAndUnescape("static \\\\\\\\ tex\\:t\\\\"));
}
@Test(expected = IllegalArgumentException.class)
public void testNullMessage()
{
parse(null);
}
@Test
public void testIntegerConversion()
{
assertEquals(elems(indexed(11)), parse("{11}"));
}
@Test
public void testIntegerValidation()
{
assertEquals(elems(named("1a")), parse("{1a}"));
}
private static String convertAndUnescape(String s)
{
return unescape(s, 0, s.length(), false);
}
}
|
package org.elasticsearch.shield.tribe;
import com.carrotsearch.randomizedtesting.LifecycleScope;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthStatus;
import org.elasticsearch.client.support.Headers;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.common.collect.ImmutableMap;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.shield.authc.support.UsernamePasswordToken;
import org.elasticsearch.shield.signature.InternalSignatureService;
import org.elasticsearch.test.InternalTestCluster;
import org.elasticsearch.test.ShieldIntegrationTest;
import org.elasticsearch.test.ShieldSettingsSource;
import org.elasticsearch.transport.Transport;
import org.elasticsearch.tribe.TribeService;
import org.junit.*;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.elasticsearch.test.InternalTestCluster.clusterName;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoFailures;
import static org.hamcrest.Matchers.*;
public class TribeTests extends ShieldIntegrationTest {
//use known suite prefix since their threads are already ignored via ElasticsearchThreadFilter
public static final String SECOND_CLUSTER_NODE_PREFIX = SUITE_CLUSTER_NODE_PREFIX;
public static final String TRIBE_CLUSTER_NODE_PREFIX = "tribe_cluster_node_";
private static InternalTestCluster cluster2;
private static ShieldSettingsSource tribeSettingsSource;
private InternalTestCluster tribeNodeCluster;
@Before
public void setupSecondClusterAndTribeNode() throws Exception {
final Settings globalClusterSettings = internalCluster().getInstance(Settings.class);
//TODO tribe nodes and all of the tribes need to have either ssl disabled or enabled as a whole
//we read the randomized setting from the global cluster and apply it to the other cluster that we are going to start
//for simplicity the same certificates are used on all clusters
final boolean sslTransportEnabled = globalClusterSettings.getAsBoolean("shield.transport.ssl", null);
//we need to make sure that all clusters and the tribe node use the same system key, we just point to the same file on all clusters
byte[] systemKey = Files.readAllBytes(Paths.get(globalClusterSettings.get(InternalSignatureService.FILE_SETTING)));
//we run this part in @Before instead of beforeClass because we need to have the current cluster already assigned to global
//so that we can retrieve its settings and apply some of them the the second cluster (and tribe node too)
if (cluster2 == null) {
// create another cluster
String cluster2Name = clusterName(Scope.SUITE.name(), Integer.toString(CHILD_JVM_ID), randomLong());
//no port conflicts as this test uses the global cluster and a suite cluster that gets manually created
ShieldSettingsSource cluster2SettingsSource = new ShieldSettingsSource(2, sslTransportEnabled, systemKey, newTempDir(LifecycleScope.SUITE), Scope.SUITE);
cluster2 = new InternalTestCluster(randomLong(), 2, 2, cluster2Name, cluster2SettingsSource, 0, false, CHILD_JVM_ID, SECOND_CLUSTER_NODE_PREFIX);
assert tribeSettingsSource == null;
//given the low (2 and 1) number of nodes that the 2 SUITE clusters will have, we are not going to have port conflicts
tribeSettingsSource = new ShieldSettingsSource(1, sslTransportEnabled, systemKey, newTempDir(LifecycleScope.SUITE), Scope.SUITE) {
@Override
public Settings node(int nodeOrdinal) {
Settings shieldSettings = super.node(nodeOrdinal);
//all the settings are needed for the tribe node, some of them will also need to be copied to the tribe clients configuration
ImmutableSettings.Builder builder = ImmutableSettings.builder().put(shieldSettings);
//the tribe node itself won't join any cluster, no need for unicast discovery configuration
builder.remove("discovery.type");
builder.remove("discovery.zen.ping.multicast.enabled");
//remove doesn't remove all the elements of an array, but we know it has only one element
builder.remove("discovery.zen.ping.unicast.hosts.0");
//copy the needed settings to the tribe clients configuration
ImmutableMap<String, String> shieldSettingsAsMap = shieldSettings.getAsMap();
for (Map.Entry<String, String> entry : shieldSettingsAsMap.entrySet()) {
if (isSettingNeededForTribeClient(entry.getKey())) {
builder.put("tribe.t1." + entry.getKey(), entry.getValue());
builder.put("tribe.t2." + entry.getKey(), entry.getValue());
}
}
return builder.put("tribe.t1.cluster.name", internalCluster().getClusterName())
.putArray("tribe.t1.discovery.zen.ping.unicast.hosts", unicastHosts(internalCluster()))
.put("tribe.t1.shield.transport.ssl", sslTransportEnabled)
.put("tribe.t2.cluster.name", cluster2.getClusterName())
.putArray("tribe.t2.discovery.zen.ping.unicast.hosts", unicastHosts(cluster2))
.put("tribe.t2.shield.transport.ssl", sslTransportEnabled).build();
}
/**
* Returns true if the setting is needed to setup a tribe client and needs to get forwarded to it, false otherwise.
* Only some of the settings need to be forwarded e.g. realm configuration gets filtered out
*/
private boolean isSettingNeededForTribeClient(String settingKey) {
if (settingKey.equals("transport.host")) {
return true;
}
//discovery settings get forwarded to tribe clients to disable multicast discovery
if (settingKey.equals("discovery.type") || settingKey.equals("discovery.zen.ping.multicast.enabled")) {
return true;
}
//plugins need to be properly loaded on the tribe clients too
if (settingKey.startsWith("plugin")) {
return true;
}
//make sure node.mode is network on the tribe clients too
if (settingKey.equals("node.mode")) {
return true;
}
//forward the shield audit enabled to the tribe clients
if (settingKey.equals("shield.audit.enabled")) {
return true;
}
//forward the system key to the tribe clients, same file will be used
if (settingKey.equals(InternalSignatureService.FILE_SETTING)) {
return true;
}
//forward ssl settings to the tribe clients, same certificates will be used
if (settingKey.startsWith("shield.ssl") || settingKey.equals("shield.transport.ssl") || settingKey.equals("shield.http.ssl")) {
return true;
}
//forward the credentials to the tribe clients
if (settingKey.equals("shield.user") || settingKey.equals(Headers.PREFIX + "." + UsernamePasswordToken.BASIC_AUTH_HEADER)) {
return true;
}
return false;
}
};
}
cluster2.beforeTest(getRandom(), 0.5);
//we need to recreate the tribe node after each test otherwise ensureClusterSizeConsistency barfs
String tribeClusterName = clusterName(Scope.SUITE.name(), Integer.toString(CHILD_JVM_ID), randomLong());
tribeNodeCluster = new InternalTestCluster(randomLong(), 1, 1, tribeClusterName, tribeSettingsSource, 0, false, CHILD_JVM_ID, TRIBE_CLUSTER_NODE_PREFIX);
tribeNodeCluster.beforeTest(getRandom(), 0.5);
awaitSameNodeCounts();
}
private static String[] unicastHosts(InternalTestCluster testCluster) {
Iterable<Transport> transports = testCluster.getInstances(Transport.class);
List<String> unicastHosts = new ArrayList<>();
for (Transport transport : transports) {
TransportAddress transportAddress = transport.boundAddress().boundAddress();
assertThat(transportAddress, is(instanceOf(InetSocketTransportAddress.class)));
InetSocketTransportAddress inetSocketTransportAddress = (InetSocketTransportAddress) transportAddress;
unicastHosts.add("localhost:" + inetSocketTransportAddress.address().getPort());
}
return unicastHosts.toArray(new String[unicastHosts.size()]);
}
@After
public void afterTest() throws IOException {
//we need to close the tribe node after each test otherwise ensureClusterSizeConsistency barfs
if (tribeNodeCluster != null) {
try {
tribeNodeCluster.close();
} finally {
tribeNodeCluster = null;
}
}
//and clean up the second cluster that we manually started
if (cluster2 != null) {
try {
cluster2.wipe();
} finally {
cluster2.afterTest();
}
}
}
@AfterClass
public static void tearDownSecondCluster() {
if (cluster2 != null) {
try {
cluster2.close();
} finally {
cluster2 = null;
tribeSettingsSource = null;
}
}
}
@Test
public void testIndexRefreshAndSearch() throws Exception {
internalCluster().client().admin().indices().prepareCreate("test1").get();
cluster2.client().admin().indices().prepareCreate("test2").get();
assertThat(tribeNodeCluster.client().admin().cluster().prepareHealth().setWaitForGreenStatus().get().getStatus(), equalTo(ClusterHealthStatus.GREEN));
tribeNodeCluster.client().prepareIndex("test1", "type1", "1").setSource("field1", "value1").get();
tribeNodeCluster.client().prepareIndex("test2", "type1", "1").setSource("field1", "value1").get();
assertNoFailures(tribeNodeCluster.client().admin().indices().prepareRefresh().get());
assertHitCount(tribeNodeCluster.client().prepareSearch().get(), 2l);
}
private void awaitSameNodeCounts() throws Exception {
assertBusy(new Runnable() {
@Override
public void run() {
DiscoveryNodes tribeNodes = tribeNodeCluster.client().admin().cluster().prepareState().get().getState().getNodes();
assertThat(countDataNodesForTribe("t1", tribeNodes), equalTo(internalCluster().client().admin().cluster().prepareState().get().getState().getNodes().dataNodes().size()));
assertThat(countDataNodesForTribe("t2", tribeNodes), equalTo(cluster2.client().admin().cluster().prepareState().get().getState().getNodes().dataNodes().size()));
}
});
}
private int countDataNodesForTribe(String tribeName, DiscoveryNodes nodes) {
int count = 0;
for (DiscoveryNode node : nodes) {
if (!node.dataNode()) {
continue;
}
if (tribeName.equals(node.getAttributes().get(TribeService.TRIBE_NAME))) {
count++;
}
}
return count;
}
}
|
package com.collective.celos;
import java.util.Arrays;
import org.junit.Assert;
import org.junit.Test;
import com.collective.celos.api.ScheduledTime;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
public class ShellCommandTriggerTest {
private final ObjectMapper mapper = new ObjectMapper();
@Test(expected=IllegalArgumentException.class)
public void testRequiresCommand() throws Exception {
new ShellCommandTrigger(mapper.createObjectNode());
}
@Test(expected=IllegalArgumentException.class)
public void testCommandMustBeArray() throws Exception {
ObjectNode node = mapper.createObjectNode();
node.put(ShellCommandTrigger.COMMAND_PROP, "foo");
new ShellCommandTrigger(node);
}
@Test(expected=IllegalArgumentException.class)
public void testOnlyStringsAllowedInArray() throws Exception {
ArrayNode array = mapper.createArrayNode();
array.add(12);
array.add("-h");
array.add("now");
ObjectNode node = mapper.createObjectNode();
node.put(ShellCommandTrigger.COMMAND_PROP, array);
new ShellCommandTrigger(node);
}
@Test
public void testUsesCommand() throws Exception {
ObjectNode node = makeConfig("shutdown", "-h", "now");
Assert.assertEquals(Arrays.asList("shutdown", "-h", "now"), new ShellCommandTrigger(node).getRawCommandElements());
}
@Test
public void testCheckSuccessExitValueProperly() throws Exception {
ObjectNode node = makeConfig("true");
Assert.assertTrue(new ShellCommandTrigger(node).isDataAvailable(ScheduledTime.now(), ScheduledTime.now()));
}
@Test
public void testChecksFailureExitValueProperly() throws Exception {
ObjectNode node = makeConfig("false");
Assert.assertFalse(new ShellCommandTrigger(node).isDataAvailable(ScheduledTime.now(), ScheduledTime.now()));
}
@Test
public void testSetsVariables() throws Exception {
String time = "2014-03-24T09:25:13Z";
ScheduledTime t = new ScheduledTime(time);
ObjectNode node = makeConfig("src/test/resources/com/collective/celos/shell-command-trigger-test-script.sh",
"${year}-${month}-${day}T${hour}:${minute}:${second}Z");
Assert.assertTrue(new ShellCommandTrigger(node).isDataAvailable(ScheduledTime.now(), t));
}
private ObjectNode makeConfig(String... command) {
ObjectNode node = mapper.createObjectNode();
ArrayNode array = mapper.createArrayNode();
for (String s : command) { array.add(s); }
node.put(ShellCommandTrigger.COMMAND_PROP, array);
return node;
}
}
|
package org.mongoste.core;
import org.mongoste.model.StatAction;
import org.mongoste.model.StatBasicCounter;
import org.mongoste.model.StatEvent;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
import java.util.List;
import java.util.Map;
import java.util.Properties;
/**
*
* @author mrmx
*/
public class AbstractStatsEngineTest {
AbstractStatsEngine instance;
@Before
public void setUp() {
instance = new AbstractStatsEngineImpl();
}
/**
* Test of createDotPath method, of class AbstractStatsEngine.
*/
@Test
public void testCreateDotPath() {
System.out.println("createDotPath");
assertEquals("a", instance.createDotPath("a"));
assertEquals("a.b", instance.createDotPath("a","b"));
assertEquals("a.b.c", instance.createDotPath("a","b","c"));
assertEquals("a.c", instance.createDotPath("a",null,"c"));
assertEquals("a.c", instance.createDotPath("a","","c"));
assertEquals("1.2", instance.createDotPath(1,2));
assertEquals("a.c", instance.createDotPath("a.","c"));
assertEquals("a.c", instance.createDotPath("a..","c."));
assertEquals("a.c", instance.createDotPath("a",".","c"));
}
public class AbstractStatsEngineImpl extends AbstractStatsEngine {
@Override
public void init(Properties properties) throws StatsEngineException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void handleEvent(StatEvent event) throws StatsEngineException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void buildStats(TimeScope scope) throws StatsEngineException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public List<StatAction> getActions(String clientId) throws StatsEngineException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public List<StatBasicCounter> getTopTargets(String clientId, String targetType, String action, Integer limit) throws StatsEngineException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Map<String, Long> getMultiTargetActionCount(String clientId, String targetType, List<String> targets) throws StatsEngineException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Map<String, Long> getOwnerActionCount(String clientId, String targetType, String owner, String... tags) throws StatsEngineException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void setTargetOwners(String clientId, String targetType, List<String> targets, List<String> owners) throws StatsEngineException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void setTargetTags(String clientId, String targetType, String target, List<String> tags) throws StatsEngineException {
throw new UnsupportedOperationException("Not supported yet.");
}
}
}
|
package cucumber.runtime.formatter;
import cucumber.api.Result;
import cucumber.api.formatter.NiceAppendable;
import cucumber.runtime.TestHelper;
import cucumber.runtime.Utils;
import cucumber.runtime.model.CucumberFeature;
import cucumber.util.FixJava;
import gherkin.deps.com.google.gson.JsonParser;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.junit.Test;
import org.mockito.stubbing.Answer;
import java.io.File;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static cucumber.runtime.TestHelper.createEmbedHookAction;
import static cucumber.runtime.TestHelper.createWriteHookAction;
import static cucumber.runtime.TestHelper.feature;
import static cucumber.runtime.TestHelper.result;
import static java.util.Arrays.asList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class HTMLFormatterTest {
private final static String jsFunctionCallRegexString = "formatter.(\\w*)\\(([^)]*)\\);";
private final static Pattern jsFunctionCallRegex = Pattern.compile(jsFunctionCallRegexString);
private URL outputDir;
public void writeReport() throws Throwable {
outputDir = Utils.toURL(TempDir.createTempDirectory().getAbsolutePath());
runFeaturesWithFormatter(outputDir);
}
@Test
public void writes_index_html() throws Throwable {
writeReport();
URL indexHtml = new URL(outputDir, "index.html");
Document document = Jsoup.parse(new File(indexHtml.getFile()), "UTF-8");
Element reportElement = document.body().getElementsByClass("cucumber-report").first();
assertEquals("", reportElement.text());
}
@Test
public void writes_valid_report_js() throws Throwable {
writeReport();
String reportJs = FixJava.readReader(new InputStreamReader(new URL(outputDir, "report.js").openStream(), "UTF-8"));
assertJsFunctionCallSequence(asList("" +
"formatter.uri(\"some\\\\windows\\\\path\\\\some.feature\");\n",
"formatter.feature({\n" +
" \"name\": \"\",\n" +
" \"description\": \"\",\n" +
" \"keyword\": \"Feature\"\n" +
"});\n",
"formatter.scenario({\n" +
" \"name\": \"some cukes\",\n" +
" \"description\": \"\",\n" +
" \"keyword\": \"Scenario\"\n" +
"});\n",
"formatter.step({\n" +
" \"name\": \"first step\",\n" +
" \"keyword\": \"Given \"\n" +
"});\n",
"formatter.match({\n" +
" \"location\": \"path/step_definitions.java:3\"\n" +
"});\n",
"formatter.result({\n" +
" \"status\": \"passed\"\n" +
"});\n",
"formatter.embedding(\"image/png\", \"embedded0.png\");\n",
"formatter.after({\n" +
" \"status\": \"passed\"\n" +
"});\n",
"formatter.embedding(\"text/plain\", \"dodgy stack trace here\");\n",
"formatter.after({\n" +
" \"status\": \"passed\"\n" +
"});\n"),
reportJs);
}
@Test
public void includes_uri() throws Throwable {
writeReport();
String reportJs = FixJava.readReader(new InputStreamReader(new URL(outputDir, "report.js").openStream(), "UTF-8"));
assertContains("formatter.uri(\"some\\\\windows\\\\path\\\\some.feature\");", reportJs);
}
@Test
public void included_embedding() throws Throwable {
writeReport();
String reportJs = FixJava.readReader(new InputStreamReader(new URL(outputDir, "report.js").openStream(), "UTF-8"));
assertContains("formatter.embedding(\"image/png\", \"embedded0.png\");", reportJs);
assertContains("formatter.embedding(\"text/plain\", \"dodgy stack trace here\");", reportJs);
}
@Test
public void should_handle_a_single_scenario() throws Throwable {
CucumberFeature feature = feature("path/test.feature", "" +
"Feature: feature name\n" +
" Scenario: scenario name\n" +
" Given first step\n" +
" Then second step\n");
Map<String, Result> stepsToResult = new HashMap<String, Result>();
stepsToResult.put("first step", result("passed"));
stepsToResult.put("second step", result("passed"));
Map<String, String> stepsToLocation = new HashMap<String, String>();
stepsToLocation.put("first step", "path/step_definitions.java:3");
stepsToLocation.put("second step", "path/step_definitions.java:7");
long stepDuration = 1;
String formatterOutput = runFeatureWithHTMLFormatter(feature, stepsToResult, stepsToLocation, stepDuration);
assertJsFunctionCallSequence(asList("" +
"formatter.uri(\"path/test.feature\");\n", "" +
"formatter.feature({\n" +
" \"description\": \"\",\n" +
" \"name\": \"feature name\",\n" +
" \"keyword\": \"Feature\"\n" +
"});\n", "" +
"formatter.scenario({\n" +
" \"description\": \"\",\n" +
" \"keyword\": \"Scenario\",\n" +
" \"name\": \"scenario name\"\n" +
"});\n", "" +
"formatter.step({\n" +
" \"keyword\": \"Given \",\n" +
" \"name\": \"first step\"\n" +
"});\n", "" +
"formatter.match({\n" +
" \"location\": \"path/step_definitions.java:3\"\n" +
"});\n", "" +
"formatter.result({\n" +
" \"status\": \"passed\"\n" +
"});\n", "" +
"formatter.step({\n" +
" \"keyword\": \"Then \",\n" +
" \"name\": \"second step\"\n" +
"});\n", "" +
"formatter.match({\n" +
" \"location\": \"path/step_definitions.java:7\"\n" +
"});\n", "" +
"formatter.result({\n" +
" \"status\": \"passed\"\n" +
"});"),
formatterOutput);
}
@Test
public void should_handle_backgound() throws Throwable {
CucumberFeature feature = feature("path/test.feature", "" +
"Feature: feature name\n" +
" Background: background name\n" +
" Given first step\n" +
" Scenario: scenario 1\n" +
" Then second step\n" +
" Scenario: scenario 2\n" +
" Then third step\n");
Map<String, Result> stepsToResult = new HashMap<String, Result>();
stepsToResult.put("first step", result("passed"));
stepsToResult.put("second step", result("passed"));
stepsToResult.put("third step", result("passed"));
Map<String, String> stepsToLocation = new HashMap<String, String>();
stepsToLocation.put("first step", "path/step_definitions.java:3");
stepsToLocation.put("second step", "path/step_definitions.java:7");
stepsToLocation.put("third step", "path/step_definitions.java:11");
long stepDuration = 1;
String formatterOutput = runFeatureWithHTMLFormatter(feature, stepsToResult, stepsToLocation, stepDuration);
assertJsFunctionCallSequence(asList("" +
"formatter.background({\n" +
" \"description\": \"\",\n" +
" \"keyword\": \"Background\",\n" +
" \"name\": \"background name\"\n" +
"});\n", "" +
"formatter.step({\n" +
" \"keyword\": \"Given \",\n" +
" \"name\": \"first step\"\n" +
"});\n", "" +
"formatter.match({\n" +
" \"location\": \"path/step_definitions.java:3\"\n" +
"});\n", "" +
"formatter.result({\n" +
" \"status\": \"passed\"\n" +
"});\n", "" +
"formatter.scenario({\n" +
" \"description\": \"\",\n" +
" \"keyword\": \"Scenario\",\n" +
" \"name\": \"scenario 1\"\n" +
"});\n", "" +
"formatter.step({\n" +
" \"keyword\": \"Then \",\n" +
" \"name\": \"second step\"\n" +
"});\n", "" +
"formatter.match({\n" +
" \"location\": \"path/step_definitions.java:7\"\n" +
"});\n", "" +
"formatter.result({\n" +
" \"status\": \"passed\"\n" +
"});\n", "" +
"formatter.background({\n" +
" \"description\": \"\",\n" +
" \"keyword\": \"Background\",\n" +
" \"name\": \"background name\"\n" +
"});\n", "" +
"formatter.step({\n" +
" \"keyword\": \"Given \",\n" +
" \"name\": \"first step\"\n" +
"});\n", "" +
"formatter.match({\n" +
" \"location\": \"path/step_definitions.java:3\"\n" +
"});\n", "" +
"formatter.result({\n" +
" \"status\": \"passed\"\n" +
"});\n", "" +
"formatter.scenario({\n" +
" \"description\": \"\",\n" +
" \"keyword\": \"Scenario\",\n" +
" \"name\": \"scenario 2\"\n" +
"});\n", "" +
"formatter.step({\n" +
" \"keyword\": \"Then \",\n" +
" \"name\": \"third step\"\n" +
"});\n", "" +
"formatter.match({\n" +
" \"location\": \"path/step_definitions.java:11\"\n" +
"});\n", "" +
"formatter.result({\n" +
" \"status\": \"passed\"\n" +
"});\n"),
formatterOutput);
}
@Test
public void should_handle_scenario_outline() throws Throwable {
CucumberFeature feature = feature("path/test.feature", "" +
"Feature: feature name\n" +
" Scenario Outline: outline name\n" +
" Given first step\n" +
" Then <arg> step\n" +
" Examples: examples name\n" +
" | arg |\n" +
" | second |\n" +
" | third |\n");
Map<String, Result> stepsToResult = new HashMap<String, Result>();
stepsToResult.put("first step", result("passed"));
stepsToResult.put("second step", result("passed"));
stepsToResult.put("third step", result("passed"));
Map<String, String> stepsToLocation = new HashMap<String, String>();
stepsToLocation.put("first step", "path/step_definitions.java:3");
stepsToLocation.put("second step", "path/step_definitions.java:7");
stepsToLocation.put("third step", "path/step_definitions.java:11");
long stepDuration = 1;
String formatterOutput = runFeatureWithHTMLFormatter(feature, stepsToResult, stepsToLocation, stepDuration);
assertJsFunctionCallSequence(asList("" +
"formatter.uri(\"path/test.feature\");\n", "" +
"formatter.feature({\n" +
" \"description\": \"\",\n" +
" \"name\": \"feature name\",\n" +
" \"keyword\": \"Feature\"\n" +
"});\n", "" +
"formatter.scenarioOutline({\n" +
" \"description\": \"\",\n" +
" \"keyword\": \"Scenario Outline\",\n" +
" \"name\": \"outline name\"\n" +
"});\n", "" +
"formatter.step({\n" +
" \"keyword\": \"Given \",\n" +
" \"name\": \"first step\"\n" +
"});\n", "" +
"formatter.step({\n" +
" \"keyword\": \"Then \",\n" +
" \"name\": \"\\u003carg\\u003e step\"\n" +
"});\n", "" +
"formatter.examples({\n" +
" \"description\": \"\",\n" +
" \"keyword\": \"Examples\",\n" +
" \"name\": \"examples name\",\n" +
" \"rows\": [\n" +
" {\n" +
" \"cells\": [\n" +
" \"arg\"\n" +
" ]\n" +
" },\n" +
" {\n" +
" \"cells\": [\n" +
" \"second\"\n" +
" ]\n" +
" },\n" +
" {\n" +
" \"cells\": [\n" +
" \"third\"\n" +
" ]\n" +
" }\n" +
" ]\n" +
"});\n", "" +
"formatter.scenario({\n" +
" \"description\": \"\",\n" +
" \"keyword\": \"Scenario Outline\",\n" +
" \"name\": \"outline name\"\n" +
"});\n", "" +
"formatter.step({\n" +
" \"keyword\": \"Given \",\n" +
" \"name\": \"first step\"\n" +
"});\n", "" +
"formatter.match({\n" +
" \"location\": \"path/step_definitions.java:3\"\n" +
"});\n", "" +
"formatter.result({\n" +
" \"status\": \"passed\"\n" +
"});\n", "" +
"formatter.step({\n" +
" \"keyword\": \"Then \",\n" +
" \"name\": \"second step\"\n" +
"});\n", "" +
"formatter.match({\n" +
" \"location\": \"path/step_definitions.java:7\"\n" +
"});\n", "" +
"formatter.result({\n" +
" \"status\": \"passed\"\n" +
"});\n", "" +
"formatter.scenario({\n" +
" \"description\": \"\",\n" +
" \"keyword\": \"Scenario Outline\",\n" +
" \"name\": \"outline name\"\n" +
"});\n", "" +
"formatter.step({\n" +
" \"keyword\": \"Given \",\n" +
" \"name\": \"first step\"\n" +
"});\n", "" +
"formatter.match({\n" +
" \"location\": \"path/step_definitions.java:3\"\n" +
"});\n", "" +
"formatter.result({\n" +
" \"status\": \"passed\"\n" +
"});\n", "" +
"formatter.step({\n" +
" \"keyword\": \"Then \",\n" +
" \"name\": \"third step\"\n" +
"});\n", "" +
"formatter.match({\n" +
" \"location\": \"path/step_definitions.java:11\"\n" +
"});\n", "" +
"formatter.result({\n" +
" \"status\": \"passed\"\n" +
"});"),
formatterOutput);
}
@Test
public void should_handle_before_hooks() throws Throwable {
CucumberFeature feature = feature("path/test.feature", "" +
"Feature: feature name\n" +
" Scenario: scenario name\n" +
" Given first step\n");
Map<String, Result> stepsToResult = new HashMap<String, Result>();
stepsToResult.put("first step", result("passed"));
Map<String, String> stepsToLocation = new HashMap<String, String>();
stepsToLocation.put("first step", "path/step_definitions.java:3");
List<SimpleEntry<String, Result>> hooks = new ArrayList<SimpleEntry<String, Result>>();
hooks.add(TestHelper.hookEntry("before", result("passed")));
long stepDuration = 1;
String formatterOutput = runFeatureWithHTMLFormatter(feature, stepsToResult, stepsToLocation, hooks, stepDuration);
assertJsFunctionCallSequence(asList("" +
"formatter.scenario({\n" +
" \"description\": \"\",\n" +
" \"keyword\": \"Scenario\",\n" +
" \"name\": \"scenario name\"\n" +
"});\n", "" +
"formatter.before({\n" +
" \"status\": \"passed\"\n" +
"});\n", "" +
"formatter.step({\n" +
" \"keyword\": \"Given \",\n" +
" \"name\": \"first step\"\n" +
"});\n", "" +
"formatter.match({\n" +
" \"location\": \"path/step_definitions.java:3\"\n" +
"});\n", "" +
"formatter.result({\n" +
" \"status\": \"passed\"\n" +
"});\n"),
formatterOutput);
}
@Test
public void should_handle_after_hooks() throws Throwable {
CucumberFeature feature = feature("path/test.feature", "" +
"Feature: feature name\n" +
" Scenario: scenario name\n" +
" Given first step\n");
Map<String, Result> stepsToResult = new HashMap<String, Result>();
stepsToResult.put("first step", result("passed"));
Map<String, String> stepsToLocation = new HashMap<String, String>();
stepsToLocation.put("first step", "path/step_definitions.java:3");
List<SimpleEntry<String, Result>> hooks = new ArrayList<SimpleEntry<String, Result>>();
hooks.add(TestHelper.hookEntry("after", result("passed")));
long stepDuration = 1;
String formatterOutput = runFeatureWithHTMLFormatter(feature, stepsToResult, stepsToLocation, hooks, stepDuration);
assertJsFunctionCallSequence(asList("" +
"formatter.scenario({\n" +
" \"description\": \"\",\n" +
" \"keyword\": \"Scenario\",\n" +
" \"name\": \"scenario name\"\n" +
"});\n", "" +
"formatter.step({\n" +
" \"keyword\": \"Given \",\n" +
" \"name\": \"first step\"\n" +
"});\n", "" +
"formatter.match({\n" +
" \"location\": \"path/step_definitions.java:3\"\n" +
"});\n", "" +
"formatter.result({\n" +
" \"status\": \"passed\"\n" +
"});\n", "" +
"formatter.after({\n" +
" \"status\": \"passed\"\n" +
"});\n"),
formatterOutput);
}
@Test
public void should_handle_output_from_before_hooks() throws Throwable {
CucumberFeature feature = feature("path/test.feature", "" +
"Feature: feature name\n" +
" Scenario: scenario name\n" +
" Given first step\n");
Map<String, Result> stepsToResult = new HashMap<String, Result>();
stepsToResult.put("first step", result("passed"));
Map<String, String> stepsToLocation = new HashMap<String, String>();
stepsToLocation.put("first step", "path/step_definitions.java:3");
List<SimpleEntry<String, Result>> hooks = new ArrayList<SimpleEntry<String, Result>>();
hooks.add(TestHelper.hookEntry("before", result("passed")));
List<Answer<Object>> hookActions = new ArrayList<Answer<Object>>();
hookActions.add(createWriteHookAction("printed from hook"));
long stepDuration = 1;
String formatterOutput = runFeatureWithHTMLFormatter(feature, stepsToResult, stepsToLocation, hooks, hookActions, stepDuration);
assertJsFunctionCallSequence(asList("" +
"formatter.scenario({\n" +
" \"description\": \"\",\n" +
" \"keyword\": \"Scenario\",\n" +
" \"name\": \"scenario name\"\n" +
"});\n", "" +
"formatter.write(\"printed from hook\");\n", "" +
"formatter.before({\n" +
" \"status\": \"passed\"\n" +
"});\n", "" +
"formatter.step({\n" +
" \"keyword\": \"Given \",\n" +
" \"name\": \"first step\"\n" +
"});\n", "" +
"formatter.match({\n" +
" \"location\": \"path/step_definitions.java:3\"\n" +
"});\n", "" +
"formatter.result({\n" +
" \"status\": \"passed\"\n" +
"});\n"),
formatterOutput);
}
@Test
public void should_handle_output_from_after_hooks() throws Throwable {
CucumberFeature feature = feature("path/test.feature", "" +
"Feature: feature name\n" +
" Scenario: scenario name\n" +
" Given first step\n");
Map<String, Result> stepsToResult = new HashMap<String, Result>();
stepsToResult.put("first step", result("passed"));
Map<String, String> stepsToLocation = new HashMap<String, String>();
stepsToLocation.put("first step", "path/step_definitions.java:3");
List<SimpleEntry<String, Result>> hooks = new ArrayList<SimpleEntry<String, Result>>();
hooks.add(TestHelper.hookEntry("after", result("passed")));
List<Answer<Object>> hookActions = new ArrayList<Answer<Object>>();
hookActions.add(createWriteHookAction("printed from hook"));
long stepDuration = 1;
String formatterOutput = runFeatureWithHTMLFormatter(feature, stepsToResult, stepsToLocation, hooks, hookActions, stepDuration);
assertJsFunctionCallSequence(asList("" +
"formatter.scenario({\n" +
" \"description\": \"\",\n" +
" \"keyword\": \"Scenario\",\n" +
" \"name\": \"scenario name\"\n" +
"});\n", "" +
"formatter.step({\n" +
" \"keyword\": \"Given \",\n" +
" \"name\": \"first step\"\n" +
"});\n", "" +
"formatter.match({\n" +
" \"location\": \"path/step_definitions.java:3\"\n" +
"});\n", "" +
"formatter.result({\n" +
" \"status\": \"passed\"\n" +
"});\n", "" +
"formatter.write(\"printed from hook\");\n", "" +
"formatter.after({\n" +
" \"status\": \"passed\"\n" +
"});\n"),
formatterOutput);
}
@Test
public void should_handle_text_embeddings_from_before_hooks() throws Throwable {
CucumberFeature feature = feature("path/test.feature", "" +
"Feature: feature name\n" +
" Scenario: scenario name\n" +
" Given first step\n");
Map<String, Result> stepsToResult = new HashMap<String, Result>();
stepsToResult.put("first step", result("passed"));
Map<String, String> stepsToLocation = new HashMap<String, String>();
stepsToLocation.put("first step", "path/step_definitions.java:3");
List<SimpleEntry<String, Result>> hooks = new ArrayList<SimpleEntry<String, Result>>();
hooks.add(TestHelper.hookEntry("before", result("passed")));
List<Answer<Object>> hookActions = new ArrayList<Answer<Object>>();
hookActions.add(createEmbedHookAction("embedded from hook".getBytes("US-ASCII"), "text/ascii"));
long stepDuration = 1;
String formatterOutput = runFeatureWithHTMLFormatter(feature, stepsToResult, stepsToLocation, hooks, hookActions, stepDuration);
assertJsFunctionCallSequence(asList("" +
"formatter.scenario({\n" +
" \"description\": \"\",\n" +
" \"keyword\": \"Scenario\",\n" +
" \"name\": \"scenario name\"\n" +
"});\n", "" +
"formatter.embedding(\"text/ascii\", \"embedded from hook\");\n", "" +
"formatter.before({\n" +
" \"status\": \"passed\"\n" +
"});\n", "" +
"formatter.step({\n" +
" \"keyword\": \"Given \",\n" +
" \"name\": \"first step\"\n" +
"});\n", "" +
"formatter.match({\n" +
" \"location\": \"path/step_definitions.java:3\"\n" +
"});\n", "" +
"formatter.result({\n" +
" \"status\": \"passed\"\n" +
"});\n"),
formatterOutput);
}
private void assertJsFunctionCallSequence(List<String> expectedList, String actual) {
Iterator<String> expectedIterator = expectedList.iterator();
String expected = expectedIterator.next();
Matcher expectedMatcher = jsFunctionCallRegex.matcher(expected);
Matcher actualMatcher = jsFunctionCallRegex.matcher(actual);
assertTrue(jsFunctionCallMatchFailure(expected), expectedMatcher.find());
boolean found = false;
while (actualMatcher.find()) {
if (matchFound(expectedMatcher, actualMatcher)) {
found = true;
break;
}
}
assertTrue(jsFunctionCallNotFoundMessage(actual, expected), found);
while (expectedIterator.hasNext()) {
expected = expectedIterator.next();
expectedMatcher = jsFunctionCallRegex.matcher(expected);
assertTrue(jsFunctionCallMatchFailure(expected), expectedMatcher.find());
assertTrue(jsFunctionCallNotFoundMessage(actual, expected), actualMatcher.find());
if (!matchFound(expectedMatcher, actualMatcher)) {
fail(jsFunctionCallNotFoundMessage(actual, expected));
}
}
}
private String jsFunctionCallMatchFailure(String expected) {
return "The expected string: " + expected + ", does not match " + jsFunctionCallRegexString;
}
private String jsFunctionCallNotFoundMessage(String actual, String expected) {
return "The expected js function call: " + expected + ", is not found in " + actual;
}
private boolean matchFound(Matcher expectedMatcher, Matcher actualMatcher) {
String expectedFunction = expectedMatcher.group(1);
String actualFunction = actualMatcher.group(1);
if (!expectedFunction.equals(actualFunction)) {
return false;
}
String expectedArgument = expectedMatcher.group(2);
String actualArgumant = actualMatcher.group(2);
if (matchUsingJson(expectedArgument, actualArgumant)) {
JsonParser parser = new JsonParser();
return parser.parse(expectedArgument).equals(parser.parse(actualArgumant));
} else {
return expectedArgument.equals(actualArgumant);
}
}
private boolean matchUsingJson(String expected, String actual) {
return expected.startsWith("{") && actual.startsWith("{");
}
private void assertContains(String substring, String string) {
if (string.indexOf(substring) == -1) {
fail(String.format("[%s] not contained in [%s]", substring, string));
}
}
private void runFeaturesWithFormatter(URL outputDir) throws Throwable {
final HTMLFormatter f = new HTMLFormatter(outputDir);
CucumberFeature feature = feature("some\\windows\\path\\some.feature", "" +
"Feature:\n" +
" Scenario: some cukes\n" +
" Given first step\n");
Map<String, Result> stepsToResult = new HashMap<String, Result>();
stepsToResult.put("first step", result("passed"));
Map<String, String> stepsToLocation = new HashMap<String, String>();
stepsToLocation.put("first step", "path/step_definitions.java:3");
List<SimpleEntry<String, Result>> hooks = new ArrayList<SimpleEntry<String, Result>>();
hooks.add(TestHelper.hookEntry("after", result("passed")));
hooks.add(TestHelper.hookEntry("after", result("passed")));
List<Answer<Object>> hookActions = new ArrayList<Answer<Object>>();
hookActions.add(createEmbedHookAction("fakedata".getBytes("US-ASCII"), "image/png"));
hookActions.add(createEmbedHookAction("dodgy stack trace here".getBytes("US-ASCII"), "text/plain"));
long stepHookDuration = 1;
TestHelper.runFeatureWithFormatter(feature, stepsToResult, stepsToLocation, hooks, Collections.<String>emptyList(), hookActions, stepHookDuration, f);
}
private String runFeatureWithHTMLFormatter(final CucumberFeature feature, final Map<String, Result> stepsToResult, final Map<String, String> stepsToLocation, final long stepHookDuration) throws Throwable {
return runFeatureWithHTMLFormatter(feature, stepsToResult, stepsToLocation, Collections.<SimpleEntry<String, Result>>emptyList(), stepHookDuration);
}
private String runFeatureWithHTMLFormatter(final CucumberFeature feature, final Map<String, Result> stepsToResult, final Map<String, String> stepsToLocation, final List<SimpleEntry<String, Result>> hooks, final long stepHookDuration) throws Throwable {
return runFeatureWithHTMLFormatter(feature, stepsToResult, stepsToLocation, hooks, Collections.<Answer<Object>>emptyList(), stepHookDuration);
}
private String runFeatureWithHTMLFormatter(final CucumberFeature feature, final Map<String, Result> stepsToResult, final Map<String, String> stepsToLocation, final List<SimpleEntry<String, Result>> hooks, final List<Answer<Object>> hookActions, final long stepHookDuration) throws Throwable {
final StringBuilder out = new StringBuilder();
final HTMLFormatter htmlFormatter = new HTMLFormatter(null, new NiceAppendable(out));
TestHelper.runFeatureWithFormatter(feature, stepsToResult, stepsToLocation, hooks, Collections.<String>emptyList(), hookActions, stepHookDuration, htmlFormatter);
return out.toString();
}
}
|
package seedu.address.testutil;
import seedu.address.commons.exceptions.IllegalValueException;
import seedu.address.model.AddressBook;
import seedu.address.model.person.Person;
import seedu.address.model.person.UniquePersonList;
public class TypicalTestPersons {
public static TestPerson alice;
public static TestPerson benson;
public static TestPerson carl;
public static TestPerson daniel;
public static TestPerson elle;
public static TestPerson fiona;
public static TestPerson george;
public static TestPerson hoon;
public static TestPerson ida;
public TypicalTestPersons() {
try {
alice = new PersonBuilder().withName("Alice Pauline").withAddress("123, Jurong West Ave 6, #08-111")
.withEmail("alice@gmail.com").withPhone("85355255")
.withTags("friends").build();
benson = new PersonBuilder().withName("Benson Meier").withAddress("311, Clementi Ave 2, #02-25")
.withEmail("johnd@gmail.com").withPhone("98765432")
.withTags("owesMoney", "friends").build();
carl = new PersonBuilder().withName("Carl Kurz").withPhone("95352563").withEmail("heinz@yahoo.com").withAddress("wall street").build();
daniel = new PersonBuilder().withName("Daniel Meier").withPhone("87652533").withEmail("cornelia@google.com").withAddress("10th street").build();
elle = new PersonBuilder().withName("Elle Meyer").withPhone("9482224").withEmail("werner@gmail.com").withAddress("michegan ave").build();
fiona = new PersonBuilder().withName("Fiona Kunz").withPhone("9482427").withEmail("lydia@gmail.com").withAddress("little tokyo").build();
george = new PersonBuilder().withName("George Best").withPhone("9482442").withEmail("anna@google.com").withAddress("4th street").build();
//Manually added
hoon = new PersonBuilder().withName("Hoon Meier").withPhone("8482424").withEmail("stefan@mail.com").withAddress("little india").build();
ida = new PersonBuilder().withName("Ida Mueller").withPhone("8482131").withEmail("hans@google.com").withAddress("chicago ave").build();
} catch (IllegalValueException e) {
e.printStackTrace();
assert false : "not possible";
}
}
public static void loadAddressBookWithSampleData(AddressBook ab) {
try {
ab.addPerson(new Person(alice));
ab.addPerson(new Person(benson));
ab.addPerson(new Person(carl));
ab.addPerson(new Person(daniel));
ab.addPerson(new Person(elle));
ab.addPerson(new Person(fiona));
ab.addPerson(new Person(george));
} catch (UniquePersonList.DuplicatePersonException e) {
assert false : "not possible";
}
}
public TestPerson[] getTypicalPersons() {
return new TestPerson[]{alice, benson, carl, daniel, elle, fiona, george};
}
public AddressBook getTypicalAddressBook() {
AddressBook ab = new AddressBook();
loadAddressBookWithSampleData(ab);
return ab;
}
}
|
package software.committed.rejux;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import software.committed.rejux.impl.AbstractReducer;
import software.committed.rejux.impl.Store;
public class RejuxFullApiTest {
public static class ArthimeticStore {
private final Store<SumState> sum;
public ArthimeticStore() {
sum = Rejux.createStore(new SumState(0), new SumReducer());
}
public Subscription subscribe(Subscriber<SumState> subscriber) {
return sum.subscribe(subscriber);
}
public Store<SumState> getSum() {
return sum;
}
public int getSumValue() {
return sum.getState().getValue();
}
}
public static class SumState {
private final int sum;
public SumState(int sum) {
this.sum = sum;
}
public int getValue() {
return sum;
}
}
public static class SumReducer extends AbstractReducer<SumState> {
public SumReducer() {
super(SumState.class);
}
public SumState add(SumState state, AddAction action) {
return new SumState(state.getValue() + action.getAmount());
}
}
public static class CountSubscriber implements Subscriber<SumState> {
private int count;
@Override
public void onStateChanged(SumState state) {
count++;
}
public int getCount() {
return count;
}
}
public static class AddAction implements Action {
private final int amount;
public AddAction(int amount) {
this.amount = amount;
}
public int getAmount() {
return amount;
}
}
@Test
public void canCreateStore() {
ArthimeticStore store = new ArthimeticStore();
assertNotNull(store);
assertEquals(0, store.getSumValue());
}
@Test
public void canCreateDispatch() {
assertNotNull(Rejux.createSuperStore(new ArthimeticStore()));
}
@Test
public void canDispatchAction() {
ArthimeticStore store = new ArthimeticStore();
Dispatcher dispatcher = Rejux.createSuperStore(store);
assertEquals(0, store.getSumValue());
dispatcher.dispatch(new AddAction(10));
assertEquals(10, store.getSumValue());
}
@Test
public void canSubscribe() {
ArthimeticStore store = new ArthimeticStore();
Dispatcher dispatcher = Rejux.createSuperStore(store);
assertEquals(0, store.getSumValue());
CountSubscriber subscriber = new CountSubscriber();
Subscription subscription = store.subscribe(subscriber);
assertTrue(subscription.isSubscribed());
dispatcher.dispatch(new AddAction(10));
assertEquals(10, store.getSumValue());
assertEquals(1, subscriber.getCount());
subscription.remove();
assertFalse(subscription.isSubscribed());
assertEquals(1, subscriber.getCount());
}
}
|
package org.basex.query;
import static org.basex.core.Text.*;
import static org.basex.query.QueryError.*;
import static org.basex.util.Token.*;
import java.io.*;
import java.util.*;
import java.util.Map.*;
import org.basex.build.json.*;
import org.basex.build.json.JsonOptions.*;
import org.basex.core.*;
import org.basex.core.MainOptions.MainParser;
import org.basex.core.jobs.*;
import org.basex.core.locks.*;
import org.basex.core.users.*;
import org.basex.data.*;
import org.basex.io.parse.json.*;
import org.basex.io.serial.*;
import org.basex.query.func.*;
import org.basex.query.iter.*;
import org.basex.query.scope.*;
import org.basex.query.up.*;
import org.basex.query.util.*;
import org.basex.query.util.collation.*;
import org.basex.query.util.ft.*;
import org.basex.query.util.list.*;
import org.basex.query.value.*;
import org.basex.query.value.item.*;
import org.basex.query.value.node.*;
import org.basex.query.value.seq.*;
import org.basex.query.value.type.*;
import org.basex.query.var.*;
import org.basex.util.*;
import org.basex.util.ft.*;
import org.basex.util.hash.*;
import org.basex.util.list.*;
public final class QueryContext extends Job implements Closeable {
/** The evaluation stack. */
public final QueryStack stack = new QueryStack();
/** Static variables. */
public final Variables vars = new Variables();
/** Functions. */
public final StaticFuncs funcs = new StaticFuncs();
/** Externally bound variables. */
private final HashMap<QNm, Value> bindings = new HashMap<>();
/** External query properties. */
private final HashMap<String, Object> props;
/** Parent query context. */
public final QueryContext parent;
/** Query info. */
public final QueryInfo info;
/** Database context. */
public final Context context;
/** Query resources. */
public QueryResources resources;
/** Update container. */
public Updates updates;
/** Global database options (will be reassigned after query execution). */
QueryOptions options = new QueryOptions(this);
/** Current context value. */
public QueryFocus focus = new QueryFocus();
/** Current date/time values. */
public QueryDateTime dateTime;
/** Full-text position data (needed for highlighting full-text results). */
public FTPosData ftPosData = Prop.gui ? new FTPosData() : null;
/** Current full-text lexer. */
public FTLexer ftLexer;
/** Current full-text options. */
private FTOpt ftOpt;
/** Full-text token positions (needed for highlighting full-text results). */
public int ftPos;
/** Scoring flag. */
public boolean scoring;
/** Available collations. */
public TokenObjMap<Collation> collations;
/** Strings to lock defined by read-lock option. */
public final LockList readLocks = new LockList();
/** Strings to lock defined by write-lock option. */
public final LockList writeLocks = new LockList();
/** Number of successive tail calls. */
public int tailCalls;
/** Maximum number of successive tail calls (will be set before compilation). */
public int maxCalls;
/** Function for the next tail call. */
private XQFunction tailFunc;
/** Arguments for the next tail call. */
private Value[] args;
/** Counter for variable IDs. */
public int varIDs;
/** Parsed modules, containing the file path and module uri. */
public final TokenMap modParsed = new TokenMap();
/** Pre-declared modules, containing module uri and their file paths (required for test APIs). */
final TokenMap modDeclared = new TokenMap();
/** Stack of module files that are currently parsed. */
final TokenList modStack = new TokenList();
/** Initial context value. */
public MainModule ctxItem;
/** Root expression of the query. */
public MainModule root;
/** Serialization parameters. */
private SerializerOptions serParams;
/** Indicates if the default serialization parameters are used. */
private boolean defaultOutput;
/** Indicates if the query has been compiled. */
private boolean compiled;
/** Indicates if the query context has been closed. */
private boolean closed;
/**
* Constructor.
* @param parent parent context
*/
public QueryContext(final QueryContext parent) {
this(parent.context, parent, parent.info, parent.props);
parent.pushJob(this);
resources = parent.resources;
updates = parent.updates;
}
/**
* Constructor.
* @param context database context
*/
public QueryContext(final Context context) {
this(context, null, null, new HashMap<>());
resources = new QueryResources(this);
}
/**
* Constructor.
* @param context database context
* @param parent parent context (can be {@code null})
* @param info query info
* @param props external properties
*/
private QueryContext(final Context context, final QueryContext parent, final QueryInfo info,
final HashMap<String, Object> props) {
this.context = context;
this.parent = parent;
this.info = info != null ? info : new QueryInfo(this);
this.props = props;
}
/**
* Parses the specified query.
* @param query query string
* @param uri base URI (may be {@code null})
* @return main module
* @throws QueryException query exception
*/
public Module parse(final String query, final String uri) throws QueryException {
return parse(query, QueryProcessor.isLibrary(query), uri);
}
/**
* Parses the specified query.
* @param query query string
* @param library library/main module
* @param uri base URI (may be {@code null})
* @return main module
* @throws QueryException query exception
*/
public Module parse(final String query, final boolean library, final String uri)
throws QueryException {
return library ? parseLibrary(query, uri) : parseMain(query, uri);
}
/**
* Parses the specified query.
* @param query query string
* @param uri base URI (may be {@code null})
* @return main module
* @throws QueryException query exception
*/
public MainModule parseMain(final String query, final String uri) throws QueryException {
return parseMain(query, uri, null);
}
/**
* Parses the specified query.
* @param query query string
* @param uri base URI (may be {@code null})
* @param sc static context (may be {@code null})
* @return main module
* @throws QueryException query exception
*/
public MainModule parseMain(final String query, final String uri, final StaticContext sc)
throws QueryException {
info.query = query;
final QueryParser qp = new QueryParser(query, uri, this, sc);
root = qp.parseMain();
// updating expression: check if an updating expression is left in the expression tree
if(updating) updating = (qp.sc.mixUpdates && qp.sc.dynFuncCall) || root.expr.has(Flag.UPD);
return root;
}
/**
* Parses the specified module.
* @param query query string
* @param uri base URI (may be {@code null})
* @return name of module
* @throws QueryException query exception
*/
public LibraryModule parseLibrary(final String query, final String uri) throws QueryException {
info.query = query;
try {
return new QueryParser(query, uri, this, null).parseLibrary(true);
} finally {
// library module itself is not updating
updating = false;
}
}
/**
* Sets the main module (root expression).
* @param rt main module
*/
public void mainModule(final MainModule rt) {
root = rt;
updating = rt.expr.has(Flag.UPD);
}
/**
* Compiles and optimizes the expression.
* @throws QueryException query exception
*/
public void compile() throws QueryException {
checkStop();
if(compiled) return;
info.runtime = false;
final CompileContext cc = new CompileContext(this);
try {
// bind external variables of global option (if not assigned yet by other APIs)
final MainOptions mopts = context.options;
if(root != null && parent == null) {
for(final Entry<String, String> entry : mopts.toMap(MainOptions.BINDINGS).entrySet()) {
final String key = entry.getKey();
final Atm value = new Atm(entry.getValue());
if(key.isEmpty()) {
if(ctxItem == null) context(value, root.sc);
} else {
final QNm name = qname(key, root.sc);
if(!bindings.containsKey(name)) bind(name, value);
}
}
}
// set database options
options.compile();
// set tail call option after assigning database options
maxCalls = mopts.get(MainOptions.TAILCALLS);
// bind external variables
vars.bindExternal(this, bindings);
if(ctxItem != null) {
// evaluate initial expression
try {
ctxItem.comp(cc);
focus.value = ctxItem.cache(this).value();
} catch(final QueryException ex) {
// only {@link ParseExpr} instances may lead to a missing context
throw ex.error() == NOCTX_X ? CIRCCTX.get(ctxItem.info) : ex;
}
} else {
// cache the initial context nodes
final DBNodes nodes = context.current();
if(nodes != null) {
final String name = nodes.data().meta.name;
if(!context.perm(Perm.READ, name))
throw BASEX_PERMISSION_X_X.get(null, Perm.READ, name);
focus.value = resources.compile(nodes);
}
}
// if specified, convert context value to specified type
// [LW] should not be necessary
if(focus.value != null && root.sc != null && root.sc.contextType != null) {
focus.value = root.sc.contextType.promote(focus.value, null, this, root.sc, null, true);
}
try {
// compile the expression
if(root != null) QueryCompiler.compile(cc, root);
// compile global functions.
else funcs.compile(cc);
} catch(final StackOverflowError ex) {
Util.debug(ex);
throw BASEX_OVERFLOW.get(null, ex);
}
} finally {
info.runtime = true;
compiled = true;
}
}
/**
* Returns a result iterator.
* @return result iterator
* @throws QueryException query exception
*/
public Iter iter() throws QueryException {
compile();
try {
// no updates: iterate through results
if(!updating) return root.iter(this);
// cache results
ItemList items = root.cache(this);
// only perform updates if no parent context exists
if(updates != null && parent == null) {
final ItemList items2 = updates.items;
final HashSet<Data> datas = updates.prepare(this);
final StringList dbs = updates.databases();
materialize(items, datas, dbs);
materialize(items2, datas, dbs);
// invalidate current node set in context, apply updates
if(context.data() != null) context.invalidate();
updates.apply(this);
// append cached outputs
if(!items2.isEmpty()) {
if(items.isEmpty()) {
items = items2;
} else {
for(final Item item : items2) items.add(item);
}
}
}
return items.iter();
} catch(final StackOverflowError ex) {
Util.debug(ex);
throw BASEX_OVERFLOW.get(null);
}
}
/**
* Replaces all nodes that will be affected by updates by copies.
* @param items node cache
* @param datas data references
* @param dbs database names
* @throws QueryException query exception
*/
private void materialize(final ItemList items, final HashSet<Data> datas, final StringList dbs)
throws QueryException {
final long is = items.size();
for(int i = 0; i < is; i++) {
final Item item = items.get(i);
final Data data = item.data();
final boolean copy = data != null &&
(datas.contains(data) || !data.inMemory() && dbs.contains(data.meta.name));
final Item it = item.materialize(this, copy);
if(it == null) throw BASEX_FUNCTION_X.get(null, item);
items.set(i, it);
}
}
/**
* Checks if evaluation has been stopped and returns the next item of an iterator.
* @param iter iterator
* @return item or {@code null}
* @throws QueryException query exception
*/
public Item next(final Iter iter) throws QueryException {
checkStop();
return iter.next();
}
/**
* Returns a reference to the updates container.
* @return updates container
*/
public synchronized Updates updates() {
if(updates == null) updates = new Updates(false);
return updates;
}
@Override
public void addLocks() {
final Locks locks = jc().locks;
final LockList read = locks.reads, write = locks.writes;
read.add(readLocks);
write.add(writeLocks);
// use global locking if referenced databases cannot be statically determined
if(root == null || !root.databases(locks, this) ||
ctxItem != null && !ctxItem.databases(locks, this)) {
(updating ? write : read).addGlobal();
}
}
/**
* Assigns an external property.
* @param key key
* @param value value
*/
public void putProperty(final String key, final Object value) {
props.put(key, value);
}
/**
* Returns an external property.
* @param key key
* @return value (can be {@code null})
*/
public Object getProperty(final String key) {
return props.get(key);
}
/**
* Binds the context value, using the same rules as for
* {@link #bind(String, Object, String, StaticContext) binding variables}.
* @param value value to be bound
* @param type type (may be {@code null})
* @param sc static context
* @throws QueryException query exception
*/
public void context(final Object value, final String type, final StaticContext sc)
throws QueryException {
context(cast(value, type), sc);
}
/**
* Binds the context value.
* @param value value to be bound
* @param sc static context
*/
public void context(final Value value, final StaticContext sc) {
ctxItem = MainModule.get(new VarScope(sc), value, null, null, null);
}
/**
* Binds a value to a global variable. The specified type is interpreted as follows:
* <ul>
* <li> If {@code "json"} is specified, the value is converted according to the rules
* specified in {@link JsonXQueryConverter}.</li>
* <li> Otherwise, the type is cast to the specified XDM type.</li>
* </ul>
* If the value is an XQuery {@link Value}, it is directly assigned.
* Otherwise, it is cast to the XQuery data model, using a Java/XQuery mapping.
* @param name name of variable
* @param value value to be bound
* @param type type (may be {@code null})
* @param sc static context
* @throws QueryException query exception
*/
public void bind(final String name, final Object value, final String type, final StaticContext sc)
throws QueryException {
bind(name, cast(value, type), sc);
}
/**
* Binds a value to a global variable.
* @param name name of variable
* @param value value to be bound
* @param sc static context
* @throws QueryException query exception
*/
public void bind(final String name, final Value value, final StaticContext sc)
throws QueryException {
bind(qname(name, sc), value);
}
/**
* Binds a value to a global variable.
* @param name name of variable
* @param value value to be bound
*/
public void bind(final QNm name, final Value value) {
bindings.put(name, value);
}
/**
* Adds some evaluation info.
* @param string evaluation info
*/
public void evalInfo(final String string) {
QueryContext qc = this;
while(qc.parent != null) qc = qc.parent;
qc.info.evalInfo(string);
}
/**
* Returns info on query compilation and evaluation.
* @return query info
*/
public String info() {
return info.toString(this);
}
/**
* Returns query-specific or default serialization parameters.
* @return serialization parameters
*/
public SerializerOptions serParams() {
if(serParams == null) {
serParams = new SerializerOptions(context.options.get(MainOptions.SERIALIZER));
defaultOutput = root != null;
}
return serParams;
}
/**
* Returns the current full-text options. Creates a new instance if called for the first time.
* @return full-text options
*/
public FTOpt ftOpt() {
if(ftOpt == null) ftOpt = new FTOpt();
return ftOpt;
}
/**
* Assigns full-text options.
* @param opt full-text options
*/
public void ftOpt(final FTOpt opt) {
ftOpt = opt;
}
/**
* Creates and returns an XML query plan (expression tree) for this query.
* @return query plan
*/
public FElem plan() {
// only show root node if functions or variables exist
final FElem elem = new FElem(QueryText.QUERY_PLAN);
elem.add(QueryText.COMPILED, token(compiled));
elem.add(QueryText.UPDATING, token(updating));
if(root != null) {
for(final StaticScope ss : QueryCompiler.usedDecls(root)) ss.plan(elem);
root.plan(elem);
} else {
funcs.plan(elem);
vars.plan(elem);
}
return elem;
}
/**
* Indicates that the query contains updating expressions.
*/
public void updating() {
updating = true;
}
@Override
public void close() {
if(closed) return;
closed = true;
if(parent == null) {
// topmost query: close resources (opened by compile step)
resources.close();
} else {
// otherwise, adopt update reference (may have been initialized by sub query)
parent.updates = updates;
parent.popJob();
}
options.close();
}
@Override
public String shortInfo() {
return SAVE;
}
/**
* Caches and returns the result of the specified query. If all nodes are of the same database
* instance, the returned value will be of type {@link DBNodes}.
* @param max maximum number of results to cache (negative: return all values)
* @return resulting value
* @throws QueryException query exception
*/
Value cache(final int max) throws QueryException {
final int mx = max >= 0 ? max : Integer.MAX_VALUE;
// evaluates the query
final Iter iter = iter();
final ItemList items;
Item item;
// check if all results belong to the database of the input context
final Data data = resources.globalData();
if(defaultOutput && data != null) {
final IntList pres = new IntList();
while((item = next(iter)) != null && item.data() == data && pres.size() < mx) {
pres.add(((DBNode) item).pre());
}
// all results processed: return compact node sequence
final int ps = pres.size();
if(item == null || ps == mx) {
return ps == 0 ? Empty.SEQ : new DBNodes(data, pres.finish()).ftpos(ftPosData);
}
// otherwise, add nodes to standard iterator
items = new ItemList();
for(int p = 0; p < ps; p++) items.add(new DBNode(data, pres.get(p)));
items.add(item);
} else {
items = new ItemList();
}
// use standard iterator
while((item = next(iter)) != null && items.size() < mx) {
item.cache(null);
items.add(item);
}
return items.value();
}
/**
* Casts a value to the specified type.
* See {@link #bind(String, Object, String, StaticContext)} for more infos.
* @param value value to be cast
* @param type type (may be {@code null})
* @return cast value
* @throws QueryException query exception
*/
private Value cast(final Object value, final String type) throws QueryException {
final StaticContext sc = root != null ? root.sc : new StaticContext(this);
// String input
Object object = value;
if(object instanceof String) {
final String string = (String) object;
final StringList strings = new StringList(1);
// strings containing multiple items (value \1 ...)
if(string.indexOf('\1') == -1) {
strings.add(string);
} else {
strings.add(string.split("\1"));
object = strings.toArray();
}
// sub types overriding the global value (value \2 type)
if(string.indexOf('\2') != -1) {
final ValueBuilder vb = new ValueBuilder(this);
for(final String str : strings) {
final int i = str.indexOf('\2');
final String val = i == -1 ? str : str.substring(0, i);
final String tp = i == -1 ? type : str.substring(i + 1);
vb.add(cast(val, tp));
}
return vb.value();
}
}
// no type specified: return original value or convert Java object
if(type == null || type.isEmpty()) {
return object instanceof Value ? (Value) object : JavaFunction.toValue(object, this, sc);
}
// convert to json
if(type.equalsIgnoreCase(MainParser.JSON.name())) {
try {
final JsonParserOptions jp = new JsonParserOptions();
jp.set(JsonOptions.FORMAT, JsonFormat.XQUERY);
return JsonConverter.get(jp).convert(token(object.toString()), null);
} catch(final QueryIOException ex) {
throw ex.getCause();
}
}
// test for empty sequence
if(type.equals(QueryText.EMPTY_SEQUENCE + "()")) return Empty.SEQ;
// convert to the specified type
// [LW] type should be parsed properly
final QNm nm = new QNm(token(type.replaceAll("\\(.*?\\)$", "")), sc);
if(!nm.hasURI() && nm.hasPrefix()) throw NOURI_X.get(null, nm.string());
Type tp;
if(type.endsWith(")")) {
tp = nm.eq(AtomType.ITEM.name) ? AtomType.ITEM : NodeType.find(nm);
if(tp == null) tp = FuncType.find(nm);
} else {
tp = ListType.find(nm);
if(tp == null) tp = AtomType.find(nm, false);
}
if(tp == null) throw WHICHTYPE_X.get(null, type);
// cast XDM values
if(object instanceof Value) {
// cast single item
if(object instanceof Item) return tp.cast((Item) object, this, sc, null);
// cast sequence
final Value vl = (Value) object;
final ValueBuilder vb = new ValueBuilder(this);
final BasicIter<?> iter = vl.iter();
for(Item item; (item = iter.next()) != null;) vb.add(tp.cast(item, this, sc, null));
return vb.value();
}
if(object instanceof String[]) {
// cast string array
final ValueBuilder vb = new ValueBuilder(this);
for(final String string : (String[]) object) vb.add(tp.cast(string, this, sc, null));
return vb.value();
}
// cast any other object to XDM
return tp.cast(object, this, sc, null);
}
/**
* Gets the value currently bound to the given variable.
* @param var variable
* @return bound value
*/
public Value get(final Var var) {
return stack.get(var);
}
/**
* Binds an expression to a local variable.
* @param var variable
* @param val expression to be bound
* @throws QueryException exception
*/
public void set(final Var var, final Value val) throws QueryException {
stack.set(var, val, this);
}
/**
* Registers a tail-called function and its arguments to this query context.
* @param fn function to call
* @param arg arguments to pass to {@code fn}
*/
public void registerTailCall(final XQFunction fn, final Value[] arg) {
tailFunc = fn;
args = arg;
}
/**
* Returns and clears the currently registered tail-call function.
* @return function to call if present, {@code null} otherwise
*/
public XQFunction pollTailCall() {
final XQFunction fn = tailFunc;
tailFunc = null;
return fn;
}
/**
* Returns and clears registered arguments of a tail-called function.
* @return argument values if a tail call was registered, {@code null} otherwise
*/
public Value[] pollTailArgs() {
final Value[] as = args;
args = null;
return as;
}
/**
* Initializes the static date and time context of a query if not done yet.
* @return self reference
* @throws QueryException query exception
*/
public QueryDateTime dateTime() throws QueryException {
if(dateTime == null) dateTime = new QueryDateTime();
return dateTime;
}
@Override
public String toString() {
return root != null ? QueryInfo.usedDecls(root) : info.query;
}
/**
* Converts the specified variable name to a QName.
* @param name name of variable
* @param sc static context
* @return QName
* @throws QueryException query context
*/
private static QNm qname(final String name, final StaticContext sc) throws QueryException {
return QNm.resolve(token(Strings.startsWith(name, '$') ? name.substring(1) : name), sc);
}
}
|
package net.minecraftforge.oredict;
import java.util.ArrayList;
import java.util.HashMap;
import net.minecraft.src.Block;
import net.minecraft.src.IRecipe;
import net.minecraft.src.InventoryCrafting;
import net.minecraft.src.Item;
import net.minecraft.src.ItemStack;
import net.minecraft.src.ShapedRecipes;
import net.minecraft.src.World;
public class ShapedOreRecipe implements IRecipe
{
//Added in for future ease of change, but hard coded for now.
private static final int MAX_CRAFT_GRID_WIDTH = 3;
private static final int MAX_CRAFT_GRID_HEIGHT = 3;
private ItemStack output = null;
private Object[] input = null;
private int width = 0;
private int height = 0;
private boolean mirrored = true;
public ShapedOreRecipe(Block result, Object... recipe){ this(new ItemStack(result), recipe); }
public ShapedOreRecipe(Item result, Object... recipe){ this(new ItemStack(result), recipe); }
public ShapedOreRecipe(ItemStack result, Object... recipe)
{
output = result.copy();
String shape = "";
int idx = 0;
if (recipe[idx] instanceof Boolean)
{
mirrored = (Boolean)recipe[idx];
if (recipe[idx+1] instanceof Object[])
{
recipe = (Object[])recipe[idx+1];
}
else
{
idx = 1;
}
}
if (recipe[idx] instanceof String[])
{
String[] parts = ((String[])recipe[idx++]);
for (String s : parts)
{
width = s.length();
shape += s;
}
height = parts.length;
}
else
{
while (recipe[idx] instanceof String)
{
String s = (String)recipe[idx++];
shape += s;
width = s.length();
height++;
}
}
if (width * height != shape.length())
{
String ret = "Invalid shaped ore recipe: ";
for (Object tmp : recipe)
{
ret += tmp + ", ";
}
ret += output;
throw new RuntimeException(ret);
}
HashMap<Character, Object> itemMap = new HashMap<Character, Object>();
for (; idx < recipe.length; idx += 2)
{
Character chr = (Character)recipe[idx];
Object in = recipe[idx + 1];
Object val = null;
if (in instanceof ItemStack)
{
itemMap.put(chr, ((ItemStack)in).copy());
}
else if (in instanceof Item)
{
itemMap.put(chr, new ItemStack((Item)in));
}
else if (in instanceof Block)
{
itemMap.put(chr, new ItemStack((Block)in, 1, -1));
}
else if (in instanceof String)
{
itemMap.put(chr, OreDictionary.getOres((String)in));
}
else
{
String ret = "Invalid shaped ore recipe: ";
for (Object tmp : recipe)
{
ret += tmp + ", ";
}
ret += output;
throw new RuntimeException(ret);
}
}
input = new Object[width * height];
int x = 0;
for (char chr : shape.toCharArray())
{
input[x++] = itemMap.get(chr);
}
}
@Override
public ItemStack getCraftingResult(InventoryCrafting var1){ return output.copy(); }
@Override
public int getRecipeSize(){ return input.length; }
@Override
public ItemStack getRecipeOutput(){ return output; }
@Override
public boolean matches(InventoryCrafting inv, World world)
{
for (int x = 0; x <= MAX_CRAFT_GRID_WIDTH - width; x++)
{
for (int y = 0; y <= MAX_CRAFT_GRID_HEIGHT - height; ++y)
{
if (checkMatch(inv, x, y, true))
{
return true;
}
if (mirrored && checkMatch(inv, x, y, false))
{
return true;
}
}
}
return false;
}
private boolean checkMatch(InventoryCrafting inv, int startX, int startY, boolean mirror)
{
for (int x = 0; x < MAX_CRAFT_GRID_WIDTH; x++)
{
for (int y = 0; y < MAX_CRAFT_GRID_HEIGHT; y++)
{
int subX = x - startX;
int subY = y - startY;
Object target = null;
if (subX >= 0 && subY >= 0 && subX < width && subY < height)
{
if (mirror)
{
target = input[width - subX - 1 + subY * width];
}
else
{
target = input[subX + subY * width];
}
}
ItemStack slot = inv.getStackInRowAndColumn(x, y);
if (target instanceof ItemStack)
{
if (!checkItemEquals((ItemStack)target, slot))
{
return false;
}
}
else if (target instanceof ArrayList)
{
boolean matched = false;
for (ItemStack item : (ArrayList<ItemStack>)target)
{
matched = matched || checkItemEquals(item, slot);
}
if (!matched)
{
return false;
}
}
else if (target == null && slot != null)
{
return false;
}
}
}
return true;
}
private boolean checkItemEquals(ItemStack target, ItemStack input)
{
if (input == null && target != null || input != null && target == null)
{
return false;
}
return (target.itemID == input.itemID && (target.getItemDamage() == -1 || target.getItemDamage() == input.getItemDamage()));
}
public ShapedOreRecipe setMirrored(boolean mirror)
{
mirrored = mirror;
return this;
}
}
|
package com.gooddata.util;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import au.com.bytecode.opencsv.CSVReader;
import au.com.bytecode.opencsv.CSVWriter;
/**
* GoodData
*
* @author zd <zd@gooddata.com>
* @version 1.0
*/
public class StringUtil {
private static String[] DISCARD_CHARS = {"\"", " ", "!", "?", "%", "&", "
"$", "%", ",", "(", ")", "", "", "","@", "{" ,"}",
"[", "]","\\"};
private static String[] INVALID_CSV_HEADER_CHARS = {"\"", "'", "!", "?", "%", "&", "
"$", "%", ",", "(", ")", "", "", "","@", "{" ,"}",
"[", "]","\\"};
private static String[] WHITESPACE = {"\n","\t"};
private static String[][] DATE_FORMAT_CONVERSION = {{"MM","%m"},{"yyyy","%Y"},{"yy","%y"},{"dd","%d"}};
/**
* Formats a string as identifier
* Currently only converts to the lowercase and replace spaces
* @param s the string to convert to identifier
* @return converted string
*/
public static String formatShortName(String s) {
for ( String r : DISCARD_CHARS ) {
s = s.replace(r,"");
}
s.replaceAll("^[0-9]*", "");
return s.toLowerCase().trim();
}
/**
* Checks if the string contains an character that shoukd be stripped from identifier name
* @param s the checked
* @return true if there are invalid chars, false otherwise
*/
public static boolean containsInvvalidIdentifierChar(String s) {
for ( String r : DISCARD_CHARS )
if(s.indexOf(r)>=0)
return true;
return false;
}
/**
* Remove whitespace
* Currently only converts to the lowercase and replace spaces
* @param s the string to process
* @return converted string
*/
public static String removeWhitespace(String s) {
for ( String r : WHITESPACE ) {
s = s.replace(r,"");
}
return s;
}
/**
* Formats a string as title
* Currently does nothing TBD
* @param s the string to convert to a title
* @return converted string
*/
public static String formatLongName(String s) {
return s.trim();
}
/**
* Formats a CSV header
* @param s the string to convert to identifier
* @return converted string
*/
public static String csvHeaderToIdentifier(String s) {
for ( String r : INVALID_CSV_HEADER_CHARS ) {
s = s.replace(r,"");
}
return s.toLowerCase().trim();
}
/**
* Formats a CSV header
* @param s the string to convert to identifier
* @return converted string
*/
public static String csvHeaderToTitle(String s) {
for ( String r : INVALID_CSV_HEADER_CHARS ) {
s = s.replace(r,"");
}
return s.trim();
}
/**
* Converts the Java date format string to the MySQL format
* @param dateFormat Java date format
* @return MySQL date format
*/
public static String convertJavaDateFormatToMySql(String dateFormat) {
for(int i=0; i < DATE_FORMAT_CONVERSION.length; i++)
dateFormat = dateFormat.replace(DATE_FORMAT_CONVERSION[i][0],
DATE_FORMAT_CONVERSION[i][1]);
return dateFormat;
}
/**
* Converts a {@link Collection} to a <tt>separator<tt> separated string
*
* @param separator
* @param list
* @return <tt>separator<tt> separated string version of the given list
*/
public static String join(String separator, Collection<String> list) {
return join(separator, list, null);
}
/**
* Converts a {@link Collection} to a <tt>separator<tt> separated string.
* If the <tt>replacement</tt> parameter is not null, it is used to populate
* the result string instead of list elements.
*
* @param separator
* @param list
* @param replacement
* @return <tt>separator<tt> separated string version of the given list
*/
public static String join(String separator, Collection<String> list, String replacement) {
StringBuffer sb = new StringBuffer();
boolean first = true;
for (final String s : list) {
if (first)
first = false;
else
sb.append(separator);
sb.append(replacement == null ? s : replacement);
}
return sb.toString();
}
/**
* Parse CSV line
* @param elements CSV line
* @return alements as String[]
*/
public static List<String> parseLine(String elements) {
if (elements == null) {
return new ArrayList<String>();
}
// TODO proper CSV parsing
String[] result = elements.trim().split("\\s*,\\s*");
return Arrays.asList(result);
}
public static void normalize(File in, File out, int skipRows) throws IOException {
CSVReader csvIn = new CSVReader(new FileReader(in));
CSVWriter csvOut = new CSVWriter(new FileWriter(out));
normalize(csvIn, csvOut, skipRows);
csvOut.close();
}
public static void normalize(CSVReader in, CSVWriter out, int skipRows) throws IOException {
String[] nextLine;
int i = 0;
while ((nextLine = in.readNext()) != null) {
if (i >= skipRows) {
out.writeNext(nextLine);
}
i++;
}
}
}
|
package org.neo4j.api.core;
import org.neo4j.impl.transaction.TransactionUtil;
/**
* A utility class to manage transactions in Neo. All operations that work with
* the node space (even read operations) must be wrapped in a transaction.
* Fortunately, the Transaction class makes this very easy. Here's the idiomatic
* use of transactions in Neo:<pre><code> Transaction tx = Transaction.begin();
* try
* {
* ... // any operation that works with the node space
* tx.success();
* }
* finally
* {
* tx.finish();
* } </code></pre>
* <p>
* Let's walk through this example line by line. First we retrieve a Transaction
* object by invoking the static {@link #begin()} factory method. This creates
* a new Transaction instance which has internal state to keep track of whether
* the current transaction is successful. Then we wrap all operations that work
* with the node space in a try-finally block. At the end of the block, we
* invoke the {@link #finish() tx.success()} method to indicate that the
* transaction is successful. As we exit the block, the finally clause will
* kick in and {@link #finish() tx.finish} will commit the transaction if the
* internal state indicates success or else mark it for rollback.
* <p>
* If an exception is raised in the try-block, <code>tx.success()</code> will
* never be invoked and the internal state of the transaction object will cause
* <code>tx.finish()</code> to roll back the transaction. This is very
* important: unless {@link #success()} is invoked, the transaction will fail
* upon {@link #finish()}. A transaction can be explicitly marked for rollback
* by invoking the {@link #failure() tx.failure()} method.
*/
public class Transaction
{
private static final Transaction PLACEBO_TRANSACTION = new Transaction()
{
@Override
public void failure()
{
TransactionUtil.markAsRollbackOnly();
}
@Override
public void finish()
{
// Do nothing
}
@Override
public void success()
{
// Do nothing
}
};
private boolean success = false;
/**
* Private constructor.
*/
private Transaction()
{
}
/**
* Starts a new transaction.
* @return a transaction object representing the current transaction
*/
public static Transaction begin()
{
if ( TransactionUtil.beginTx() )
{
return new Transaction();
}
else
{
return PLACEBO_TRANSACTION;
}
}
/**
* Marks this transaction as failed, which means that it will inexplicably be
* rolled back upon invocation of {@link #finish()}. Once this method has
* been invoked, it doesn't matter how many times {@link #success()} is
* invoked -- the transaction will still be rolled back.
*/
public void failure()
{
this.success = false;
TransactionUtil.markAsRollbackOnly();
}
/**
* Marks this transaction as successful, which means that it will be
* commited upon invocation of {@link #finish()} unless {@link #failure()}
* has or will be invoked before then.
*/
public void success()
{
success = true;
}
/**
* Commits or marks this transaction for rollback, depending on whether
* {@link #success()} or {@link #failure()} has been previously invoked.
*/
public void finish()
{
TransactionUtil.finishTx( success, true );
}
}
|
package cgeo.geocaching.utils;
import cgeo.geocaching.R;
import cgeo.geocaching.activity.ActivityMixin;
import cgeo.geocaching.network.Network;
import org.apache.commons.lang3.StringUtils;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
/**
* Utilities used for translating
*/
public final class TranslationUtils {
private static final String TRANSLATION_WEBSITE = "https://translate.google.com/m/translate";
private static final String TRANSLATION_FORCE_CLASSIC_MODE = "?vi=c";
private static final String TRANSLATION_AUTO_SELECT = "#auto";
private static final String TRANSLATION_FIELD_SEPARATOR = "|";
private static final int TRANSLATION_TEXT_LENGTH_WARN = 500;
private static final String TRANSLATION_APP = "com.google.android.apps.translate";
private TranslationUtils() {
// utility class
}
/**
* Build a URI for Google Translate.
*
* @param toLang
* The two-letter lowercase ISO language codes as defined by ISO 639-1
* @param text
* The text to be translated
* @return URI ready to be parsed
*/
private static String buildTranslationURI(final String toLang, final String text) {
String content = Network.encode(text);
// the app works better without the "+", the website works better with "+", therefore assume using the app if installed
if (ProcessUtils.isLaunchable(TRANSLATION_APP)) {
content = StringUtils.replace(content, "+", "%20");
}
return TRANSLATION_WEBSITE + TRANSLATION_FORCE_CLASSIC_MODE + TRANSLATION_AUTO_SELECT + TRANSLATION_FIELD_SEPARATOR + toLang + TRANSLATION_FIELD_SEPARATOR + content;
}
/**
* Send Intent for Google Translate. Can be caught by Google Translate App or browser.
*
* @param activity
* The activity starting the process
* @param toLang
* The two-letter lowercase ISO language codes as defined by ISO 639-1
* @param text
* The text to be translated
*/
public static void startActivityTranslate(final Activity activity, final String toLang, final String text) {
if (text.length() > TRANSLATION_TEXT_LENGTH_WARN) {
ActivityMixin.showToast(activity, R.string.translate_length_warning);
}
activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(buildTranslationURI(toLang, text))));
}
}
|
package aQute.launchpad;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNotNull;
import java.io.Closeable;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean;
import org.junit.Test;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
public class Manual {
LaunchpadBuilder builder = new LaunchpadBuilder().runfw("org.apache.felix.framework");
@Service
BundleContext context;
@Test
public void quickStart() throws Exception {
try (Launchpad launchpad = builder.create()
.inject(this)) {
assertNotNull(context);
}
}
public static class Activator implements BundleActivator {
@Override
public void start(BundleContext context) throws Exception {
System.out.println("Hello World");
}
@Override
public void stop(BundleContext context) throws Exception {
System.out.println("Goodbye World");
}
}
@Test
public void activator() throws Exception {
try (Launchpad launchpad = builder.create()
.inject(this)) {
Bundle b = launchpad.bundle()
.bundleActivator(Activator.class)
.start();
assertThat(launchpad.isActive(b)).isTrue();
}
}
interface Foo {
void bar();
}
@Test
public void services() throws Exception {
try (Launchpad launchpad = builder.create()
.debug()
.report()) {
ServiceRegistration<Foo> register = launchpad.register(Foo.class, () -> {
});
Optional<Foo> s = launchpad.waitForService(Foo.class, 100);
assertThat(s.isPresent()).isTrue();
register.unregister();
s = launchpad.waitForService(Foo.class, 100);
assertThat(s.isPresent()).isFalse();
Optional<Foo> service = launchpad.getService(Foo.class);
assertThat(service.isPresent()).isFalse();
}
}
@Test
public void inject() throws Exception {
try (Launchpad launchpad = builder.create()) {
ServiceRegistration<Foo> register = launchpad.register(Foo.class, () -> {
});
class I {
@Service
Foo foo;
@Service
Bundle bundles[];
@SuppressWarnings("hiding")
@Service
BundleContext context;
}
I inject = new I();
launchpad.inject(inject);
assertThat(inject.bundles).isNotEmpty();
register.unregister();
}
}
interface Bar {
void bar();
}
@Component
public static class C {
@Reference
Bar bar;
@Activate
void activate() {
bar.bar();
}
}
@Test
public void component() throws Exception {
try (Launchpad launchpad = builder.bundles("org.apache.felix.log")
.bundles("org.apache.felix.scr")
.bundles("org.apache.felix.configadmin")
.create()) {
launchpad.component(C.class);
AtomicBoolean called = new AtomicBoolean(false);
launchpad.register(Bar.class, () -> called.set(true));
assertThat(called.get()).isTrue();
}
}
@Test
public void debug() throws Exception {
try (Launchpad launchpad = builder.bundles("org.apache.felix.log")
.bundles("org.apache.felix.scr")
.bundles("org.apache.felix.configadmin")
.debug()
.create()) {
}
}
@Test
public void gogo() throws Exception {
// try (Launchpad launchpad = builder.gogo()
// .debug()
// .create()) {
// // Thread.sleep(100000);
}
@Test
public void bndrun() throws Exception {
// try (Launchpad launchpad = builder.bndrun("showit.bndrun")
// .create()) {
// // Thread.sleep(100000);
}
@Test
public void bundles() throws Exception {
try (Launchpad launchpad = builder.create()) {
Bundle b = launchpad.bundle()
.header("FooBar", "1")
.install();
String string = b.getHeaders()
.get("FooBar");
assertThat(string).isEqualTo("1");
}
}
/**
* Hide a service
*/
@Test
public void testHiding() throws Exception {
try (Launchpad fw = builder.runfw("org.apache.felix.framework")
.nostart()
.create()
.inject(this)) {
@SuppressWarnings("resource")
Closeable hide = fw.hide(String.class);
fw.start();
boolean isHidden = fw.getServices(String.class)
.isEmpty();
assertThat(isHidden).isTrue();
fw.framework.getBundleContext()
.registerService(String.class, "fw", null);
isHidden = fw.getServices(String.class)
.isEmpty();
assertThat(isHidden).isTrue();
ServiceRegistration<String> visibleToAllViaTestbundle = fw.register(String.class, "Hello");
assertThat(fw.getServices(String.class)).containsOnly("Hello");
visibleToAllViaTestbundle.unregister();
isHidden = fw.getServices(String.class)
.isEmpty();
assertThat(isHidden).isTrue();
hide.close();
assertThat(fw.getServices(String.class)).containsOnly("fw");
}
}
@Test
public void testHidingViaBuilder() throws Exception {
try (Launchpad fw = builder.runfw("org.apache.felix.framework")
.hide(String.class)
.create()) {
boolean isHidden = fw.getServices(String.class)
.isEmpty();
assertThat(isHidden).isTrue();
fw.framework.getBundleContext()
.registerService(String.class, "fw", null);
isHidden = fw.getServices(String.class)
.isEmpty();
assertThat(isHidden).isTrue();
ServiceRegistration<String> visibleToAllViaTestbundle = fw.register(String.class, "Hello");
assertThat(fw.getServices(String.class)).containsOnly("Hello");
visibleToAllViaTestbundle.unregister();
isHidden = fw.getServices(String.class)
.isEmpty();
assertThat(isHidden).isTrue();
}
}
}
|
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.jcache.JCacheGaugeSet;
import javax.cache.Cache;
import javax.cache.CacheManager;
import javax.cache.Caching;
import javax.cache.spi.CachingProvider;
import static org.assertj.core.api.Assertions.assertThat;
public class JCacheGaugeSetTest {
private MetricRegistry registry;
private Cache<Object, Object> myCache;
private Cache<Object, Object> myOtherCache;
private CacheManager cacheManager;
@Before
public void setUp() throws Exception {
CachingProvider provider = Caching.getCachingProvider();
cacheManager = provider.getCacheManager(
getClass().getResource("ehcache.xml").toURI(),
getClass().getClassLoader());
myCache = cacheManager.getCache("myCache");
myOtherCache = cacheManager.getCache("myOtherCache");
registry = new MetricRegistry();
registry.register("jcache.statistics", new JCacheGaugeSet());
}
@Test
public void measuresGauges() throws Exception {
myOtherCache.get("woo");
assertThat(registry.getGauges().get("jcache.statistics.myOtherCache.cache-misses").getValue())
.isEqualTo(1L);
myCache.get("woo");
assertThat(registry.getGauges().get("jcache.statistics.myCache.cache-misses").getValue())
.isEqualTo(1L);
assertThat(registry.getGauges().get("jcache.statistics.myCache.cache-hits").getValue())
.isEqualTo(0L);
assertThat(registry.getGauges().get("jcache.statistics.myCache.cache-gets").getValue())
.isEqualTo(1L);
myCache.put("woo", "whee");
myCache.get("woo");
assertThat(registry.getGauges().get("jcache.statistics.myCache.cache-puts").getValue())
.isEqualTo(1L);
assertThat(registry.getGauges().get("jcache.statistics.myCache.cache-hits").getValue())
.isEqualTo(1L);
assertThat(registry.getGauges().get("jcache.statistics.myCache.cache-hit-percentage").getValue())
.isEqualTo(50.0f);
assertThat(registry.getGauges().get("jcache.statistics.myCache.cache-miss-percentage").getValue())
.isEqualTo(50.0f);
assertThat(registry.getGauges().get("jcache.statistics.myCache.cache-gets").getValue())
.isEqualTo(2L);
// cache size being 1, eviction occurs after this line
myCache.put("woo2", "whoza");
assertThat(registry.getGauges().get("jcache.statistics.myCache.cache-evictions").getValue())
.isEqualTo(1L);
myCache.remove("woo2");
assertThat((Float)registry.getGauges().get("jcache.statistics.myCache.average-get-time").getValue())
.isGreaterThan(0.0f);
assertThat((Float)registry.getGauges().get("jcache.statistics.myCache.average-put-time").getValue())
.isGreaterThan(0.0f);
assertThat((Float)registry.getGauges().get("jcache.statistics.myCache.average-remove-time").getValue())
.isGreaterThan(0.0f);
}
@After
public void tearDown() throws Exception {
cacheManager.destroyCache("myCache");
cacheManager.destroyCache("myOtherCache");
cacheManager.close();
}
}
|
package net.md_5.bungee.protocol;
import com.google.common.base.Preconditions;
import gnu.trove.map.TObjectIntMap;
import gnu.trove.map.hash.TObjectIntHashMap;
import java.lang.reflect.Constructor;
import java.util.Arrays;
import java.util.List;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import net.md_5.bungee.protocol.packet.Chat;
import net.md_5.bungee.protocol.packet.ClientSettings;
import net.md_5.bungee.protocol.packet.EncryptionRequest;
import net.md_5.bungee.protocol.packet.EncryptionResponse;
import net.md_5.bungee.protocol.packet.Handshake;
import net.md_5.bungee.protocol.packet.KeepAlive;
import net.md_5.bungee.protocol.packet.Kick;
import net.md_5.bungee.protocol.packet.Login;
import net.md_5.bungee.protocol.packet.LoginRequest;
import net.md_5.bungee.protocol.packet.LoginSuccess;
import net.md_5.bungee.protocol.packet.PingPacket;
import net.md_5.bungee.protocol.packet.PlayerListHeaderFooter;
import net.md_5.bungee.protocol.packet.PlayerListItem;
import net.md_5.bungee.protocol.packet.PluginMessage;
import net.md_5.bungee.protocol.packet.Respawn;
import net.md_5.bungee.protocol.packet.ScoreboardDisplay;
import net.md_5.bungee.protocol.packet.ScoreboardObjective;
import net.md_5.bungee.protocol.packet.ScoreboardScore;
import net.md_5.bungee.protocol.packet.SetCompression;
import net.md_5.bungee.protocol.packet.StatusRequest;
import net.md_5.bungee.protocol.packet.StatusResponse;
import net.md_5.bungee.protocol.packet.TabCompleteRequest;
import net.md_5.bungee.protocol.packet.TabCompleteResponse;
import net.md_5.bungee.protocol.packet.Team;
import net.md_5.bungee.protocol.packet.Title;
public enum Protocol
{
// Undef
HANDSHAKE
{
{
TO_SERVER.registerPacket( 0x00, Handshake.class );
}
},
GAME
{
{
TO_CLIENT.registerPacket( 0x00, KeepAlive.class );
TO_CLIENT.registerPacket( 0x01, Login.class );
TO_CLIENT.registerPacket( 0x02, Chat.class );
TO_CLIENT.registerPacket( 0x07, Respawn.class );
TO_CLIENT.registerPacket( 0x38, PlayerListItem.class );
TO_CLIENT.registerPacket( 0x3A, TabCompleteResponse.class );
TO_CLIENT.registerPacket( 0x3B, ScoreboardObjective.class );
TO_CLIENT.registerPacket( 0x3C, ScoreboardScore.class );
TO_CLIENT.registerPacket( 0x3D, ScoreboardDisplay.class );
TO_CLIENT.registerPacket( 0x3E, Team.class );
TO_CLIENT.registerPacket( 0x3F, PluginMessage.class );
TO_CLIENT.registerPacket( 0x40, Kick.class );
TO_CLIENT.registerPacket( 0x45, Title.class );
TO_CLIENT.registerPacket( 0x46, SetCompression.class );
TO_CLIENT.registerPacket( 0x47, PlayerListHeaderFooter.class );
TO_SERVER.registerPacket( 0x00, KeepAlive.class );
TO_SERVER.registerPacket( 0x01, Chat.class );
TO_SERVER.registerPacket( 0x14, TabCompleteRequest.class );
TO_SERVER.registerPacket( 0x15, ClientSettings.class );
TO_SERVER.registerPacket( 0x17, PluginMessage.class );
}
},
STATUS
{
{
TO_CLIENT.registerPacket( 0x00, StatusResponse.class );
TO_CLIENT.registerPacket( 0x01, PingPacket.class );
TO_SERVER.registerPacket( 0x00, StatusRequest.class );
TO_SERVER.registerPacket( 0x01, PingPacket.class );
}
},
LOGIN
{
{
TO_CLIENT.registerPacket( 0x00, Kick.class );
TO_CLIENT.registerPacket( 0x01, EncryptionRequest.class );
TO_CLIENT.registerPacket( 0x02, LoginSuccess.class );
TO_CLIENT.registerPacket( 0x03, SetCompression.class );
TO_SERVER.registerPacket( 0x00, LoginRequest.class );
TO_SERVER.registerPacket( 0x01, EncryptionResponse.class );
}
};
public static final int MAX_PACKET_ID = 0xFF;
public static List<Integer> supportedVersions = Arrays.asList(
ProtocolConstants.MINECRAFT_1_7_2,
ProtocolConstants.MINECRAFT_1_7_6,
ProtocolConstants.MINECRAFT_1_8
);
public final DirectionData TO_SERVER = new DirectionData( ProtocolConstants.Direction.TO_SERVER );
public final DirectionData TO_CLIENT = new DirectionData( ProtocolConstants.Direction.TO_CLIENT );
@RequiredArgsConstructor
public class DirectionData
{
@Getter
private final ProtocolConstants.Direction direction;
private final TObjectIntMap<Class<? extends DefinedPacket>> packetMap = new TObjectIntHashMap<>( MAX_PACKET_ID );
private final Class<? extends DefinedPacket>[] packetClasses = new Class[ MAX_PACKET_ID ];
private final Constructor<? extends DefinedPacket>[] packetConstructors = new Constructor[ MAX_PACKET_ID ];
public boolean hasPacket(int id)
{
return id >= 0 && id < MAX_PACKET_ID && packetConstructors[id] != null;
}
public final DefinedPacket createPacket(int id)
{
if ( id > MAX_PACKET_ID )
{
throw new BadPacketException( "Packet with id " + id + " outside of range " );
}
if ( packetConstructors[id] == null )
{
throw new BadPacketException( "No packet with id " + id );
}
try
{
return packetConstructors[id].newInstance();
} catch ( ReflectiveOperationException ex )
{
throw new BadPacketException( "Could not construct packet with id " + id, ex );
}
}
protected final void registerPacket(int id, Class<? extends DefinedPacket> packetClass)
{
try
{
packetConstructors[id] = packetClass.getDeclaredConstructor();
} catch ( NoSuchMethodException ex )
{
throw new BadPacketException( "No NoArgsConstructor for packet class " + packetClass );
}
packetClasses[id] = packetClass;
packetMap.put( packetClass, id );
}
protected final void unregisterPacket(int id)
{
packetMap.remove( packetClasses[id] );
packetClasses[id] = null;
packetConstructors[id] = null;
}
final int getId(Class<? extends DefinedPacket> packet)
{
Preconditions.checkArgument( packetMap.containsKey( packet ), "Cannot get ID for packet " + packet );
return packetMap.get( packet );
}
}
}
|
package com.wavefront.agent;
import com.google.common.annotations.VisibleForTesting;
import com.wavefront.common.Clock;
import com.yammer.metrics.Metrics;
import com.yammer.metrics.core.Counter;
import com.yammer.metrics.core.Histogram;
import com.yammer.metrics.core.MetricName;
import org.apache.commons.lang.StringUtils;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nullable;
import sunnylabs.report.ReportPoint;
/**
* Adds all graphite strings to a working list, and batches them up on a set schedule (100ms) to be sent (through the
* daemon's logic) up to the collector on the server side.
*/
public class PointHandlerImpl implements PointHandler {
private static final Logger logger = Logger.getLogger(PointHandlerImpl.class.getCanonicalName());
private static final Random random = new Random();
// What types of data should be validated and sent to the cloud?
public static final String VALIDATION_NO_VALIDATION = "NO_VALIDATION"; // Validate nothing
public static final String VALIDATION_NUMERIC_ONLY = "NUMERIC_ONLY"; // Validate/send numerics; block text
private final Counter illegalCharacterPoints;
private final Histogram receivedPointLag;
private final String validationLevel;
private final int port;
protected final int blockedPointsPerBatch;
protected final PostPushDataTimedTask[] sendDataTasks;
public PointHandlerImpl(final int port,
final String validationLevel,
final int blockedPointsPerBatch,
final PostPushDataTimedTask[] sendDataTasks) {
this.validationLevel = validationLevel;
this.port = port;
this.blockedPointsPerBatch = blockedPointsPerBatch;
this.illegalCharacterPoints = Metrics.newCounter(new MetricName("point", "", "badchars"));
this.receivedPointLag = Metrics.newHistogram(
new MetricName("points." + String.valueOf(port) + ".received", "", "lag"));
this.sendDataTasks = sendDataTasks;
}
@Override
public void reportPoint(ReportPoint point, @Nullable String debugLine) {
final PostPushDataTimedTask randomPostTask = getRandomPostTask();
try {
Object pointValue = point.getValue();
validateHost(point.getHost());
if (point.getMetric().length() >= 1024) {
throw new IllegalArgumentException("WF-301: Metric name is too long: " + point.getMetric());
}
if (!charactersAreValid(point.getMetric())) {
illegalCharacterPoints.inc();
String errorMessage = "WF-400 " + port + ": Point metric has illegal character (" +
(debugLine == null ? pointToString(point) : debugLine) + ")";
throw new IllegalArgumentException(errorMessage);
}
if (!annotationKeysAreValid(point)) {
String errorMessage = "WF-401 " + port + ": Point annotation key has illegal character (" +
(debugLine == null ? pointToString(point) : debugLine) + ")";
throw new IllegalArgumentException(errorMessage);
}
// Each tag of the form "k=v" must be < 256
for (Map.Entry<String, String> tag : point.getAnnotations().entrySet()) {
if (tag.getKey().length() + tag.getValue().length() >= 255) {
throw new IllegalArgumentException("Tag too long: " + tag.getKey() + "=" + tag.getValue() + "(" +
(debugLine == null ? pointToString(point) : debugLine) + ")");
}
}
if ((validationLevel != null) && (!validationLevel.equals(VALIDATION_NO_VALIDATION))) {
// Is it the right type of point?
switch (validationLevel) {
case VALIDATION_NUMERIC_ONLY:
if (!(pointValue instanceof Long) && !(pointValue instanceof Double)) {
String errorMessage = "WF-403 " + port + ": Was not long/double object (" +
(debugLine == null ? pointToString(point) : debugLine) + ")";
throw new IllegalArgumentException(errorMessage);
}
break;
}
randomPostTask.addPoint(pointToString(point));
receivedPointLag.update(Clock.now() - point.getTimestamp());
} else {
// No validation was requested by user; send forward.
randomPostTask.addPoint(pointToString(point));
receivedPointLag.update(Clock.now() - point.getTimestamp());
}
} catch (IllegalArgumentException e) {
this.handleBlockedPoint(e.getMessage());
} catch (Exception ex) {
logger.log(Level.SEVERE, "WF-500 Uncaught exception when handling point (" +
(debugLine == null ? pointToString(point) : debugLine) + ")", ex);
}
}
@Override
public void reportPoints(List<ReportPoint> points) {
for (final ReportPoint point : points) {
reportPoint(point, null);
}
}
public PostPushDataTimedTask getRandomPostTask() {
// return the task with the lowest number of pending points and, if possible, not currently flushing to retry queue
long min = Long.MAX_VALUE;
PostPushDataTimedTask randomPostTask = null;
PostPushDataTimedTask firstChoicePostTask = null;
for (int i = 0; i < this.sendDataTasks.length; i++) {
long pointsToSend = this.sendDataTasks[i].getNumPointsToSend();
if (pointsToSend < min) {
min = pointsToSend;
randomPostTask = this.sendDataTasks[i];
if (!this.sendDataTasks[i].getFlushingToQueueFlag()) {
firstChoicePostTask = this.sendDataTasks[i];
}
}
}
return firstChoicePostTask == null ? randomPostTask : firstChoicePostTask;
}
@Override
public void handleBlockedPoint(@Nullable String pointLine) {
final PostPushDataTimedTask randomPostTask = getRandomPostTask();
if (pointLine != null && randomPostTask.getBlockedSampleSize() < this.blockedPointsPerBatch) {
randomPostTask.addBlockedSample(pointLine);
}
randomPostTask.incrementBlockedPoints();
}
@VisibleForTesting
static boolean annotationKeysAreValid(ReportPoint point) {
for (String key : point.getAnnotations().keySet()) {
if (!charactersAreValid(key)) {
return false;
}
}
return true;
}
@VisibleForTesting
static boolean charactersAreValid(String input) {
int l = input.length();
if (l == 0) {
return false;
}
for (int i = 0; i < l; i++) {
char cur = input.charAt(i);
if (!(44 <= cur && cur <= 57) && !(65 <= cur && cur <= 90) && !(97 <= cur && cur <= 122) &&
cur != 95) {
if (i != 0 || cur != 126) {
// first character can be 126 (~)
return false;
}
}
}
return true;
}
static void validateHost(String host) {
if (StringUtils.isBlank(host)) {
throw new IllegalArgumentException("WF-301: Host is required");
}
if (host.length() >= 1024) {
throw new IllegalArgumentException("WF-301: Host is too long: " + host);
}
}
private static String pointToStringSB(ReportPoint point) {
StringBuilder sb = new StringBuilder("\"")
.append(point.getMetric().replace("\"", "\\\"")).append("\" ")
.append(point.getValue()).append(" ")
.append(point.getTimestamp() / 1000).append(" ")
.append("source=\"").append(point.getHost().replace("\"", "\\\"")).append("\"");
for (Map.Entry<String, String> entry : point.getAnnotations().entrySet()) {
sb.append(" \"").append(entry.getKey().replace("\"", "\\\"")).append("\"")
.append("=")
.append("\"").append(entry.getValue().replace("\"", "\\\"")).append("\"");
}
return sb.toString();
}
@VisibleForTesting
static String pointToString(ReportPoint point) {
return pointToStringSB(point);
}
}
|
package net.jforum.view.forum;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import net.jforum.Command;
import net.jforum.JForum;
import net.jforum.SessionFacade;
import net.jforum.dao.AttachmentDAO;
import net.jforum.dao.DataAccessDriver;
import net.jforum.dao.ForumDAO;
import net.jforum.dao.KarmaDAO;
import net.jforum.dao.PostDAO;
import net.jforum.dao.TopicDAO;
import net.jforum.dao.UserDAO;
import net.jforum.entities.Attachment;
import net.jforum.entities.Forum;
import net.jforum.entities.Post;
import net.jforum.entities.QuotaLimit;
import net.jforum.entities.Topic;
import net.jforum.entities.User;
import net.jforum.entities.UserSession;
import net.jforum.exceptions.AttachmentException;
import net.jforum.exceptions.AttachmentSizeTooBigException;
import net.jforum.repository.ForumRepository;
import net.jforum.repository.PostRepository;
import net.jforum.repository.RankingRepository;
import net.jforum.repository.SecurityRepository;
import net.jforum.repository.SmiliesRepository;
import net.jforum.repository.TopicRepository;
import net.jforum.security.PermissionControl;
import net.jforum.security.SecurityConstants;
import net.jforum.util.I18n;
import net.jforum.util.preferences.ConfigKeys;
import net.jforum.util.preferences.SystemGlobals;
import net.jforum.util.preferences.TemplateKeys;
import net.jforum.view.forum.common.AttachmentCommon;
import net.jforum.view.forum.common.ForumCommon;
import net.jforum.view.forum.common.PostCommon;
import net.jforum.view.forum.common.TopicsCommon;
import net.jforum.view.forum.common.ViewCommon;
/**
* @author Rafael Steil
* @version $Id: PostAction.java,v 1.109 2005/10/08 11:02:25 vmal Exp $
*/
public class PostAction extends Command
{
public void list() throws Exception
{
PostDAO pm = DataAccessDriver.getInstance().newPostDAO();
UserDAO um = DataAccessDriver.getInstance().newUserDAO();
TopicDAO tm = DataAccessDriver.getInstance().newTopicDAO();
UserSession us = SessionFacade.getUserSession();
int anonymousUser = SystemGlobals.getIntValue(ConfigKeys.ANONYMOUS_USER_ID);
int topicId = this.request.getIntParameter("topic_id");
Topic topic = TopicRepository.getTopic(new Topic(topicId));
if (topic == null) {
topic = tm.selectById(topicId);
}
// The topic exists?
if (topic.getId() == 0) {
this.topicNotFound();
return;
}
// Shall we proceed?
if (!SessionFacade.isLogged()) {
Forum f = ForumRepository.getForum(topic.getForumId());
if (f == null || !ForumRepository.isCategoryAccessible(f.getCategoryId())) {
this.setTemplateName(ViewCommon.contextToLogin());
return;
}
}
else if (!TopicsCommon.isTopicAccessible(topic.getForumId())) {
return;
}
int count = SystemGlobals.getIntValue(ConfigKeys.POST_PER_PAGE);
int start = ViewCommon.getStartPage();
PermissionControl pc = SecurityRepository.get(us.getUserId());
boolean canEdit = false;
if (pc.canAccess(SecurityConstants.PERM_MODERATION_POST_EDIT)) {
canEdit = true;
}
List helperList = PostCommon.topicPosts(pm, canEdit, us.getUserId(), topic.getId(), start, count);
// Ugly assumption:
// Is moderation pending for the topic?
if (topic.isModerated() && helperList.size() == 0) {
this.notModeratedYet();
return;
}
// Set the topic status as read
tm.updateReadStatus(topic.getId(), us.getUserId(), true);
tm.incrementTotalViews(topic.getId());
topic.setTotalViews(topic.getTotalViews() + 1);
if (us.getUserId() != anonymousUser) {
((Map) SessionFacade.getAttribute(ConfigKeys.TOPICS_TRACKING)).put(new Integer(topic.getId()),
new Long(topic.getLastPostDate().getTime()));
}
this.context.put("attachmentsEnabled", SecurityRepository.canAccess(
SecurityConstants.PERM_ATTACHMENTS_ENABLED, Integer.toString(topic.getForumId())));
this.context.put("canDownloadAttachments", SecurityRepository.canAccess(
SecurityConstants.PERM_ATTACHMENTS_DOWNLOAD));
this.context.put("am", new AttachmentCommon(this.request, topic.getForumId()));
this.context.put("karmaVotes", DataAccessDriver.getInstance().newKarmaDAO().getUserVotes(topic.getId(), us.getUserId()));
this.context.put("rssEnabled", SystemGlobals.getBoolValue(ConfigKeys.RSS_ENABLED));
this.context.put("canRemove",
SecurityRepository.canAccess(SecurityConstants.PERM_MODERATION_POST_REMOVE));
this.context.put("canEdit", canEdit);
this.setTemplateName(TemplateKeys.POSTS_LIST);
this.context.put("allCategories", ForumCommon.getAllCategoriesAndForums(false));
this.context.put("topic", topic);
this.context.put("rank", new RankingRepository());
this.context.put("posts", helperList);
this.context.put("forum", ForumRepository.getForum(topic.getForumId()));
Map topicPosters = tm.topicPosters(topic.getId());
for (Iterator iter = topicPosters.values().iterator(); iter.hasNext(); ) {
ViewCommon.prepareUserSignature((User)iter.next());
}
this.context.put("users", topicPosters);
this.context.put("topicId", new Integer(topicId));
this.context.put("anonymousPosts", SecurityRepository.canAccess(SecurityConstants.PERM_ANONYMOUS_POST,
Integer.toString(topic.getForumId())));
this.context.put("watching", tm.isUserSubscribed(topicId, SessionFacade.getUserSession().getUserId()));
this.context.put("pageTitle", topic.getTitle());
this.context.put("isAdmin", SecurityRepository.canAccess(SecurityConstants.PERM_ADMINISTRATION));
this.context.put("readonly", !SecurityRepository.canAccess(SecurityConstants.PERM_READ_ONLY_FORUMS,
Integer.toString(topic.getForumId())));
this.context.put("replyOnly", !SecurityRepository.canAccess(SecurityConstants.PERM_REPLY_ONLY,
Integer.toString(topic.getForumId())));
this.context.put("isModerator", us.isModerator(topic.getForumId()));
// Topic Status
this.context.put("STATUS_LOCKED", new Integer(Topic.STATUS_LOCKED));
this.context.put("STATUS_UNLOCKED", new Integer(Topic.STATUS_UNLOCKED));
// Pagination
ViewCommon.contextToPagination(start, topic.getTotalReplies(), count);
TopicRepository.updateTopic(topic);
}
/**
* Given a postId, sends the user to the right page
* @throws Exception
*/
public void preList() throws Exception
{
int postId = this.request.getIntParameter("post_id");
PostDAO pdao = DataAccessDriver.getInstance().newPostDAO();
int count = pdao.countPreviousPosts(postId);
int postsPerPage = SystemGlobals.getIntValue(ConfigKeys.POST_PER_PAGE);
int topicId = this.request.getIntParameter("topic_id");
String page = "";
if (count > postsPerPage) {
page = Integer.toString(postsPerPage * ((count - 1) / postsPerPage)) + "/";
}
JForum.setRedirect(
this.request.getContextPath() + "/posts/list/"
+ page + topicId
+ SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION)
+ "#" + postId);
}
public void listByUser() throws Exception
{
PostDAO pm = DataAccessDriver.getInstance().newPostDAO();
UserDAO um = DataAccessDriver.getInstance().newUserDAO();
TopicDAO tm = DataAccessDriver.getInstance().newTopicDAO();
UserSession us = SessionFacade.getUserSession();
int anonymousUser = SystemGlobals.getIntValue(ConfigKeys.ANONYMOUS_USER_ID);
User u = um.selectById(this.request.getIntParameter("user_id"));
if (u.getId() == 0) {
this.context.put("message", I18n.getMessage("User.notFound"));
this.setTemplateName(TemplateKeys.USER_NOT_FOUND);
return;
}
int count = SystemGlobals.getIntValue(ConfigKeys.POST_PER_PAGE);
int start = ViewCommon.getStartPage();
int postsPerPage = SystemGlobals.getIntValue(ConfigKeys.POST_PER_PAGE);
List posts = pm.selectByUserByLimit(u.getId(), start, postsPerPage);
int totalMessages = u.getTotalPosts();
// get list of forums
Map topics = new HashMap();
Map forums = new HashMap();
for (Iterator iter = posts.iterator(); iter.hasNext(); ) {
Post p = (Post)iter.next();
if (!topics.containsKey(new Integer(p.getTopicId()))) {
Topic t = TopicRepository.getTopic(new Topic(p.getTopicId()));
if (t == null) {
t = tm.selectRaw(p.getTopicId());
}
this.context.put("attachmentsEnabled", SecurityRepository.canAccess(
SecurityConstants.PERM_ATTACHMENTS_ENABLED, Integer.toString(t.getForumId())));
this.context.put("am", new AttachmentCommon(this.request, t.getForumId()));
topics.put(new Integer(t.getId()), t);
}
if (!forums.containsKey(new Integer(p.getForumId()))) {
Forum f = ForumRepository.getForum(p.getForumId());
if (f == null) {
iter.remove();
totalMessages
continue;
}
forums.put(new Integer(f.getId()), f);
}
PostCommon.preparePostForDisplay(p);
}
this.setTemplateName(TemplateKeys.POSTS_USER_POSTS_LIST);
this.context.put("canDownloadAttachments", SecurityRepository.canAccess(
SecurityConstants.PERM_ATTACHMENTS_DOWNLOAD));
this.context.put("rssEnabled", SystemGlobals.getBoolValue(ConfigKeys.RSS_ENABLED));
this.context.put("allCategories", ForumCommon.getAllCategoriesAndForums(false));
this.context.put("posts", posts);
this.context.put("topics", topics);
this.context.put("forums", forums);
this.context.put("u", u);
this.context.put("pageTitle", I18n.getMessage("PostShow.userPosts") + " " + u.getUsername());
ViewCommon.contextToPagination(start, totalMessages, count);
}
public void review() throws Exception {
PostDAO pm = DataAccessDriver.getInstance().newPostDAO();
UserDAO um = DataAccessDriver.getInstance().newUserDAO();
TopicDAO tm = DataAccessDriver.getInstance().newTopicDAO();
int userId = SessionFacade.getUserSession().getUserId();
int topicId = this.request.getIntParameter("topic_id");
Topic topic = tm.selectById(topicId);
if (!TopicsCommon.isTopicAccessible(topic.getForumId())) {
return;
}
int count = SystemGlobals.getIntValue(ConfigKeys.POST_PER_PAGE);
int start = ViewCommon.getStartPage();
Map usersMap = tm.topicPosters(topic.getId());
List helperList = PostCommon.topicPosts(pm, false, userId, topic.getId(), start, count);
Collections.reverse(helperList);
this.setTemplateName(SystemGlobals.getValue(ConfigKeys.TEMPLATE_DIR) + "/empty.htm");
this.setTemplateName(TemplateKeys.POSTS_REVIEW);
this.context.put("posts", helperList);
this.context.put("users", usersMap);
}
private void topicNotFound() {
this.setTemplateName(TemplateKeys.POSTS_TOPIC_NOT_FOUND);
this.context.put("message", I18n.getMessage("PostShow.TopicNotFound"));
}
private void postNotFound() {
this.setTemplateName(TemplateKeys.POSTS_POST_NOT_FOUND);
this.context.put("message", I18n.getMessage("PostShow.PostNotFound"));
}
private void replyOnly()
{
this.setTemplateName(TemplateKeys.POSTS_REPLY_ONLY);
this.context.put("message", I18n.getMessage("PostShow.replyOnly"));
}
private boolean isReplyOnly(int forumId) throws Exception
{
return !SecurityRepository.canAccess(SecurityConstants.PERM_REPLY_ONLY,
Integer.toString(forumId));
}
public void insert() throws Exception
{
int forumId = this.request.getIntParameter("forum_id");
if (!TopicsCommon.isTopicAccessible(forumId)) {
return;
}
if (!this.anonymousPost(forumId)
|| this.isForumReadonly(forumId, this.request.getParameter("topic_id") != null)) {
return;
}
if (this.request.getParameter("topic_id") != null) {
int topicId = this.request.getIntParameter("topic_id");
Topic t = TopicRepository.getTopic(new Topic(topicId));
if (t == null) {
t = DataAccessDriver.getInstance().newTopicDAO().selectRaw(topicId);
}
if (!TopicsCommon.isTopicAccessible(t.getForumId())) {
return;
}
if (t.getStatus() == Topic.STATUS_LOCKED) {
this.topicLocked();
return;
}
this.context.put("topic", t);
this.context.put("setType", false);
this.context.put("pageTitle", I18n.getMessage("PostForm.reply")+" "+t.getTitle());
}
else {
if (this.isReplyOnly(forumId)) {
this.replyOnly();
return;
}
this.context.put("setType", true);
this.context.put("pageTitle", I18n.getMessage("PostForm.title"));
}
int userId = SessionFacade.getUserSession().getUserId();
this.setTemplateName(TemplateKeys.POSTS_INSERT);
// Attachments
boolean attachmentsEnabled = SecurityRepository.canAccess(
SecurityConstants.PERM_ATTACHMENTS_ENABLED, Integer.toString(forumId));
if (attachmentsEnabled && !SessionFacade.isLogged()
&& !SystemGlobals.getBoolValue(ConfigKeys.ATTACHMENTS_ANONYMOUS)) {
attachmentsEnabled = false;
}
this.context.put("attachmentsEnabled", attachmentsEnabled);
if (attachmentsEnabled) {
QuotaLimit ql = new AttachmentCommon(this.request, forumId).getQuotaLimit(userId);
this.context.put("maxAttachmentsSize", new Long(ql != null ? ql.getSizeInBytes() : 1));
this.context.put("maxAttachments", SystemGlobals.getValue(ConfigKeys.ATTACHMENTS_MAX_POST));
}
boolean needCaptcha = SystemGlobals.getBoolValue(ConfigKeys.CAPTCHA_POSTS);
if (needCaptcha) {
SessionFacade.getUserSession().createNewCaptcha();
}
this.context.put("smilies", SmiliesRepository.getSmilies());
this.context.put("forum", ForumRepository.getForum(forumId));
this.context.put("action", "insertSave");
this.context.put("start", this.request.getParameter("start"));
this.context.put("isNewPost", true);
this.context.put("needCaptcha", needCaptcha);
this.context.put("htmlAllowed",
SecurityRepository.canAccess(SecurityConstants.PERM_HTML_DISABLED, Integer.toString(forumId)));
this.context.put("canCreateStickyOrAnnouncementTopics",
SecurityRepository.canAccess(SecurityConstants.PERM_CREATE_STICKY_ANNOUNCEMENT_TOPICS));
User user = DataAccessDriver.getInstance().newUserDAO().selectById(userId);
user.setSignature(PostCommon.processText(user.getSignature()));
user.setSignature(PostCommon.processSmilies(user.getSignature(), SmiliesRepository.getSmilies()));
if (this.request.getParameter("preview") != null) {
user.setNotifyOnMessagesEnabled(this.request.getParameter("notify") != null);
}
this.context.put("user", user);
}
public void edit() throws Exception {
this.edit(false, null);
}
private void edit(boolean preview, Post p) throws Exception
{
int userId = SessionFacade.getUserSession().getUserId();
int aId = SystemGlobals.getIntValue(ConfigKeys.ANONYMOUS_USER_ID);
boolean canAccess = false;
if (!preview) {
PostDAO pm = DataAccessDriver.getInstance().newPostDAO();
p = pm.selectById(this.request.getIntParameter("post_id"));
// The post exist?
if (p.getId() == 0) {
this.postNotFound();
return;
}
}
boolean isModerator = SecurityRepository.canAccess(SecurityConstants.PERM_MODERATION_POST_EDIT);
canAccess = (isModerator || p.getUserId() == userId);
if ((userId != aId) && canAccess) {
Topic topic = TopicRepository.getTopic(new Topic(p.getTopicId()));
if (topic == null) {
topic = DataAccessDriver.getInstance().newTopicDAO().selectById(p.getTopicId());
}
if (!TopicsCommon.isTopicAccessible(topic.getForumId())) {
return;
}
if (topic.getStatus() == Topic.STATUS_LOCKED && !isModerator) {
this.topicLocked();
return;
}
if (preview && this.request.getParameter("topic_type") != null) {
topic.setType(this.request.getIntParameter("topic_type"));
}
if (p.hasAttachments()) {
this.context.put("attachments",
DataAccessDriver.getInstance().newAttachmentDAO().selectAttachments(p.getId()));
}
this.context.put("attachmentsEnabled", SecurityRepository.canAccess(
SecurityConstants.PERM_ATTACHMENTS_ENABLED, Integer.toString(p.getForumId())));
QuotaLimit ql = new AttachmentCommon(this.request, p.getForumId()).getQuotaLimit(userId);
this.context.put("maxAttachmentsSize", new Long(ql != null ? ql.getSizeInBytes() : 1));
this.context.put("maxAttachments", SystemGlobals.getValue(ConfigKeys.ATTACHMENTS_MAX_POST));
this.context.put("smilies", SmiliesRepository.getSmilies());
this.context.put("forum", ForumRepository.getForum(p.getForumId()));
this.context.put("action", "editSave");
this.context.put("post", p);
this.context.put("setType", p.getId() == topic.getFirstPostId());
this.context.put("topic", topic);
this.context.put("pageTitle", I18n.getMessage("PostShow.messageTitle")+" "+p.getSubject());
this.setTemplateName(TemplateKeys.POSTS_EDIT);
this.context.put("start", this.request.getParameter("start"));
this.context.put("htmlAllowed", SecurityRepository.canAccess(SecurityConstants.PERM_HTML_DISABLED,
Integer.toString(topic.getForumId())));
this.context.put("canCreateStickyOrAnnouncementTopics",
SecurityRepository.canAccess(SecurityConstants.PERM_CREATE_STICKY_ANNOUNCEMENT_TOPICS));
}
else {
this.setTemplateName(TemplateKeys.POSTS_EDIT_CANNOTEDIT);
this.context.put("message", I18n.getMessage("CannotEditPost"));
}
UserDAO udao = DataAccessDriver.getInstance().newUserDAO();
User u = udao.selectById(userId);
ViewCommon.prepareUserSignature(u);
if (preview) {
u.setNotifyOnMessagesEnabled(this.request.getParameter("notify") != null);
if (u.getId() != p.getUserId()) {
// Probably a moderator is editing the message
User previewUser = udao.selectById(p.getUserId());
ViewCommon.prepareUserSignature(previewUser);
this.context.put("previewUser", previewUser);
}
}
this.context.put("user", u);
}
public void quote() throws Exception {
PostDAO pm = DataAccessDriver.getInstance().newPostDAO();
Post p = pm.selectById(this.request.getIntParameter("post_id"));
if (!this.anonymousPost(p.getForumId())) {
return;
}
Topic t = TopicRepository.getTopic(new Topic(p.getTopicId()));
if (t == null) {
t = DataAccessDriver.getInstance().newTopicDAO().selectRaw(p.getTopicId());
}
if (!TopicsCommon.isTopicAccessible(t.getForumId())) {
return;
}
if (t.getStatus() == Topic.STATUS_LOCKED) {
this.topicLocked();
return;
}
if (p.getId() == 0) {
this.postNotFound();
return;
}
if (p.isModerationNeeded()) {
this.notModeratedYet();
return;
}
this.context.put("forum", ForumRepository.getForum(p.getForumId()));
this.context.put("action", "insertSave");
this.context.put("post", p);
UserDAO um = DataAccessDriver.getInstance().newUserDAO();
User u = um.selectById(p.getUserId());
Topic topic = DataAccessDriver.getInstance().newTopicDAO().selectById(p.getTopicId());
int userId = SessionFacade.getUserSession().getUserId();
this.context.put("attachmentsEnabled", SecurityRepository.canAccess(
SecurityConstants.PERM_ATTACHMENTS_ENABLED, Integer.toString(topic.getForumId())));
QuotaLimit ql = new AttachmentCommon(this.request, topic.getForumId()).getQuotaLimit(userId);
this.context.put("maxAttachmentsSize", new Long(ql != null ? ql.getSizeInBytes() : 1));
this.context.put("maxAttachments", SystemGlobals.getValue(ConfigKeys.ATTACHMENTS_MAX_POST));
this.context.put("isNewPost", true);
this.context.put("topic", topic);
this.context.put("quote", "true");
this.context.put("quoteUser", u.getUsername());
this.setTemplateName(TemplateKeys.POSTS_QUOTE);
this.context.put("setType", false);
this.context.put("htmlAllowed", SecurityRepository.canAccess(SecurityConstants.PERM_HTML_DISABLED,
Integer.toString(topic.getForumId())));
this.context.put("start", this.request.getParameter("start"));
this.context.put("user", DataAccessDriver.getInstance().newUserDAO().selectById(userId));
this.context.put("pageTitle", I18n.getMessage("PostForm.reply")+" "+p.getSubject());
}
public void editSave() throws Exception
{
PostDAO pm = DataAccessDriver.getInstance().newPostDAO();
TopicDAO tm = DataAccessDriver.getInstance().newTopicDAO();
Post p = pm.selectById(this.request.getIntParameter("post_id"));
p = PostCommon.fillPostFromRequest(p, true);
// The user wants to preview the message before posting it?
if (this.request.getParameter("preview") != null) {
this.context.put("preview", true);
Post postPreview = new Post(p);
this.context.put("postPreview", PostCommon.preparePostForDisplay(postPreview));
this.edit(true, p);
}
else {
AttachmentCommon attachments = new AttachmentCommon(this.request, p.getForumId());
try {
attachments.preProcess();
}
catch (AttachmentException e) {
JForum.enableCancelCommit();
p.setText(this.request.getParameter("message"));
this.context.put("errorMessage", e.getMessage());
this.context.put("post", p);
this.edit(false, p);
return;
}
Topic t = TopicRepository.getTopic(new Topic(p.getTopicId()));
if (t == null) {
t = tm.selectById(p.getTopicId());
}
if (!TopicsCommon.isTopicAccessible(t.getForumId())) {
return;
}
if (t.getStatus() == Topic.STATUS_LOCKED
&& !SecurityRepository.canAccess(SecurityConstants.PERM_MODERATION_POST_EDIT)) {
this.topicLocked();
return;
}
pm.update(p);
// Attachments
attachments.editAttachments(p.getId(), p.getForumId());
attachments.insertAttachments(p);
// Updates the topic title
if (t.getFirstPostId() == p.getId()) {
t.setTitle(p.getSubject());
int newType = this.request.getIntParameter("topic_type");
boolean changeType = SecurityRepository.canAccess(SecurityConstants.PERM_CREATE_STICKY_ANNOUNCEMENT_TOPICS)
&& newType != t.getType();
if (changeType) {
t.setType(newType);
}
tm.update(t);
User u = DataAccessDriver.getInstance().newUserDAO().selectById(p.getUserId());
if (changeType) {
TopicRepository.addTopic(t);
}
else {
TopicRepository.updateTopic(t);
}
}
if (this.request.getParameter("notify") == null) {
tm.removeSubscription(p.getTopicId(), SessionFacade.getUserSession().getUserId());
}
String path = this.request.getContextPath() + "/posts/list/";
String start = this.request.getParameter("start");
if (start != null && !start.equals("0")) {
path += start + "/";
}
path += p.getTopicId() + SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION) + "#" + p.getId();
JForum.setRedirect(path);
if (SystemGlobals.getBoolValue(ConfigKeys.POSTS_CACHE_ENABLED)) {
PostRepository.update(p.getTopicId(), PostCommon.preparePostForDisplay(p));
}
}
}
public void waitingModeration()
{
this.setTemplateName(TemplateKeys.POSTS_WAITING);
int topicId = this.request.getIntParameter("topic_id");
String path = this.request.getContextPath();
if (topicId == 0) {
path += "/forums/show/" + this.request.getParameter("forum_id");
}
else {
path += "/posts/list/" + topicId;
}
this.context.put("message", I18n.getMessage("PostShow.waitingModeration",
new String[] { path + SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION) }));
}
private void notModeratedYet()
{
this.setTemplateName(TemplateKeys.POSTS_NOT_MODERATED);
this.context.put("message", I18n.getMessage("PostShow.notModeratedYet"));
}
public void insertSave() throws Exception
{
int forumId = this.request.getIntParameter("forum_id");
boolean firstPost = false;
if (!this.anonymousPost(forumId)) {
SessionFacade.setAttribute(ConfigKeys.REQUEST_DUMP, this.request.dumpRequest());
return;
}
Topic t = new Topic(-1);
t.setForumId(forumId);
boolean newTopic = (this.request.getParameter("topic_id") == null);
if (!TopicsCommon.isTopicAccessible(t.getForumId())
|| this.isForumReadonly(t.getForumId(), newTopic)) {
return;
}
TopicDAO tm = DataAccessDriver.getInstance().newTopicDAO();
PostDAO pm = DataAccessDriver.getInstance().newPostDAO();
ForumDAO fm = DataAccessDriver.getInstance().newForumDAO();
if (!newTopic) {
int topicId = this.request.getIntParameter("topic_id");
t = TopicRepository.getTopic(new Topic(topicId));
if (t == null) {
t = tm.selectById(topicId);
}
if (!TopicsCommon.isTopicAccessible(t.getForumId())) {
return;
}
// Cannot insert new messages on locked topics
if (t.getStatus() == Topic.STATUS_LOCKED) {
this.topicLocked();
return;
}
}
else {
if (this.isReplyOnly(forumId)) {
this.replyOnly();
return;
}
}
if (this.request.getParameter("topic_type") != null) {
t.setType(this.request.getIntParameter("topic_type"));
if (t.getType() != Topic.TYPE_NORMAL
&& !SecurityRepository.canAccess(SecurityConstants.PERM_CREATE_STICKY_ANNOUNCEMENT_TOPICS)) {
t.setType(Topic.TYPE_NORMAL);
}
}
UserSession us = SessionFacade.getUserSession();
User u = new User();
if ("1".equals(this.request.getParameter("quick")) && SessionFacade.isLogged()) {
u = DataAccessDriver.getInstance().newUserDAO().selectById(us.getUserId());
this.request.addParameter("notify", u.isNotifyOnMessagesEnabled() ? "1" : null);
this.request.addParameter("attach_sig", u.getAttachSignatureEnabled() ? "1" : "0");
}
else {
u.setId(us.getUserId());
u.setUsername(us.getUsername());
}
// Set the Post
Post p = PostCommon.fillPostFromRequest();
if (p.getText() == null || p.getText().trim().equals("")) {
this.insert();
return;
}
// Check the elapsed time since the last post from the user
int delay = SystemGlobals.getIntValue(ConfigKeys.POSTS_NEW_DELAY);
if (delay > 0) {
Long lastPostTime = (Long)SessionFacade.getAttribute(ConfigKeys.LAST_POST_TIME);
if (lastPostTime != null) {
if (System.currentTimeMillis() < (lastPostTime.longValue() + delay)) {
this.context.put("post", p);
this.context.put("start", this.request.getParameter("start"));
this.context.put("error", I18n.getMessage("PostForm.tooSoon"));
this.insert();
return;
}
}
}
p.setForumId(this.request.getIntParameter("forum_id"));
if (p.getSubject() == null || p.getSubject() == "") {
p.setSubject(t.getTitle());
}
boolean needCaptcha = SystemGlobals.getBoolValue(ConfigKeys.CAPTCHA_POSTS);
if (needCaptcha) {
if (!us.validateCaptchaResponse(this.request.getParameter("captcha_anwser"))) {
this.context.put("post", p);
this.context.put("start", this.request.getParameter("start"));
this.context.put("error", I18n.getMessage("CaptchaResponseFails"));
this.insert();
return;
}
}
boolean preview = (this.request.getParameter("preview") != null);
boolean moderate = false;
if (!preview) {
AttachmentCommon attachments = new AttachmentCommon(this.request, forumId);
try {
attachments.preProcess();
}
catch (AttachmentSizeTooBigException e) {
JForum.enableCancelCommit();
p.setText(this.request.getParameter("message"));
p.setId(0);
this.context.put("errorMessage", e.getMessage());
this.context.put("post", p);
this.insert();
return;
}
// If topic_id is -1, then is the first post
if (t.getId() == -1) {
t.setTime(new Date());
t.setTitle(this.request.getParameter("subject"));
t.setModerated(ForumRepository.getForum(forumId).isModerated());
t.setPostedBy(u);
t.setFirstPostTime(ViewCommon.formatDate(t.getTime()));
int topicId = tm.addNew(t);
t.setId(topicId);
firstPost = true;
}
// Moderators and admins don't need to have their messages moderated
moderate = (t.isModerated()
&& !SecurityRepository.canAccess(SecurityConstants.PERM_MODERATION)
&& !SecurityRepository.canAccess(SecurityConstants.PERM_ADMINISTRATION));
// Topic watch
if (this.request.getParameter("notify") != null) {
this.watch(tm, t.getId(), u.getId());
}
p.setTopicId(t.getId());
// Save the remaining stuff
p.setModerate(moderate);
int postId = pm.addNew(p);
if (newTopic) {
t.setFirstPostId(postId);
}
t.setLastPostId(postId);
t.setLastPostBy(u);
t.setLastPostDate(p.getTime());
t.setLastPostTime(p.getFormatedTime());
tm.update(t);
attachments.insertAttachments(p);
if (!moderate) {
if (!newTopic) {
TopicsCommon.notifyUsers(t, tm);
t.setTotalReplies(t.getTotalReplies() + 1);
}
t.setTotalViews(t.getTotalViews() + 1);
DataAccessDriver.getInstance().newUserDAO().incrementPosts(p.getUserId());
TopicsCommon.updateBoardStatus(t, postId, firstPost, tm, fm);
ForumRepository.updateForumStats(t, u, p);
String path = this.request.getContextPath() + "/posts/list/";
int start = ViewCommon.getStartPage();
path += this.startPage(t, start) + "/";
path += t.getId() + SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION) + "#" + postId;
JForum.setRedirect(path);
int anonymousUser = SystemGlobals.getIntValue(ConfigKeys.ANONYMOUS_USER_ID);
if (u.getId() != anonymousUser) {
((Map) SessionFacade.getAttribute(ConfigKeys.TOPICS_TRACKING)).put(new Integer(t.getId()),
new Long(p.getTime().getTime()));
}
if (SystemGlobals.getBoolValue(ConfigKeys.POSTS_CACHE_ENABLED)) {
SimpleDateFormat df = new SimpleDateFormat(SystemGlobals.getValue(ConfigKeys.DATE_TIME_FORMAT));
p.setFormatedTime(df.format(p.getTime()));
PostRepository.append(p.getTopicId(), PostCommon.preparePostForDisplay(p));
}
}
else {
JForum.setRedirect(this.request.getContextPath() + "/posts/waitingModeration/" + (firstPost ? 0 : t.getId())
+ "/" + t.getForumId()
+ SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION));
}
if (delay > 0) {
SessionFacade.setAttribute(ConfigKeys.LAST_POST_TIME, new Long(System.currentTimeMillis()));
}
}
else {
this.context.put("preview", true);
this.context.put("post", p);
this.context.put("start", this.request.getParameter("start"));
Post postPreview = new Post(p);
this.context.put("postPreview", PostCommon.preparePostForDisplay(postPreview));
this.insert();
}
}
private int startPage(Topic t, int currentStart) {
int postsPerPage = SystemGlobals.getIntValue(ConfigKeys.POST_PER_PAGE);
int newStart = (t.getTotalReplies() + 1) / postsPerPage * postsPerPage;
if (newStart > currentStart) {
return newStart;
}
return currentStart;
}
public void delete() throws Exception
{
if (!SecurityRepository.canAccess(SecurityConstants.PERM_MODERATION_POST_REMOVE)) {
this.setTemplateName(TemplateKeys.POSTS_CANNOT_DELETE);
this.context.put("message", I18n.getMessage("CannotRemovePost"));
return;
}
// Post
PostDAO pm = DataAccessDriver.getInstance().newPostDAO();
Post p = pm.selectById(this.request.getIntParameter("post_id"));
TopicDAO tm = DataAccessDriver.getInstance().newTopicDAO();
Topic t = TopicRepository.getTopic(new Topic(p.getTopicId()));
if (t == null) {
t = tm.selectById(p.getTopicId());
}
if (!TopicsCommon.isTopicAccessible(t.getForumId())) {
return;
}
if (p.getId() == 0) {
this.postNotFound();
return;
}
pm.delete(p);
DataAccessDriver.getInstance().newUserDAO().decrementPosts(p.getUserId());
// Karma
KarmaDAO karmaDao = DataAccessDriver.getInstance().newKarmaDAO();
karmaDao.updateUserKarma(p.getUserId());
// Attachments
new AttachmentCommon(this.request, p.getForumId()).deleteAttachments(p.getId(), p.getForumId());
// Topic
tm.decrementTotalReplies(p.getTopicId());
int maxPostId = tm.getMaxPostId(p.getTopicId());
if (maxPostId > -1) {
tm.setLastPostId(p.getTopicId(), maxPostId);
}
int minPostId = tm.getMinPostId(p.getTopicId());
if (minPostId > -1) {
tm.setFirstPostId(p.getTopicId(), minPostId);
}
// Forum
ForumDAO fm = DataAccessDriver.getInstance().newForumDAO();
maxPostId = fm.getMaxPostId(p.getForumId());
if (maxPostId > -1) {
fm.setLastPost(p.getForumId(), maxPostId);
}
// It was the last remaining post in the topic?
int totalPosts = tm.getTotalPosts(p.getTopicId());
if (totalPosts > 0) {
String page = this.request.getParameter("start");
String returnPath = this.request.getContextPath() + "/posts/list/";
if (page != null && !page.equals("") && !page.equals("0")) {
int postsPerPage = SystemGlobals.getIntValue(ConfigKeys.POST_PER_PAGE);
int newPage = Integer.parseInt(page);
if (totalPosts % postsPerPage == 0) {
newPage -= postsPerPage;
}
returnPath += newPage + "/";
}
JForum.setRedirect(returnPath + p.getTopicId() + SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION));
}
else {
// Ok, all posts were removed. Time to say goodbye
TopicsCommon.deleteTopic(p.getTopicId(), p.getForumId(), false);
JForum.setRedirect(this.request.getContextPath() + "/forums/show/" + p.getForumId()
+ SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION));
}
ForumRepository.reloadForum(p.getForumId());
TopicRepository.clearCache(p.getForumId());
PostRepository.clearCache(p.getTopicId());
}
private void watch(TopicDAO tm, int topicId, int userId) throws Exception {
if (!tm.isUserSubscribed(topicId, userId)) {
tm.subscribeUser(topicId, userId);
}
}
public void watch() throws Exception {
int topicId = this.request.getIntParameter("topic_id");
int userId = SessionFacade.getUserSession().getUserId();
this.watch(DataAccessDriver.getInstance().newTopicDAO(), topicId, userId);
this.list();
}
public void unwatch() throws Exception {
if (SessionFacade.isLogged()) {
int topicId = this.request.getIntParameter("topic_id");
int userId = SessionFacade.getUserSession().getUserId();
String start = this.request.getParameter("start");
DataAccessDriver.getInstance().newTopicDAO().removeSubscription(topicId, userId);
String returnPath = this.request.getContextPath() + "/posts/list/";
if (start != null && !start.equals("")) {
returnPath += start + "/";
}
returnPath += topicId + SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION);
this.setTemplateName(TemplateKeys.POSTS_UNWATCH);
this.context.put("message", I18n.getMessage("ForumBase.unwatched", new String[] { returnPath }));
}
else {
this.setTemplateName(ViewCommon.contextToLogin());
}
}
public void downloadAttach() throws Exception
{
if ((SecurityRepository.canAccess(SecurityConstants.PERM_ATTACHMENTS_ENABLED) &&
!SecurityRepository.canAccess(SecurityConstants.PERM_ATTACHMENTS_DOWNLOAD))
|| (!SessionFacade.isLogged() && !SystemGlobals.getBoolValue(ConfigKeys.ATTACHMENTS_ANONYMOUS))) {
this.setTemplateName(TemplateKeys.POSTS_CANNOT_DOWNLOAD);
this.context.put("message", I18n.getMessage("Attachments.featureDisabled"));
return;
}
int id = this.request.getIntParameter("attach_id");
AttachmentDAO am = DataAccessDriver.getInstance().newAttachmentDAO();
Attachment a = am.selectAttachmentById(id);
String filename = SystemGlobals.getValue(ConfigKeys.ATTACHMENTS_STORE_DIR)
+ "/"
+ a.getInfo().getPhysicalFilename();
if (!new File(filename).exists()) {
this.setTemplateName(TemplateKeys.POSTS_ATTACH_NOTFOUND);
this.context.put("message", I18n.getMessage("Attachments.notFound"));
return;
}
a.getInfo().setDownloadCount(a.getInfo().getDownloadCount() + 1);
am.updateAttachment(a);
FileInputStream fis = new FileInputStream(filename);
OutputStream os = response.getOutputStream();
if(am.isPhysicalDownloadMode(a.getInfo().getExtension().getExtensionGroupId())) {
this.response.setContentType("application/octet-stream");
}
else {
this.response.setContentType(a.getInfo().getMimetype());
}
if (this.request.getHeader("User-Agent").indexOf("Firefox") != -1) {
this.response.setHeader("Content-Disposition", "attachment; filename=\""
+ new String(a.getInfo().getRealFilename().getBytes(SystemGlobals.getValue(ConfigKeys.ENCODING)),
SystemGlobals.getValue(ConfigKeys.DEFAULT_CONTAINER_ENCODING)) + "\";");
}
else {
this.response.setHeader("Content-Disposition", "attachment; filename=\""
+ ViewCommon.toUtf8String(a.getInfo().getRealFilename()) + "\";");
}
this.response.setContentLength((int)a.getInfo().getFilesize());
int c = 0;
byte[] b = new byte[4096];
while ((c = fis.read(b)) != -1) {
os.write(b, 0, c);
}
fis.close();
os.close();
JForum.enableBinaryContent(true);
}
private void topicLocked() {
this.setTemplateName(TemplateKeys.POSTS_TOPIC_LOCKED);
this.context.put("message", I18n.getMessage("PostShow.topicLocked"));
}
public void listSmilies()
{
this.setTemplateName(SystemGlobals.getValue(ConfigKeys.TEMPLATE_DIR) + "/empty.htm");
this.setTemplateName(TemplateKeys.POSTS_LIST_SMILIES);
this.context.put("smilies", SmiliesRepository.getSmilies());
}
private boolean isForumReadonly(int forumId, boolean isReply) throws Exception {
if (!SecurityRepository.canAccess(SecurityConstants.PERM_READ_ONLY_FORUMS, Integer.toString(forumId))) {
if (isReply) {
this.list();
}
else {
JForum.setRedirect(this.request.getContextPath() + "/forums/show/" + forumId
+ SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION));
}
return true;
}
return false;
}
private boolean anonymousPost(int forumId) throws Exception {
// Check if anonymous posts are allowed
if (!SessionFacade.isLogged()
&& !SecurityRepository.canAccess(SecurityConstants.PERM_ANONYMOUS_POST, Integer.toString(forumId))) {
this.setTemplateName(ViewCommon.contextToLogin());
return false;
}
return true;
}
}
|
package net.bytebuddy.asm;
import net.bytebuddy.ClassFileVersion;
import net.bytebuddy.description.annotation.AnnotationDescription;
import net.bytebuddy.description.field.FieldDescription;
import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.description.method.MethodList;
import net.bytebuddy.description.method.ParameterDescription;
import net.bytebuddy.description.method.ParameterList;
import net.bytebuddy.description.type.TypeDefinition;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.description.type.TypeList;
import net.bytebuddy.dynamic.ClassFileLocator;
import net.bytebuddy.dynamic.scaffold.FieldLocator;
import net.bytebuddy.dynamic.scaffold.InstrumentedType;
import net.bytebuddy.implementation.Implementation;
import net.bytebuddy.implementation.SuperMethodCall;
import net.bytebuddy.implementation.bytecode.*;
import net.bytebuddy.implementation.bytecode.assign.Assigner;
import net.bytebuddy.implementation.bytecode.collection.ArrayAccess;
import net.bytebuddy.implementation.bytecode.collection.ArrayFactory;
import net.bytebuddy.implementation.bytecode.constant.*;
import net.bytebuddy.implementation.bytecode.member.FieldAccess;
import net.bytebuddy.implementation.bytecode.member.MethodInvocation;
import net.bytebuddy.implementation.bytecode.member.MethodVariableAccess;
import net.bytebuddy.matcher.ElementMatcher;
import net.bytebuddy.pool.TypePool;
import net.bytebuddy.utility.CompoundList;
import net.bytebuddy.utility.JavaConstant;
import net.bytebuddy.utility.JavaType;
import net.bytebuddy.utility.visitor.ExceptionTableSensitiveMethodVisitor;
import net.bytebuddy.utility.visitor.LineNumberPrependingMethodVisitor;
import net.bytebuddy.utility.visitor.StackAwareMethodVisitor;
import org.objectweb.asm.*;
import java.io.*;
import java.lang.annotation.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;
import static net.bytebuddy.matcher.ElementMatchers.*;
public class Advice implements AsmVisitorWrapper.ForDeclaredMethods.MethodVisitorWrapper, Implementation {
/**
* Indicates that no class reader is available to an adice method.
*/
private static final ClassReader UNDEFINED = null;
/**
* A reference to the {@link OnMethodEnter#inline()} method.
*/
private static final MethodDescription.InDefinedShape INLINE_ENTER;
/**
* A reference to the {@link OnMethodEnter#suppress()} method.
*/
private static final MethodDescription.InDefinedShape SUPPRESS_ENTER;
/**
* A reference to the {@link OnMethodEnter#prependLineNumber()} method.
*/
private static final MethodDescription.InDefinedShape PREPEND_LINE_NUMBER;
/**
* A reference to the {@link OnMethodEnter#skipOn()} method.
*/
private static final MethodDescription.InDefinedShape SKIP_ON;
/**
* A reference to the {@link OnMethodExit#inline()} method.
*/
private static final MethodDescription.InDefinedShape INLINE_EXIT;
/**
* A reference to the {@link OnMethodExit#suppress()} method.
*/
private static final MethodDescription.InDefinedShape SUPPRESS_EXIT;
/**
* A reference to the {@link OnMethodExit#onThrowable()} method.
*/
private static final MethodDescription.InDefinedShape ON_THROWABLE;
/*
* Extracts the annotation values for the enter and exit advice annotations.
*/
static {
MethodList<MethodDescription.InDefinedShape> enter = new TypeDescription.ForLoadedType(OnMethodEnter.class).getDeclaredMethods();
INLINE_ENTER = enter.filter(named("inline")).getOnly();
SUPPRESS_ENTER = enter.filter(named("suppress")).getOnly();
SKIP_ON = enter.filter(named("skipOn")).getOnly();
PREPEND_LINE_NUMBER = enter.filter(named("prependLineNumber")).getOnly();
MethodList<MethodDescription.InDefinedShape> exit = new TypeDescription.ForLoadedType(OnMethodExit.class).getDeclaredMethods();
INLINE_EXIT = exit.filter(named("inline")).getOnly();
SUPPRESS_EXIT = exit.filter(named("suppress")).getOnly();
ON_THROWABLE = exit.filter(named("onThrowable")).getOnly();
}
/**
* The dispatcher for instrumenting the instrumented method upon entering.
*/
private final Dispatcher.Resolved.ForMethodEnter methodEnter;
/**
* The dispatcher for instrumenting the instrumented method upon exiting.
*/
private final Dispatcher.Resolved.ForMethodExit methodExit;
/**
* The assigner to use.
*/
private final Assigner assigner;
/**
* The delegate implementation to apply if this advice is used as an instrumentation.
*/
private final Implementation delegate;
/**
* Creates a new advice.
*
* @param methodEnter The dispatcher for instrumenting the instrumented method upon entering.
* @param methodExit The dispatcher for instrumenting the instrumented method upon exiting.
*/
protected Advice(Dispatcher.Resolved.ForMethodEnter methodEnter, Dispatcher.Resolved.ForMethodExit methodExit) {
this(methodEnter, methodExit, Assigner.DEFAULT, SuperMethodCall.INSTANCE);
}
/**
* Creates a new advice.
*
* @param methodEnter The dispatcher for instrumenting the instrumented method upon entering.
* @param methodExit The dispatcher for instrumenting the instrumented method upon exiting.
* @param assigner The assigner to use.
* @param delegate The delegate implementation to apply if this advice is used as an instrumentation.
*/
private Advice(Dispatcher.Resolved.ForMethodEnter methodEnter, Dispatcher.Resolved.ForMethodExit methodExit, Assigner assigner, Implementation delegate) {
this.methodEnter = methodEnter;
this.methodExit = methodExit;
this.assigner = assigner;
this.delegate = delegate;
}
/**
* Implements advice where every matched method is advised by the given type's advisory methods. The advices binary representation is
* accessed by querying the class loader of the supplied class for a class file.
*
* @param advice The type declaring the advice.
* @return A method visitor wrapper representing the supplied advice.
*/
public static Advice to(Class<?> advice) {
return to(advice, ClassFileLocator.ForClassLoader.of(advice.getClassLoader()));
}
/**
* Implements advice where every matched method is advised by the given type's advisory methods.
*
* @param advice The type declaring the advice.
* @param classFileLocator The class file locator for locating the advisory class's class file.
* @return A method visitor wrapper representing the supplied advice.
*/
public static Advice to(Class<?> advice, ClassFileLocator classFileLocator) {
return to(new TypeDescription.ForLoadedType(advice), classFileLocator);
}
/**
* Implements advice where every matched method is advised by the given type's advisory methods. Using this method, a non-operational
* class file locator is specified for the advice target. This implies that only advice targets with the <i>inline</i> target set
* to {@code false} are resolvable by the returned instance.
*
* @param advice The type declaring the advice.
* @return A method visitor wrapper representing the supplied advice.
*/
public static Advice to(TypeDescription advice) {
return to(advice, ClassFileLocator.NoOp.INSTANCE);
}
/**
* Implements advice where every matched method is advised by the given type's advisory methods.
*
* @param advice A description of the type declaring the advice.
* @param classFileLocator The class file locator for locating the advisory class's class file.
* @return A method visitor wrapper representing the supplied advice.
*/
public static Advice to(TypeDescription advice, ClassFileLocator classFileLocator) {
return to(advice, classFileLocator, Collections.<Dispatcher.OffsetMapping.Factory>emptyList());
}
/**
* Creates a new advice.
*
* @param advice A description of the type declaring the advice.
* @param classFileLocator The class file locator for locating the advisory class's class file.
* @param userFactories A list of custom factories for user generated offset mappings.
* @return A method visitor wrapper representing the supplied advice.
*/
protected static Advice to(TypeDescription advice, ClassFileLocator classFileLocator, List<? extends Dispatcher.OffsetMapping.Factory> userFactories) {
Dispatcher.Unresolved methodEnter = Dispatcher.Inactive.INSTANCE, methodExit = Dispatcher.Inactive.INSTANCE;
for (MethodDescription.InDefinedShape methodDescription : advice.getDeclaredMethods()) {
methodEnter = locate(OnMethodEnter.class, INLINE_ENTER, methodEnter, methodDescription);
methodExit = locate(OnMethodExit.class, INLINE_EXIT, methodExit, methodDescription);
}
if (!methodEnter.isAlive() && !methodExit.isAlive()) {
throw new IllegalArgumentException("No advice defined by " + advice);
}
try {
ClassReader classReader = methodEnter.isBinary() || methodExit.isBinary()
? new ClassReader(classFileLocator.locate(advice.getName()).resolve())
: UNDEFINED;
Dispatcher.Resolved.ForMethodEnter resolved = methodEnter.asMethodEnter(userFactories, classReader);
return new Advice(resolved, methodExit.asMethodExitTo(userFactories, classReader, resolved));
} catch (IOException exception) {
throw new IllegalStateException("Error reading class file of " + advice, exception);
}
}
/**
* Implements advice where every matched method is advised by the given type's advisory methods. The advices binary representation is
* accessed by querying the class loader of the supplied class for a class file.
*
* @param enterAdvice The type declaring the enter advice.
* @param exitAdvice The type declaring the exit advice.
* @return A method visitor wrapper representing the supplied advice.
*/
public static Advice to(Class<?> enterAdvice, Class<?> exitAdvice) {
ClassLoader enterLoader = enterAdvice.getClassLoader(), exitLoader = exitAdvice.getClassLoader();
return to(enterAdvice, exitAdvice, enterLoader == exitLoader
? ClassFileLocator.ForClassLoader.of(enterLoader)
: new ClassFileLocator.Compound(ClassFileLocator.ForClassLoader.of(enterLoader), ClassFileLocator.ForClassLoader.of(exitLoader)));
}
/**
* Implements advice where every matched method is advised by the given type's advisory methods.
*
* @param enterAdvice The type declaring the enter advice.
* @param exitAdvice The type declaring the exit advice.
* @param classFileLocator The class file locator for locating the advisory class's class file.
* @return A method visitor wrapper representing the supplied advice.
*/
public static Advice to(Class<?> enterAdvice, Class<?> exitAdvice, ClassFileLocator classFileLocator) {
return to(new TypeDescription.ForLoadedType(enterAdvice), new TypeDescription.ForLoadedType(exitAdvice), classFileLocator);
}
/**
* Implements advice where every matched method is advised by the given type's advisory methods. Using this method, a non-operational
* class file locator is specified for the advice target. This implies that only advice targets with the <i>inline</i> target set
* to {@code false} are resolvable by the returned instance.
*
* @param enterAdvice The type declaring the enter advice.
* @param exitAdvice The type declaring the exit advice.
* @return A method visitor wrapper representing the supplied advice.
*/
public static Advice to(TypeDescription enterAdvice, TypeDescription exitAdvice) {
return to(enterAdvice, exitAdvice, ClassFileLocator.NoOp.INSTANCE);
}
/**
* Implements advice where every matched method is advised by the given type's advisory methods.
*
* @param enterAdvice The type declaring the enter advice.
* @param exitAdvice The type declaring the exit advice.
* @param classFileLocator The class file locator for locating the advisory class's class file.
* @return A method visitor wrapper representing the supplied advice.
*/
public static Advice to(TypeDescription enterAdvice, TypeDescription exitAdvice, ClassFileLocator classFileLocator) {
return to(enterAdvice, exitAdvice, classFileLocator, Collections.<Dispatcher.OffsetMapping.Factory>emptyList());
}
/**
* Creates a new advice.
*
* @param enterAdvice The type declaring the enter advice.
* @param exitAdvice The type declaring the exit advice.
* @param classFileLocator The class file locator for locating the advisory class's class file.
* @param userFactories A list of custom factories for user generated offset mappings.
* @return A method visitor wrapper representing the supplied advice.
*/
protected static Advice to(TypeDescription enterAdvice,
TypeDescription exitAdvice,
ClassFileLocator classFileLocator,
List<? extends Dispatcher.OffsetMapping.Factory> userFactories) {
Dispatcher.Unresolved methodEnter = Dispatcher.Inactive.INSTANCE, methodExit = Dispatcher.Inactive.INSTANCE;
for (MethodDescription.InDefinedShape methodDescription : enterAdvice.getDeclaredMethods()) {
methodEnter = locate(OnMethodEnter.class, INLINE_ENTER, methodEnter, methodDescription);
}
if (!methodEnter.isAlive()) {
throw new IllegalArgumentException("No enter advice defined by " + enterAdvice);
}
for (MethodDescription.InDefinedShape methodDescription : exitAdvice.getDeclaredMethods()) {
methodExit = locate(OnMethodExit.class, INLINE_EXIT, methodExit, methodDescription);
}
if (!methodExit.isAlive()) {
throw new IllegalArgumentException("No enter advice defined by " + exitAdvice);
}
try {
Dispatcher.Resolved.ForMethodEnter resolved = methodEnter.asMethodEnter(userFactories, methodEnter.isBinary()
? new ClassReader(classFileLocator.locate(enterAdvice.getName()).resolve())
: UNDEFINED);
return new Advice(resolved, methodExit.asMethodExitTo(userFactories, methodExit.isBinary()
? new ClassReader(classFileLocator.locate(exitAdvice.getName()).resolve())
: UNDEFINED, resolved));
} catch (IOException exception) {
throw new IllegalStateException("Error reading class file of " + enterAdvice + " or " + exitAdvice, exception);
}
}
/**
* Locates a dispatcher for the method if available.
*
* @param type The annotation type that indicates a given form of advice that is currently resolved.
* @param property An annotation property that indicates if the advice method should be inlined.
* @param dispatcher Any previous dispatcher that was discovered or {@code null} if no such dispatcher was yet found.
* @param methodDescription The method description that is considered as an advice method.
* @return A resolved dispatcher or {@code null} if no dispatcher was resolved.
*/
private static Dispatcher.Unresolved locate(Class<? extends Annotation> type,
MethodDescription.InDefinedShape property,
Dispatcher.Unresolved dispatcher,
MethodDescription.InDefinedShape methodDescription) {
AnnotationDescription annotation = methodDescription.getDeclaredAnnotations().ofType(type);
if (annotation == null) {
return dispatcher;
} else if (dispatcher.isAlive()) {
throw new IllegalStateException("Duplicate advice for " + dispatcher + " and " + methodDescription);
} else if (!methodDescription.isStatic()) {
throw new IllegalStateException("Advice for " + methodDescription + " is not static");
} else {
return annotation.getValue(property).resolve(Boolean.class)
? new Dispatcher.Inlining(methodDescription)
: new Dispatcher.Delegating(methodDescription);
}
}
/**
* Allows for the configuration of custom annotations that are then bound to a dynamically computed, constant value.
*
* @return A builder for an {@link Advice} instrumentation with custom values.
* @see DynamicValue
*/
public static WithCustomMapping withCustomMapping() {
return new WithCustomMapping();
}
/**
* Returns an ASM visitor wrapper that matches the given matcher and applies this advice to the matched methods.
*
* @param matcher The matcher identifying methods to apply the advice to.
* @return A suitable ASM visitor wrapper with the <i>compute frames</i> option enabled.
*/
public AsmVisitorWrapper.ForDeclaredMethods on(ElementMatcher<? super MethodDescription.InDefinedShape> matcher) {
return new AsmVisitorWrapper.ForDeclaredMethods().method(matcher, this);
}
@Override
public MethodVisitor wrap(TypeDescription instrumentedType,
MethodDescription.InDefinedShape instrumentedMethod,
MethodVisitor methodVisitor,
Implementation.Context implementationContext,
TypePool typePool,
int writerFlags,
int readerFlags) {
return instrumentedMethod.isAbstract() || instrumentedMethod.isNative()
? methodVisitor
: doWrap(instrumentedType, instrumentedMethod, methodVisitor, implementationContext, writerFlags, readerFlags);
}
/**
* Wraps the method visitor to implement this advice.
*
* @param instrumentedType The instrumented type.
* @param instrumentedMethod The instrumented method.
* @param methodVisitor The method visitor to write to.
* @param implementationContext The implementation context to use.
* @param writerFlags The ASM writer flags to use.
* @param readerFlags The ASM reader flags to use.
* @return A method visitor that applies this advice.
*/
protected MethodVisitor doWrap(TypeDescription instrumentedType,
MethodDescription instrumentedMethod,
MethodVisitor methodVisitor,
Implementation.Context implementationContext,
int writerFlags,
int readerFlags) {
methodVisitor = methodEnter.isPrependLineNumber()
? new LineNumberPrependingMethodVisitor(methodVisitor)
: methodVisitor;
if (!methodExit.isAlive()) {
return new AdviceVisitor.WithoutExitAdvice(methodVisitor,
implementationContext,
assigner,
instrumentedType,
instrumentedMethod,
methodEnter,
writerFlags,
readerFlags);
} else if (methodExit.getThrowable().represents(NoExceptionHandler.class)) {
return new AdviceVisitor.WithExitAdvice.WithoutExceptionHandling(methodVisitor,
implementationContext,
assigner,
instrumentedType,
instrumentedMethod,
methodEnter,
methodExit,
writerFlags,
readerFlags);
} else if (instrumentedMethod.isConstructor()) {
throw new IllegalStateException("Cannot catch exception during constructor call for " + instrumentedMethod);
} else {
return new AdviceVisitor.WithExitAdvice.WithExceptionHandling(methodVisitor,
implementationContext,
assigner,
instrumentedType,
instrumentedMethod,
methodEnter,
methodExit,
writerFlags,
readerFlags,
methodExit.getThrowable());
}
}
@Override
public InstrumentedType prepare(InstrumentedType instrumentedType) {
return delegate.prepare(instrumentedType);
}
@Override
public ByteCodeAppender appender(Target implementationTarget) {
return new Appender(this, implementationTarget, delegate.appender(implementationTarget));
}
/**
* Configures this advice to use the specified assigner. Any previous or default assigner is replaced.
*
* @param assigner The assigner to use,
* @return A version of this advice that uses the specified assigner.
*/
public Advice withAssigner(Assigner assigner) {
return new Advice(methodEnter, methodExit, assigner, delegate);
}
/**
* Wraps the supplied implementation to have this advice applied around it.
*
* @param implementation The implementation to wrap.
* @return An implementation that applies the supplied implementation and wraps it with this advice.
*/
public Implementation wrap(Implementation implementation) {
return new Advice(methodEnter, methodExit, assigner, implementation);
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null || getClass() != other.getClass()) return false;
Advice advice = (Advice) other;
return methodEnter.equals(advice.methodEnter)
&& methodExit.equals(advice.methodExit)
&& assigner.equals(advice.assigner)
&& delegate.equals(advice.delegate);
}
@Override
public int hashCode() {
int result = methodEnter.hashCode();
result = 31 * result + methodExit.hashCode();
result = 31 * result + assigner.hashCode();
result = 31 * result + delegate.hashCode();
return result;
}
@Override
public String toString() {
return "Advice{" +
"methodEnter=" + methodEnter +
", methodExit=" + methodExit +
", assigner=" + assigner +
", delegate=" + delegate +
'}';
}
/**
* A handler for computing the instrumented method's size.
*/
protected interface MethodSizeHandler {
/**
* Indicates that a size is not computed but handled directly by ASM.
*/
int UNDEFINED_SIZE = Short.MAX_VALUE;
/**
* Requires a minimum length of the local variable array.
*
* @param localVariableLength The minimal required length of the local variable array.
*/
void requireLocalVariableLength(int localVariableLength);
/**
* A method size handler for the instrumented method.
*/
interface ForInstrumentedMethod extends MethodSizeHandler {
/**
* Binds a method size handler for the entry advice.
*
* @param adviceMethod The method representing the entry advice.
* @return A method size handler for the entry advice.
*/
ForAdvice bindEntry(MethodDescription.InDefinedShape adviceMethod);
/**
* Binds the method size handler for the exit advice.
*
* @param adviceMethod The method representing the exit advice.
* @param skipThrowable {@code true} if the exit advice is not invoked on an exception.
* @return A method size handler for the exit advice.
*/
ForAdvice bindExit(MethodDescription.InDefinedShape adviceMethod, boolean skipThrowable);
/**
* Computes a compound stack size for the advice and the translated instrumented method.
*
* @param stackSize The required stack size of the instrumented method before translation.
* @return The stack size required by the instrumented method and its advice methods.
*/
int compoundStackSize(int stackSize);
/**
* Computes a compound local variable array length for the advice and the translated instrumented method.
*
* @param localVariableLength The required local variable array length of the instrumented method before translation.
* @return The local variable length required by the instrumented method and its advice methods.
*/
int compoundLocalVariableLength(int localVariableLength);
}
/**
* A method size handler for an advice method.
*/
interface ForAdvice extends MethodSizeHandler {
/**
* Records a minimum stack size required by the represented advice method.
*
* @param stackSize The minimum size required by the represented advice method.
*/
void requireStackSize(int stackSize);
/**
* Records the maximum values for stack size and local variable array which are required by the advice method
* for its individual execution without translation.
*
* @param stackSize The minimum required stack size.
* @param localVariableLength The minimum required length of the local variable array.
*/
void recordMaxima(int stackSize, int localVariableLength);
/**
* Records a minimum padding additionally to the computed stack size that is required for implementing this advice method.
*
* @param padding The minimum required padding.
*/
void recordPadding(int padding);
}
/**
* A non-operational method size handler.
*/
enum NoOp implements ForInstrumentedMethod, ForAdvice {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public ForAdvice bindEntry(MethodDescription.InDefinedShape adviceMethod) {
return this;
}
@Override
public ForAdvice bindExit(MethodDescription.InDefinedShape adviceMethod, boolean skipThrowable) {
return this;
}
@Override
public int compoundStackSize(int stackSize) {
return UNDEFINED_SIZE;
}
@Override
public int compoundLocalVariableLength(int localVariableLength) {
return UNDEFINED_SIZE;
}
@Override
public void requireLocalVariableLength(int localVariableLength) {
/* do nothing */
}
@Override
public void requireStackSize(int stackSize) {
/* do nothing */
}
@Override
public void recordMaxima(int stackSize, int localVariableLength) {
/* do nothing */
}
@Override
public void recordPadding(int padding) {
/* do nothing */
}
@Override
public String toString() {
return "Advice.MethodSizeHandler.NoOp." + name();
}
}
/**
* A default implementation for a method size handler.
*/
class Default implements MethodSizeHandler.ForInstrumentedMethod {
/**
* The instrumented method.
*/
private final MethodDescription instrumentedMethod;
/**
* The list of types that the instrumented method requires in addition to the method parameters.
*/
private final TypeList requiredTypes;
/**
* A list of types that are yielded by the instrumented method and available to the exit advice.
*/
private final TypeList yieldedTypes;
/**
* The maximum stack size required by a visited advice method.
*/
private int stackSize;
/**
* The maximum length of the local variable array required by a visited advice method.
*/
private int localVariableLength;
/**
* Creates a new default meta data handler that recomputes the space requirements of an instrumented method.
*
* @param instrumentedMethod The instrumented method.
* @param requiredTypes The types this meta data handler expects to be available additionally to the instrumented method's parameters.
* @param yieldedTypes The types that are expected to be added after the instrumented method returns.
*/
protected Default(MethodDescription instrumentedMethod, TypeList requiredTypes, TypeList yieldedTypes) {
this.instrumentedMethod = instrumentedMethod;
this.requiredTypes = requiredTypes;
this.yieldedTypes = yieldedTypes;
}
/**
* Creates a method size handler applicable for the given instrumented method.
*
* @param instrumentedMethod The instrumented method.
* @param requiredTypes The list of types that the instrumented method requires in addition to the method parameters.
* @param yieldedTypes A list of types that are yielded by the instrumented method and available to the exit advice.
* @param writerFlags The flags supplied to the ASM class writer.
* @return An appropriate method size handler.
*/
protected static MethodSizeHandler.ForInstrumentedMethod of(MethodDescription instrumentedMethod,
List<? extends TypeDescription> requiredTypes,
List<? extends TypeDescription> yieldedTypes,
int writerFlags) {
return (writerFlags & (ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES)) != 0
? NoOp.INSTANCE
: new Default(instrumentedMethod, new TypeList.Explicit(requiredTypes), new TypeList.Explicit(yieldedTypes));
}
@Override
public MethodSizeHandler.ForAdvice bindEntry(MethodDescription.InDefinedShape adviceMethod) {
stackSize = Math.max(stackSize, adviceMethod.getReturnType().getStackSize().getSize());
return new ForAdvice(adviceMethod, new TypeList.Empty(), new TypeList.Explicit(requiredTypes));
}
@Override
public MethodSizeHandler.ForAdvice bindExit(MethodDescription.InDefinedShape adviceMethod, boolean skipThrowable) {
stackSize = Math.max(stackSize, adviceMethod.getReturnType().getStackSize().maximum(skipThrowable
? StackSize.ZERO
: StackSize.SINGLE).getSize());
return new ForAdvice(adviceMethod, new TypeList.Explicit(CompoundList.of(requiredTypes, yieldedTypes)), new TypeList.Empty());
}
@Override
public int compoundStackSize(int stackSize) {
return Math.max(this.stackSize, stackSize);
}
@Override
public int compoundLocalVariableLength(int localVariableLength) {
return Math.max(this.localVariableLength, localVariableLength
+ requiredTypes.getStackSize()
+ yieldedTypes.getStackSize());
}
@Override
public void requireLocalVariableLength(int localVariableLength) {
this.localVariableLength = Math.max(this.localVariableLength, localVariableLength);
}
@Override
public String toString() {
return "Advice.MethodSizeHandler.Default{" +
"instrumentedMethod=" + instrumentedMethod +
", requiredTypes=" + requiredTypes +
", yieldedTypes=" + yieldedTypes +
", stackSize=" + stackSize +
", localVariableLength=" + localVariableLength +
'}';
}
/**
* A method size handler for an advice method.
*/
protected class ForAdvice implements MethodSizeHandler.ForAdvice {
/**
* The advice method.
*/
private final MethodDescription.InDefinedShape adviceMethod;
/**
* A list of types required by this advice method.
*/
private final TypeList requiredTypes;
/**
* A list of types yielded by this advice method.
*/
private final TypeList yieldedTypes;
/**
* The padding that this advice method requires additionally to its computed size.
*/
private int padding;
/**
* Creates a new method size handler for an advice method.
*
* @param adviceMethod The advice method.
* @param requiredTypes A list of types required by this advice method.
* @param yieldedTypes A list of types yielded by this advice method.
*/
protected ForAdvice(MethodDescription.InDefinedShape adviceMethod, TypeList requiredTypes, TypeList yieldedTypes) {
this.adviceMethod = adviceMethod;
this.requiredTypes = requiredTypes;
this.yieldedTypes = yieldedTypes;
stackSize = Math.max(stackSize, adviceMethod.getReturnType().getStackSize().getSize());
}
@Override
public void requireLocalVariableLength(int localVariableLength) {
Default.this.requireLocalVariableLength(localVariableLength);
}
@Override
public void requireStackSize(int stackSize) {
Default.this.stackSize = Math.max(Default.this.stackSize, stackSize);
}
@Override
public void recordMaxima(int stackSize, int localVariableLength) {
Default.this.stackSize = Math.max(Default.this.stackSize, stackSize) + padding;
Default.this.localVariableLength = Math.max(Default.this.localVariableLength, localVariableLength
- adviceMethod.getStackSize()
+ instrumentedMethod.getStackSize()
+ requiredTypes.getStackSize()
+ yieldedTypes.getStackSize());
}
@Override
public void recordPadding(int padding) {
this.padding = Math.max(this.padding, padding);
}
@Override
public String toString() {
return "Advice.MethodSizeHandler.Default.ForAdvice{" +
"adviceMethod=" + adviceMethod +
", requiredTypes=" + requiredTypes +
", yieldedTypes=" + yieldedTypes +
", padding=" + padding +
'}';
}
}
}
}
/**
* A handler for computing and translating stack map frames.
*/
protected interface StackMapFrameHandler {
/**
* Translates a frame.
*
* @param methodVisitor The method visitor to write the frame to.
* @param frameType The frame's type.
* @param localVariableLength The local variable length.
* @param localVariable An array containing the types of the current local variables.
* @param stackSize The size of the operand stack.
* @param stack An array containing the types of the current operand stack.
*/
void translateFrame(MethodVisitor methodVisitor, int frameType, int localVariableLength, Object[] localVariable, int stackSize, Object[] stack);
/**
* Injects a frame indicating the beginning of a return value handler for the currently handled method.
*
* @param methodVisitor The method visitor onto which to apply the stack map frame.
*/
void injectReturnFrame(MethodVisitor methodVisitor);
/**
* Injects a frame indicating the beginning of an exception handler for the currently handled method.
*
* @param methodVisitor The method visitor onto which to apply the stack map frame.
*/
void injectExceptionFrame(MethodVisitor methodVisitor);
/**
* Injects a frame indicating the completion of the currently handled method, i.e. all yielded types were added.
*
* @param methodVisitor The method visitor onto which to apply the stack map frame.
* @param secondary {@code true} if another completion frame for this method was written previously.
*/
void injectCompletionFrame(MethodVisitor methodVisitor, boolean secondary);
/**
* A stack map frame handler for an instrumented method.
*/
interface ForInstrumentedMethod extends StackMapFrameHandler {
/**
* Binds this meta data handler for the entry advice.
*
* @param adviceMethod The entry advice method.
* @return An appropriate meta data handler for the enter method.
*/
ForAdvice bindEntry(MethodDescription.InDefinedShape adviceMethod);
/**
* Binds this meta data handler for the exit advice.
*
* @param adviceMethod The exit advice method.
* @return An appropriate meta data handler for the enter method.
*/
ForAdvice bindExit(MethodDescription.InDefinedShape adviceMethod);
/**
* Returns a hint to supply to a {@link ClassReader} when parsing an advice method.
*
* @return The reader hint to supply to an ASM class reader.
*/
int getReaderHint();
}
/**
* A stack map frame handler for an advice method.
*/
interface ForAdvice extends StackMapFrameHandler {
/* marker interface */
}
/**
* A non-operational stack map frame handler.
*/
enum NoOp implements ForInstrumentedMethod, ForAdvice {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public StackMapFrameHandler.ForAdvice bindEntry(MethodDescription.InDefinedShape adviceMethod) {
return this;
}
@Override
public StackMapFrameHandler.ForAdvice bindExit(MethodDescription.InDefinedShape adviceMethod) {
return this;
}
@Override
public int getReaderHint() {
return ClassReader.SKIP_FRAMES;
}
@Override
public void translateFrame(MethodVisitor methodVisitor,
int frameType,
int localVariableLength,
Object[] localVariable,
int stackSize,
Object[] stack) {
/* do nothing */
}
@Override
public void injectReturnFrame(MethodVisitor methodVisitor) {
/* do nothing */
}
@Override
public void injectExceptionFrame(MethodVisitor methodVisitor) {
/* do nothing */
}
@Override
public void injectCompletionFrame(MethodVisitor methodVisitor, boolean secondary) {
/* do nothing */
}
@Override
public String toString() {
return "Advice.StackMapFrameHandler.NoOp." + name();
}
}
/**
* A default implementation of a stack map frame handler for an instrumented method.
*/
class Default implements ForInstrumentedMethod {
/**
* An empty array indicating an empty frame.
*/
private static final Object[] EMPTY = new Object[0];
/**
* The instrumented type.
*/
private final TypeDescription instrumentedType;
/**
* The instrumented method.
*/
protected final MethodDescription instrumentedMethod;
/**
* A list of intermediate types to be considered as part of the instrumented method's steady signature.
*/
protected final TypeList requiredTypes;
/**
* The types that are expected to be added after the instrumented method returns.
*/
protected final TypeList yieldedTypes;
/**
* {@code true} if the meta data handler is expected to expand its frames.
*/
private final boolean expandFrames;
/**
* The current frame's size divergence from the original local variable array.
*/
private int currentFrameDivergence;
/**
* Creates a new default meta data handler.
*
* @param instrumentedType The instrumented type.
* @param instrumentedMethod The instrumented method.
* @param requiredTypes A list of intermediate types to be considered as part of the instrumented method's steady signature.
* @param yieldedTypes The types that are expected to be added after the instrumented method returns.
* @param expandFrames {@code true} if the meta data handler is expected to expand its frames.
*/
protected Default(TypeDescription instrumentedType,
MethodDescription instrumentedMethod,
TypeList requiredTypes,
TypeList yieldedTypes,
boolean expandFrames) {
this.instrumentedType = instrumentedType;
this.instrumentedMethod = instrumentedMethod;
this.requiredTypes = requiredTypes;
this.yieldedTypes = yieldedTypes;
this.expandFrames = expandFrames;
}
/**
* Creates an appropriate stack map frame handler for an instrumented method.
*
* @param instrumentedType The instrumented type.
* @param instrumentedMethod The instrumented method.
* @param requiredTypes A list of intermediate types to be considered as part of the instrumented method's steady signature.
* @param yieldedTypes The types that are expected to be added after the instrumented method returns.
* @param classFileVersion The instrumented type's class file version.
* @param writerFlags The flags supplied to the ASM writier.
* @param readerFlags The reader flags supplied to the ASM reader.
* @return An approrpiate stack map frame handler for an instrumented method.
*/
protected static ForInstrumentedMethod of(TypeDescription instrumentedType,
MethodDescription instrumentedMethod,
List<? extends TypeDescription> requiredTypes,
List<? extends TypeDescription> yieldedTypes,
ClassFileVersion classFileVersion,
int writerFlags,
int readerFlags) {
return (writerFlags & ClassWriter.COMPUTE_FRAMES) != 0 || classFileVersion.isLessThan(ClassFileVersion.JAVA_V6)
? NoOp.INSTANCE
: new Default(instrumentedType, instrumentedMethod, new TypeList.Explicit(requiredTypes), new TypeList.Explicit(yieldedTypes), (readerFlags & ClassReader.EXPAND_FRAMES) != 0);
}
/**
* Translates a type into a representation of its form inside a stack map frame.
*
* @param typeDescription The type to translate.
* @return A stack entry representation of the supplied type.
*/
protected static Object toFrame(TypeDescription typeDescription) {
if (typeDescription.represents(boolean.class)
|| typeDescription.represents(byte.class)
|| typeDescription.represents(short.class)
|| typeDescription.represents(char.class)
|| typeDescription.represents(int.class)) {
return Opcodes.INTEGER;
} else if (typeDescription.represents(long.class)) {
return Opcodes.LONG;
} else if (typeDescription.represents(float.class)) {
return Opcodes.FLOAT;
} else if (typeDescription.represents(double.class)) {
return Opcodes.DOUBLE;
} else {
return typeDescription.getInternalName();
}
}
@Override
public StackMapFrameHandler.ForAdvice bindEntry(MethodDescription.InDefinedShape adviceMethod) {
return new ForAdvice(adviceMethod, new TypeList.Empty(), requiredTypes, TranslationMode.ENTRY);
}
@Override
public StackMapFrameHandler.ForAdvice bindExit(MethodDescription.InDefinedShape adviceMethod) {
return new ForAdvice(adviceMethod, new TypeList.Explicit(CompoundList.of(requiredTypes, yieldedTypes)), new TypeList.Empty(), TranslationMode.EXIT);
}
@Override
public int getReaderHint() {
return expandFrames
? ClassReader.EXPAND_FRAMES
: AsmVisitorWrapper.NO_FLAGS;
}
@Override
public void translateFrame(MethodVisitor methodVisitor,
int type,
int localVariableLength,
Object[] localVariable,
int stackSize,
Object[] stack) {
translateFrame(methodVisitor,
TranslationMode.COPY,
instrumentedMethod,
requiredTypes,
type,
localVariableLength,
localVariable,
stackSize,
stack);
}
/**
* Translates a frame.
*
* @param methodVisitor The method visitor to write the frame to.
* @param translationMode The translation mode to apply.
* @param methodDescription The method description for which the frame is written.
* @param additionalTypes The additional types to consider part of the instrumented method's parameters.
* @param frameType The frame's type.
* @param localVariableLength The local variable length.
* @param localVariable An array containing the types of the current local variables.
* @param stackSize The size of the operand stack.
* @param stack An array containing the types of the current operand stack.
*/
protected void translateFrame(MethodVisitor methodVisitor,
TranslationMode translationMode,
MethodDescription methodDescription,
TypeList additionalTypes,
int frameType,
int localVariableLength,
Object[] localVariable,
int stackSize,
Object[] stack) {
switch (frameType) {
case Opcodes.F_SAME:
case Opcodes.F_SAME1:
break;
case Opcodes.F_APPEND:
currentFrameDivergence += localVariableLength;
break;
case Opcodes.F_CHOP:
currentFrameDivergence -= localVariableLength;
break;
case Opcodes.F_FULL:
case Opcodes.F_NEW:
Object[] translated = new Object[localVariableLength
- methodDescription.getParameters().size()
- (methodDescription.isStatic() ? 0 : 1)
+ instrumentedMethod.getParameters().size()
+ (instrumentedMethod.isStatic() ? 0 : 1)
+ additionalTypes.size()];
int index = translationMode.copy(instrumentedType, instrumentedMethod, methodDescription, localVariable, translated);
for (TypeDescription typeDescription : additionalTypes) {
translated[index++] = toFrame(typeDescription);
}
System.arraycopy(localVariable,
methodDescription.getParameters().size() + (methodDescription.isStatic() ? 0 : 1),
translated,
index,
translated.length - index);
localVariableLength = translated.length;
localVariable = translated;
currentFrameDivergence = translated.length - index;
break;
default:
throw new IllegalArgumentException("Unexpected frame type: " + frameType);
}
methodVisitor.visitFrame(frameType, localVariableLength, localVariable, stackSize, stack);
}
@Override
public void injectReturnFrame(MethodVisitor methodVisitor) {
if (!expandFrames && currentFrameDivergence == 0 && !instrumentedMethod.isConstructor()) {
if (instrumentedMethod.getReturnType().represents(void.class)) {
methodVisitor.visitFrame(Opcodes.F_SAME, 0, EMPTY, 0, EMPTY);
} else {
methodVisitor.visitFrame(Opcodes.F_SAME1, 0, EMPTY, 1, new Object[]{toFrame(instrumentedMethod.getReturnType().asErasure())});
}
} else {
injectFullFrame(methodVisitor, requiredTypes, instrumentedMethod.getReturnType().represents(void.class)
? Collections.<TypeDescription>emptyList()
: Collections.singletonList(instrumentedMethod.getReturnType().asErasure()));
}
}
@Override
public void injectExceptionFrame(MethodVisitor methodVisitor) {
if (!expandFrames && currentFrameDivergence == 0) {
methodVisitor.visitFrame(Opcodes.F_SAME1, 0, EMPTY, 1, new Object[]{Type.getInternalName(Throwable.class)});
} else {
injectFullFrame(methodVisitor, requiredTypes, Collections.singletonList(TypeDescription.THROWABLE));
}
}
@Override
public void injectCompletionFrame(MethodVisitor methodVisitor, boolean secondary) {
if (!expandFrames && currentFrameDivergence == 0 && (secondary || !instrumentedMethod.isConstructor())) {
if (secondary) {
methodVisitor.visitFrame(Opcodes.F_SAME, 0, EMPTY, 0, EMPTY);
} else {
Object[] local = new Object[yieldedTypes.size()];
int index = 0;
for (TypeDescription typeDescription : yieldedTypes) {
local[index++] = toFrame(typeDescription);
}
methodVisitor.visitFrame(Opcodes.F_APPEND, local.length, local, 0, EMPTY);
}
} else {
injectFullFrame(methodVisitor, CompoundList.of(requiredTypes, yieldedTypes), Collections.<TypeDescription>emptyList());
}
}
/**
* Injects a full stack map frame.
*
* @param methodVisitor The method visitor onto which to write the stack map frame.
* @param typesInArray The types that were added to the local variable array additionally to the values of the instrumented method.
* @param typesOnStack The types currently on the operand stack.
*/
protected void injectFullFrame(MethodVisitor methodVisitor,
List<? extends TypeDescription> typesInArray,
List<? extends TypeDescription> typesOnStack) {
Object[] localVariable = new Object[instrumentedMethod.getParameters().size()
+ (instrumentedMethod.isStatic() ? 0 : 1)
+ typesInArray.size()];
int index = 0;
if (!instrumentedMethod.isStatic()) {
localVariable[index++] = toFrame(instrumentedType);
}
for (TypeDescription typeDescription : instrumentedMethod.getParameters().asTypeList().asErasures()) {
localVariable[index++] = toFrame(typeDescription);
}
for (TypeDescription typeDescription : typesInArray) {
localVariable[index++] = toFrame(typeDescription);
}
index = 0;
Object[] stackType = new Object[typesOnStack.size()];
for (TypeDescription typeDescription : typesOnStack) {
stackType[index++] = toFrame(typeDescription);
}
methodVisitor.visitFrame(expandFrames ? Opcodes.F_NEW : Opcodes.F_FULL, localVariable.length, localVariable, stackType.length, stackType);
currentFrameDivergence = 0;
}
@Override
public String toString() {
return "Advice.StackMapFrameHandler.Default{" +
"instrumentedType=" + instrumentedType +
", instrumentedMethod=" + instrumentedMethod +
", requiredTypes=" + requiredTypes +
", yieldedTypes=" + yieldedTypes +
", expandFrames=" + expandFrames +
", currentFrameDivergence=" + currentFrameDivergence +
'}';
}
/**
* A translation mode that determines how the fixed frames of the instrumented method are written.
*/
protected enum TranslationMode {
/**
* A translation mode that simply copies the original frames which are available when translating frames of the instrumented method.
*/
COPY {
@Override
protected int copy(TypeDescription instrumentedType,
MethodDescription instrumentedMethod,
MethodDescription methodDescription,
Object[] localVariable,
Object[] translated) {
int length = instrumentedMethod.getParameters().size() + (instrumentedMethod.isStatic() ? 0 : 1);
System.arraycopy(localVariable, 0, translated, 0, length);
return length;
}
},
/**
* A translation mode for the entry advice that considers that the {@code this} reference might not be initialized for a constructor.
*/
ENTRY {
@Override
protected int copy(TypeDescription instrumentedType,
MethodDescription instrumentedMethod,
MethodDescription methodDescription,
Object[] localVariable,
Object[] translated) {
int index = 0;
if (!instrumentedMethod.isStatic()) {
translated[index++] = instrumentedMethod.isConstructor()
? Opcodes.UNINITIALIZED_THIS
: toFrame(instrumentedType);
}
for (TypeDescription typeDescription : instrumentedMethod.getParameters().asTypeList().asErasures()) {
translated[index++] = toFrame(typeDescription);
}
return index;
}
},
/**
* A translation mode for an exit advice where the {@code this} reference is always initialized.
*/
EXIT {
@Override
protected int copy(TypeDescription instrumentedType,
MethodDescription instrumentedMethod,
MethodDescription methodDescription,
Object[] localVariable,
Object[] translated) {
int index = 0;
if (!instrumentedMethod.isStatic()) {
translated[index++] = toFrame(instrumentedType);
}
for (TypeDescription typeDescription : instrumentedMethod.getParameters().asTypeList().asErasures()) {
translated[index++] = toFrame(typeDescription);
}
return index;
}
};
/**
* Copies the fixed parameters of the instrumented method onto the operand stack.
*
* @param instrumentedType The instrumented type.
* @param instrumentedMethod The instrumented method.
* @param methodDescription The method for which a frame is created.
* @param localVariable The original local variable array.
* @param translated The array containing the translated frames.
* @return The amount of frames added to the translated frame array.
*/
protected abstract int copy(TypeDescription instrumentedType,
MethodDescription instrumentedMethod,
MethodDescription methodDescription,
Object[] localVariable,
Object[] translated);
@Override
public String toString() {
return "Advice.StackMapFrameHandler.Default.TranslationMode." + name();
}
}
/**
* A stack map frame handler for an advice method.
*/
protected class ForAdvice implements StackMapFrameHandler.ForAdvice {
/**
* The method description for which frames are translated.
*/
protected final MethodDescription.InDefinedShape adviceMethod;
/**
* A list of intermediate types to be considered as part of the instrumented method's steady signature.
*/
protected final TypeList requiredTypes;
/**
* The types that this method yields as a result.
*/
private final TypeList yieldedTypes;
/**
* The translation mode to apply for this advice method. Should be either {@link TranslationMode#ENTRY} or {@link TranslationMode#EXIT}.
*/
protected final TranslationMode translationMode;
/**
* Creates a new meta data handler for an advice method.
*
* @param adviceMethod The method description for which frames are translated.
* @param requiredTypes A list of expected types to be considered as part of the instrumented method's steady signature.
* @param yieldedTypes The types that this method yields as a result.
* @param translationMode The translation mode to apply for this advice method. Should be
* either {@link TranslationMode#ENTRY} or {@link TranslationMode#EXIT}.
*/
protected ForAdvice(MethodDescription.InDefinedShape adviceMethod,
TypeList requiredTypes,
TypeList yieldedTypes,
TranslationMode translationMode) {
this.adviceMethod = adviceMethod;
this.requiredTypes = requiredTypes;
this.yieldedTypes = yieldedTypes;
this.translationMode = translationMode;
}
@Override
public void translateFrame(MethodVisitor methodVisitor,
int type,
int localVariableLength,
Object[] localVariable,
int stackSize,
Object[] stack) {
Default.this.translateFrame(methodVisitor,
translationMode,
adviceMethod,
requiredTypes,
type,
localVariableLength,
localVariable,
stackSize,
stack);
}
@Override
public void injectReturnFrame(MethodVisitor methodVisitor) {
if (!expandFrames && currentFrameDivergence == 0) {
if (yieldedTypes.isEmpty() || adviceMethod.getReturnType().represents(void.class)) {
methodVisitor.visitFrame(Opcodes.F_SAME, 0, EMPTY, 0, EMPTY);
} else {
methodVisitor.visitFrame(Opcodes.F_SAME1, 0, EMPTY, 1, new Object[]{toFrame(adviceMethod.getReturnType().asErasure())});
}
} else {
injectFullFrame(methodVisitor, requiredTypes, yieldedTypes.isEmpty() || adviceMethod.getReturnType().represents(void.class)
? Collections.<TypeDescription>emptyList()
: Collections.singletonList(adviceMethod.getReturnType().asErasure()));
}
}
@Override
public void injectExceptionFrame(MethodVisitor methodVisitor) {
if (!expandFrames && currentFrameDivergence == 0) {
methodVisitor.visitFrame(Opcodes.F_SAME1, 0, EMPTY, 1, new Object[]{Type.getInternalName(Throwable.class)});
} else {
injectFullFrame(methodVisitor, requiredTypes, Collections.singletonList(TypeDescription.THROWABLE));
}
}
@Override
public void injectCompletionFrame(MethodVisitor methodVisitor, boolean secondary) {
if ((!expandFrames && currentFrameDivergence == 0 && yieldedTypes.size() < 4)) {
if (secondary || yieldedTypes.isEmpty()) {
methodVisitor.visitFrame(Opcodes.F_SAME, 0, EMPTY, 0, EMPTY);
} else {
Object[] local = new Object[yieldedTypes.size()];
int index = 0;
for (TypeDescription typeDescription : yieldedTypes) {
local[index++] = toFrame(typeDescription);
}
methodVisitor.visitFrame(Opcodes.F_APPEND, local.length, local, 0, EMPTY);
}
} else {
injectFullFrame(methodVisitor, CompoundList.of(requiredTypes, yieldedTypes), Collections.<TypeDescription>emptyList());
}
}
@Override
public String toString() {
return "Advice.StackMapFrameHandler.Default.ForAdvice{" +
"adviceMethod=" + adviceMethod +
", requiredTypes=" + requiredTypes +
", yieldedTypes=" + yieldedTypes +
", translationMode=" + translationMode +
'}';
}
}
}
}
/**
* A dispatcher for implementing advice.
*/
protected interface Dispatcher {
/**
* Indicates that a method does not represent advice and does not need to be visited.
*/
MethodVisitor IGNORE_METHOD = null;
/**
* Expresses that an annotation should not be visited.
*/
AnnotationVisitor IGNORE_ANNOTATION = null;
/**
* Returns {@code true} if this dispatcher is alive.
*
* @return {@code true} if this dispatcher is alive.
*/
boolean isAlive();
/**
* A dispatcher that is not yet resolved.
*/
interface Unresolved extends Dispatcher {
/**
* Indicates that this dispatcher requires access to the class file declaring the advice method.
*
* @return {@code true} if this dispatcher requires access to the advice method's class file.
*/
boolean isBinary();
/**
* Resolves this dispatcher as a dispatcher for entering a method.
*
* @param userFactories A list of custom factories for binding parameters of an advice method.
* @param classReader A class reader to query for a class file which might be {@code null} if this dispatcher is not binary.
* @return This dispatcher as a dispatcher for entering a method.
*/
Resolved.ForMethodEnter asMethodEnter(List<? extends OffsetMapping.Factory> userFactories,
ClassReader classReader);
/**
* Resolves this dispatcher as a dispatcher for exiting a method.
*
* @param userFactories A list of custom factories for binding parameters of an advice method.
* @param classReader A class reader to query for a class file which might be {@code null} if this dispatcher is not binary.
* @param dispatcher The dispatcher for entering a method.
* @return This dispatcher as a dispatcher for exiting a method.
*/
Resolved.ForMethodExit asMethodExitTo(List<? extends OffsetMapping.Factory> userFactories,
ClassReader classReader,
Resolved.ForMethodEnter dispatcher);
}
/**
* Represents an offset mapping for an advice method to an alternative offset.
*/
interface OffsetMapping {
/**
* Resolves an offset mapping to a given target offset.
*
* @param instrumentedType The instrumented type.
* @param instrumentedMethod The instrumented method for which the mapping is to be resolved.
* @param assigner The assigner to use.
* @param context The context in which the offset mapping is applied.
* @return A suitable target mapping.
*/
Target resolve(TypeDescription instrumentedType, MethodDescription instrumentedMethod, Assigner assigner, Context context);
/**
* A context for applying an {@link OffsetMapping}.
*/
interface Context {
/**
* Returns {@code true} if the advice is applied on a fully initialized instance, i.e. describes if the {@code this}
* instance is available or still uninitialized during calling the advice.
*
* @return {@code true} if the advice is applied onto a fully initialized method.
*/
boolean isInitialized();
/**
* Returns the padding before writing additional values that this context applies.
*
* @return The required padding for this context.
*/
int getPadding();
/**
* A context for an offset mapping describing a method entry.
*/
enum ForMethodEntry implements Context {
/**
* Describes a context for a method entry that is not a constructor.
*/
INITIALIZED(true),
/**
* Describes a context for a method entry that is a constructor.
*/
NON_INITIALIZED(false);
/**
* Resolves an appropriate method entry context for the supplied instrumented method.
*
* @param instrumentedMethod The instrumented method.
* @return An appropriate context.
*/
protected static Context of(MethodDescription instrumentedMethod) {
return instrumentedMethod.isConstructor()
? NON_INITIALIZED
: INITIALIZED;
}
/**
* {@code true} if the method is no constructor, i.e. is invoked for an initialized instance upon entry.
*/
private final boolean initialized;
/**
* Creates a new context for a method entry.
*
* @param initialized {@code true} if the method is no constructor, i.e. is invoked for an initialized instance upon entry.
*/
ForMethodEntry(boolean initialized) {
this.initialized = initialized;
}
@Override
public boolean isInitialized() {
return initialized;
}
@Override
public int getPadding() {
return StackSize.ZERO.getSize();
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.Context.ForMethodEntry." + name();
}
}
/**
* A context for an offset mapping describing a method exit.
*/
enum ForMethodExit implements Context {
/**
* A method exit with a zero sized padding.
*/
ZERO(StackSize.ZERO),
/**
* A method exit with a single slot padding.
*/
SINGLE(StackSize.SINGLE),
/**
* A method exit with a double slot padding.
*/
DOUBLE(StackSize.DOUBLE);
/**
* The padding implied by this method exit.
*/
private final StackSize stackSize;
/**
* Creates a new context for a method exit.
*
* @param stackSize The padding implied by this method exit.
*/
ForMethodExit(StackSize stackSize) {
this.stackSize = stackSize;
}
/**
* Resolves an appropriate method exit context for the supplied entry method type.
*
* @param typeDescription The type that is returned by the enter method.
* @return An appropriate context for the supplied entry method type.
*/
protected static Context of(TypeDefinition typeDescription) {
switch (typeDescription.getStackSize()) {
case ZERO:
return ZERO;
case SINGLE:
return SINGLE;
case DOUBLE:
return DOUBLE;
default:
throw new IllegalStateException("Unknown stack size: " + typeDescription);
}
}
@Override
public boolean isInitialized() {
return true;
}
@Override
public int getPadding() {
return stackSize.getSize();
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.Context.ForMethodExit." + name();
}
}
}
/**
* A target offset of an offset mapping.
*/
interface Target {
/**
* Resolves a read instruction.
*
* @return A stack manipulation that represents a reading of an advice parameter.
*/
StackManipulation resolveRead();
/**
* Resolves a write instruction.
*
* @return A stack manipulation that represents a writing to an advice parameter.
*/
StackManipulation resolveWrite();
/**
* Resolves an increment instruction.
*
* @param value The incrementation value.
* @return A stack manipulation that represents a writing to an advice parameter.
*/
StackManipulation resolveIncrement(int value);
/**
* A target for an offset mapping that represents a non-operational value. All writes are discarded and a value's
* default value is returned upon every read.
*/
abstract class ForDefaultValue implements Target {
/**
* The represented type.
*/
protected final TypeDefinition typeDefinition;
/**
* A stack manipulation to apply after a read instruction.
*/
protected final StackManipulation readAssignment;
/**
* Creates a new target for a default value.
*
* @param typeDefinition The represented type.
* @param readAssignment A stack manipulation to apply after a read instruction.
*/
protected ForDefaultValue(TypeDefinition typeDefinition, StackManipulation readAssignment) {
this.typeDefinition = typeDefinition;
this.readAssignment = readAssignment;
}
@Override
public StackManipulation resolveRead() {
return new StackManipulation.Compound(DefaultValue.of(typeDefinition), readAssignment);
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
ForDefaultValue that = (ForDefaultValue) object;
return typeDefinition.equals(that.typeDefinition) && readAssignment.equals(that.readAssignment);
}
@Override
public int hashCode() {
int result = typeDefinition.hashCode();
result = 31 * result + readAssignment.hashCode();
return result;
}
/**
* A read-only target for a default value.
*/
protected static class ReadOnly extends ForDefaultValue {
/**
* Creates a new writable target for a default value.
*
* @param typeDefinition The represented type.
*/
protected ReadOnly(TypeDefinition typeDefinition) {
this(typeDefinition, StackManipulation.Trivial.INSTANCE);
}
/**
* Creates a new -writable target for a default value.
*
* @param typeDefinition The represented type.
* @param readAssignment A stack manipulation to apply after a read instruction.
*/
protected ReadOnly(TypeDefinition typeDefinition, StackManipulation readAssignment) {
super(typeDefinition, readAssignment);
}
@Override
public StackManipulation resolveWrite() {
throw new IllegalStateException("Cannot write to read-only default value");
}
@Override
public StackManipulation resolveIncrement(int value) {
throw new IllegalStateException("Cannot write to read-only default value");
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.Target.ForDefaultValue.ReadOnly{" +
"typeDefinition=" + typeDefinition +
", readAssignment=" + readAssignment +
"}";
}
}
/**
* A read-write target for a default value.
*/
protected static class ReadWrite extends ForDefaultValue {
/**
* Creates a new read-only target for a default value.
*
* @param typeDefinition The represented type.
*/
protected ReadWrite(TypeDefinition typeDefinition) {
this(typeDefinition, StackManipulation.Trivial.INSTANCE);
}
/**
* Creates a new read-only target for a default value.
*
* @param typeDefinition The represented type.
* @param readAssignment A stack manipulation to apply after a read instruction.
*/
protected ReadWrite(TypeDefinition typeDefinition, StackManipulation readAssignment) {
super(typeDefinition, readAssignment);
}
@Override
public StackManipulation resolveWrite() {
return Removal.pop(typeDefinition);
}
@Override
public StackManipulation resolveIncrement(int value) {
return StackManipulation.Trivial.INSTANCE;
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.Target.ForDefaultValue.ReadWrite{" +
"typeDefinition=" + typeDefinition +
", readAssignment=" + readAssignment +
"}";
}
}
}
/**
* A target for an offset mapping that represents a local variable.
*/
abstract class ForVariable implements Target {
/**
* The represented type.
*/
protected final TypeDefinition typeDefinition;
/**
* The value's offset.
*/
protected final int offset;
/**
* An assignment to execute upon reading a value.
*/
protected final StackManipulation readAssignment;
/**
* Creates a new target for a local variable mapping.
*
* @param typeDefinition The represented type.
* @param offset The value's offset.
* @param readAssignment An assignment to execute upon reading a value.
*/
protected ForVariable(TypeDefinition typeDefinition, int offset, StackManipulation readAssignment) {
this.typeDefinition = typeDefinition;
this.offset = offset;
this.readAssignment = readAssignment;
}
@Override
public StackManipulation resolveRead() {
return new StackManipulation.Compound(MethodVariableAccess.of(typeDefinition).loadFrom(offset), readAssignment);
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
ForVariable that = (ForVariable) object;
return offset == that.offset
&& typeDefinition.equals(that.typeDefinition)
&& readAssignment.equals(that.readAssignment);
}
@Override
public int hashCode() {
int result = typeDefinition.hashCode();
result = 31 * result + offset;
result = 31 * result + readAssignment.hashCode();
return result;
}
/**
* A target for a read-only mapping of a local variable.
*/
protected static class ReadOnly extends ForVariable {
/**
* Creates a read-only mapping for a local variable.
*
* @param parameterDescription The mapped parameter.
* @param readAssignment An assignment to execute upon reading a value.
*/
protected ReadOnly(ParameterDescription parameterDescription, StackManipulation readAssignment) {
this(parameterDescription.getType(), parameterDescription.getOffset(), readAssignment);
}
/**
* Creates a read-only mapping for a local variable.
*
* @param typeDefinition The represented type.
* @param offset The value's offset.
* @param readAssignment An assignment to execute upon reading a value.
*/
protected ReadOnly(TypeDefinition typeDefinition, int offset, StackManipulation readAssignment) {
super(typeDefinition, offset, readAssignment);
}
@Override
public StackManipulation resolveWrite() {
throw new IllegalStateException("Cannot write to read-only parameter " + typeDefinition + " at " + offset);
}
@Override
public StackManipulation resolveIncrement(int value) {
throw new IllegalStateException("Cannot write to read-only variable " + typeDefinition + " at " + offset);
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.Target.ForVariable.ReadOnly{" +
"typeDefinition=" + typeDefinition +
", offset=" + offset +
", readAssignment=" + readAssignment +
"}";
}
}
/**
* A target for a writable mapping of a local variable.
*/
protected static class ReadWrite extends ForVariable {
/**
* A stack manipulation to apply upon a write to the variable.
*/
private final StackManipulation writeAssignment;
/**
* Creates a new target mapping for a writable local variable.
*
* @param parameterDescription The mapped parameter.
* @param readAssignment An assignment to execute upon reading a value.
* @param writeAssignment A stack manipulation to apply upon a write to the variable.
*/
protected ReadWrite(ParameterDescription parameterDescription, StackManipulation readAssignment, StackManipulation writeAssignment) {
this(parameterDescription.getType(), parameterDescription.getOffset(), readAssignment, writeAssignment);
}
/**
* Creates a new target mapping for a writable local variable.
*
* @param typeDefinition The represented type.
* @param offset The value's offset.
* @param readAssignment An assignment to execute upon reading a value.
* @param writeAssignment A stack manipulation to apply upon a write to the variable.
*/
protected ReadWrite(TypeDefinition typeDefinition, int offset, StackManipulation readAssignment, StackManipulation writeAssignment) {
super(typeDefinition, offset, readAssignment);
this.writeAssignment = writeAssignment;
}
@Override
public StackManipulation resolveWrite() {
return new StackManipulation.Compound(writeAssignment, MethodVariableAccess.of(typeDefinition).storeAt(offset));
}
@Override
public StackManipulation resolveIncrement(int value) {
return typeDefinition.represents(int.class)
? MethodVariableAccess.of(typeDefinition).increment(offset, value)
: new StackManipulation.Compound(resolveRead(), IntegerConstant.forValue(1), Addition.INTEGER, resolveWrite());
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
if (!super.equals(object)) return false;
ReadWrite readWrite = (ReadWrite) object;
return writeAssignment.equals(readWrite.writeAssignment);
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + writeAssignment.hashCode();
return result;
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.Target.ForVariable.ReadWrite{" +
"typeDefinition=" + typeDefinition +
", offset=" + offset +
", readAssignment=" + readAssignment +
", writeAssignment=" + writeAssignment +
"}";
}
}
}
/**
* A target mapping for an array of all local variables.
*/
abstract class ForArray implements Target {
/**
* The compound target type.
*/
protected final TypeDescription.Generic target;
/**
* The stack manipulations to apply upon reading a variable array.
*/
protected final List<? extends StackManipulation> valueReads;
/**
* Creates a new target mapping for an array of all local variables.
*
* @param target The compound target type.
* @param valueReads The stack manipulations to apply upon reading a variable array.
*/
protected ForArray(TypeDescription.Generic target, List<? extends StackManipulation> valueReads) {
this.target = target;
this.valueReads = valueReads;
}
@Override
public StackManipulation resolveRead() {
return ArrayFactory.forType(target).withValues(valueReads);
}
@Override
public StackManipulation resolveIncrement(int value) {
throw new IllegalStateException("Cannot increment read-only array value");
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
ForArray forArray = (ForArray) object;
return target.equals(forArray.target) && valueReads.equals(forArray.valueReads);
}
@Override
public int hashCode() {
int result = target.hashCode();
result = 31 * result + valueReads.hashCode();
return result;
}
/**
* A target mapping for a read-only target mapping for an array of local variables.
*/
protected static class ReadOnly extends ForArray {
/**
* Creates a read-only target mapping for an array of all local variables.
*
* @param target The compound target type.
* @param valueReads The stack manipulations to apply upon reading a variable array.
*/
protected ReadOnly(TypeDescription.Generic target, List<? extends StackManipulation> valueReads) {
super(target, valueReads);
}
@Override
public StackManipulation resolveWrite() {
throw new IllegalStateException("Cannot write to read-only array value");
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.Target.ForArray.ReadOnly{" +
"target=" + target +
", valueReads=" + valueReads +
'}';
}
}
/**
* A target mapping for a writable target mapping for an array of local variables.
*/
protected static class ReadWrite extends ForArray {
/**
* The stack manipulations to apply upon writing to a variable array.
*/
private final List<? extends StackManipulation> valueWrites;
/**
* Creates a writable target mapping for an array of all local variables.
*
* @param target The compound target type.
* @param valueReads The stack manipulations to apply upon reading a variable array.
* @param valueWrites The stack manipulations to apply upon writing to a variable array.
*/
protected ReadWrite(TypeDescription.Generic target, List<? extends StackManipulation> valueReads, List<? extends StackManipulation> valueWrites) {
super(target, valueReads);
this.valueWrites = valueWrites;
}
@Override
public StackManipulation resolveWrite() {
return ArrayAccess.of(target).forEach(valueWrites);
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
if (!super.equals(object)) return false;
ReadWrite readWrite = (ReadWrite) object;
return valueWrites.equals(readWrite.valueWrites);
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + valueWrites.hashCode();
return result;
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.Target.ForArray.ReadWrite{" +
"target=" + target +
", valueReads=" + valueReads +
", valueWrites=" + valueWrites +
'}';
}
}
}
/**
* A target for an offset mapping that loads a field value.
*/
abstract class ForField implements Target {
/**
* The field value to load.
*/
protected final FieldDescription fieldDescription;
/**
* The stack manipulation to apply upon a read.
*/
protected final StackManipulation readAssignment;
/**
* Creates a new target for a field value mapping.
*
* @param fieldDescription The field value to load.
* @param readAssignment The stack manipulation to apply upon a read.
*/
protected ForField(FieldDescription fieldDescription, StackManipulation readAssignment) {
this.fieldDescription = fieldDescription;
this.readAssignment = readAssignment;
}
@Override
public StackManipulation resolveRead() {
return new StackManipulation.Compound(fieldDescription.isStatic()
? StackManipulation.Trivial.INSTANCE
: MethodVariableAccess.REFERENCE.loadFrom(0), FieldAccess.forField(fieldDescription).getter(), readAssignment);
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
ForField forField = (ForField) object;
return fieldDescription.equals(forField.fieldDescription) && readAssignment.equals(forField.readAssignment);
}
@Override
public int hashCode() {
int result = fieldDescription.hashCode();
result = 31 * result + readAssignment.hashCode();
return result;
}
/**
* A read-only mapping for a field value.
*/
static class ReadOnly extends ForField {
/**
* Creates a new read-only mapping for a field.
*
* @param fieldDescription The field value to load.
* @param readAssignment The stack manipulation to apply upon a read.
*/
protected ReadOnly(FieldDescription fieldDescription, StackManipulation readAssignment) {
super(fieldDescription, readAssignment);
}
@Override
public StackManipulation resolveWrite() {
throw new IllegalStateException("Cannot write to read-only field value");
}
@Override
public StackManipulation resolveIncrement(int value) {
throw new IllegalStateException("Cannot write to read-only field value");
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.Target.ForField.ReadOnly{" +
"fieldDescription=" + fieldDescription +
", readAssignment=" + readAssignment +
'}';
}
}
/**
* A mapping for a writable field.
*/
static class ReadWrite extends ForField {
/**
* An assignment to apply prior to a field write.
*/
private final StackManipulation writeAssignment;
/**
* Creates a new target for a writable field.
*
* @param fieldDescription The field value to load.
* @param readAssignment The stack manipulation to apply upon a read.
* @param writeAssignment An assignment to apply prior to a field write.
*/
protected ReadWrite(FieldDescription fieldDescription, StackManipulation readAssignment, StackManipulation writeAssignment) {
super(fieldDescription, readAssignment);
this.writeAssignment = writeAssignment;
}
@Override
public StackManipulation resolveWrite() {
StackManipulation preparation;
if (fieldDescription.isStatic()) {
preparation = StackManipulation.Trivial.INSTANCE;
} else {
preparation = new StackManipulation.Compound(
MethodVariableAccess.REFERENCE.loadFrom(0),
Duplication.SINGLE.flipOver(fieldDescription.getType()),
Removal.SINGLE
);
}
return new StackManipulation.Compound(preparation, FieldAccess.forField(fieldDescription).putter());
}
@Override
public StackManipulation resolveIncrement(int value) {
return new StackManipulation.Compound(
resolveRead(),
IntegerConstant.forValue(value),
Addition.INTEGER,
resolveWrite()
);
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
if (!super.equals(object)) return false;
ReadWrite readWrite = (ReadWrite) object;
return writeAssignment.equals(readWrite.writeAssignment);
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + writeAssignment.hashCode();
return result;
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.Target.ForField.ReadWrite{" +
"fieldDescription=" + fieldDescription +
", readAssignment=" + readAssignment +
", writeAssignment=" + writeAssignment +
'}';
}
}
}
/**
* A target for an offset mapping that represents a read-only stack manipulation.
*/
class ForStackManipulation implements Target {
/**
* The represented stack manipulation.
*/
private final StackManipulation stackManipulation;
/**
* Creates a new target for an offset mapping for a stack manipulation.
*
* @param stackManipulation The represented stack manipulation.
*/
protected ForStackManipulation(StackManipulation stackManipulation) {
this.stackManipulation = stackManipulation;
}
/**
* Creates a target for a {@link Method} or {@link Constructor} constant.
*
* @param methodDescription The method or constructor to represent.
* @return A mapping for a method or constructor constant.
*/
protected static Target of(MethodDescription.InDefinedShape methodDescription) {
return new ForStackManipulation(MethodConstant.forMethod(methodDescription));
}
/**
* Creates a target for an offset mapping for a type constant.
*
* @param typeDescription The type constant to represent.
* @return A mapping for a type constant.
*/
protected static Target of(TypeDescription typeDescription) {
return new ForStackManipulation(ClassConstant.of(typeDescription));
}
/**
* Creates a target for an offset mapping for a constant string.
*
* @param value The constant string value to represent.
* @return A mapping for a constant string.
*/
protected static Target of(String value) {
return new ForStackManipulation(new TextConstant(value));
}
/**
* Creates a target for an offset mapping for a constant value.
*
* @param value The constant value to represent.
* @return An appropriate target for an offset mapping.
*/
protected static Target of(Object value) {
if (value instanceof Boolean) {
return new ForStackManipulation(IntegerConstant.forValue((Boolean) value));
} else if (value instanceof Byte) {
return new ForStackManipulation(IntegerConstant.forValue((Byte) value));
} else if (value instanceof Short) {
return new ForStackManipulation(IntegerConstant.forValue((Short) value));
} else if (value instanceof Character) {
return new ForStackManipulation(IntegerConstant.forValue((Character) value));
} else if (value instanceof Integer) {
return new ForStackManipulation(IntegerConstant.forValue((Integer) value));
} else if (value instanceof Long) {
return new ForStackManipulation(LongConstant.forValue((Long) value));
} else if (value instanceof Float) {
return new ForStackManipulation(FloatConstant.forValue((Float) value));
} else if (value instanceof Double) {
return new ForStackManipulation(DoubleConstant.forValue((Double) value));
} else if (value instanceof String) {
return new ForStackManipulation(new TextConstant((String) value));
} else {
throw new IllegalArgumentException("Not a constant value: " + value);
}
}
@Override
public StackManipulation resolveRead() {
return stackManipulation;
}
@Override
public StackManipulation resolveWrite() {
throw new IllegalStateException("Cannot write to constant value: " + stackManipulation);
}
@Override
public StackManipulation resolveIncrement(int value) {
throw new IllegalStateException("Cannot write to constant value: " + stackManipulation);
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
ForStackManipulation that = (ForStackManipulation) object;
return stackManipulation.equals(that.stackManipulation);
}
@Override
public int hashCode() {
return stackManipulation.hashCode();
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.Target.ForStackManipulation{" +
"stackManipulation=" + stackManipulation +
'}';
}
}
}
/**
* Represents a factory for creating a {@link OffsetMapping} for a given parameter.
*/
interface Factory {
/**
* Indicates that an offset mapping is undefined.
*/
OffsetMapping UNDEFINED = null;
/**
* Creates a new offset mapping for the supplied parameter if possible.
*
* @param parameterDescription The parameter description for which to resolve an offset mapping.
* @return A resolved offset mapping or {@code null} if no mapping can be resolved for this parameter.
*/
OffsetMapping make(ParameterDescription.InDefinedShape parameterDescription);
}
/**
* An offset mapping for a given parameter of the instrumented method.
*/
class ForArgument implements OffsetMapping {
/**
* The type expected by the advice method.
*/
private final TypeDescription.Generic target;
/**
* The index of the parameter.
*/
private final int index;
/**
* Determines if the parameter is to be treated as read-only.
*/
private final boolean readOnly;
/**
* The typing to apply when assigning values.
*/
private final Assigner.Typing typing;
/**
* Creates a new offset mapping for a parameter.
*
* @param target The type expected by the advice method.
* @param argument The annotation for which the mapping is to be created.
*/
protected ForArgument(TypeDescription.Generic target, Argument argument) {
this(target, argument.value(), argument.readOnly(), argument.typing());
}
/**
* Creates a new offset mapping for a parameter.
*
* @param parameterDescription The mapped parameter.
* @param readOnly {@code true} if the mapping is read-only.
* @param typing The typing to apply.
*/
protected ForArgument(ParameterDescription parameterDescription, boolean readOnly, Assigner.Typing typing) {
this(parameterDescription.getType(), parameterDescription.getIndex(), readOnly, typing);
}
/**
* Creates a new offset mapping for a parameter of the instrumented method.
*
* @param target The type expected by the advice method.
* @param index The index of the parameter.
* @param readOnly Determines if the parameter is to be treated as read-only.
* @param typing The typing to apply.
*/
protected ForArgument(TypeDescription.Generic target, int index, boolean readOnly, Assigner.Typing typing) {
this.target = target;
this.index = index;
this.readOnly = readOnly;
this.typing = typing;
}
@Override
public Target resolve(TypeDescription instrumentedType, MethodDescription instrumentedMethod, Assigner assigner, Context context) {
ParameterList<?> parameters = instrumentedMethod.getParameters();
if (parameters.size() <= index) {
throw new IllegalStateException(instrumentedMethod + " does not define an index " + index);
}
StackManipulation readAssignment = assigner.assign(parameters.get(index).getType(), target, typing);
if (!readAssignment.isValid()) {
throw new IllegalStateException("Cannot assign " + parameters.get(index) + " to " + target);
} else if (readOnly) {
return new Target.ForVariable.ReadOnly(parameters.get(index), readAssignment);
} else {
StackManipulation writeAssignment = assigner.assign(target, parameters.get(index).getType(), typing);
if (!writeAssignment.isValid()) {
throw new IllegalStateException("Cannot assign " + parameters.get(index) + " to " + target);
}
return new Target.ForVariable.ReadWrite(parameters.get(index), readAssignment, writeAssignment);
}
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
ForArgument that = (ForArgument) object;
return index == that.index
&& readOnly == that.readOnly
&& target.equals(that.target)
&& typing == that.typing;
}
@Override
public int hashCode() {
int result = target.hashCode();
result = 31 * result + index;
result = 31 * result + (readOnly ? 1 : 0);
result = 31 * result + typing.hashCode();
return result;
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.ForArgument{" +
"target=" + target +
", index=" + index +
", readOnly=" + readOnly +
", typing=" + typing +
'}';
}
/**
* A factory for a mapping of a parameter of the instrumented method.
*/
protected enum Factory implements OffsetMapping.Factory {
/**
* A factory that does not allow writing to the mapped parameter.
*/
READ_ONLY(true),
/**
* A factory that allows writing to the mapped parameter.
*/
READ_WRITE(false);
/**
* {@code true} if the parameter is read-only.
*/
private final boolean readOnly;
/**
* Creates a new factory.
*
* @param readOnly {@code true} if the parameter is read-only.
*/
Factory(boolean readOnly) {
this.readOnly = readOnly;
}
@Override
public OffsetMapping make(ParameterDescription.InDefinedShape parameterDescription) {
AnnotationDescription.Loadable<Argument> annotation = parameterDescription.getDeclaredAnnotations().ofType(Argument.class);
if (annotation == null) {
return UNDEFINED;
} else if (readOnly && !annotation.loadSilent().readOnly()) {
throw new IllegalStateException("Cannot define writable field access for " + parameterDescription);
} else {
return new ForArgument(parameterDescription.getType(), annotation.loadSilent());
}
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.ForArgument.Factory." + name();
}
}
}
/**
* An offset mapping that provides access to the {@code this} reference of the instrumented method.
*/
class ForThisReference implements OffsetMapping {
/**
* The offset of the {@code this} reference.
*/
private static final int THIS_REFERENCE = 0;
/**
* The type that the advice method expects for the {@code this} reference.
*/
private final TypeDescription.Generic target;
/**
* Determines if the parameter is to be treated as read-only.
*/
private final boolean readOnly;
/**
* The typing to apply.
*/
private final Assigner.Typing typing;
/**
* {@code true} if the parameter should be bound to {@code null} if the instrumented method is static.
*/
private final boolean optional;
/**
* Creates a new offset mapping for a {@code this} reference.
*
* @param target The type that the advice method expects for the {@code this} reference.
* @param annotation The mapped annotation.
*/
protected ForThisReference(TypeDescription.Generic target, This annotation) {
this(target, annotation.readOnly(), annotation.typing(), annotation.optional());
}
/**
* Creates a new offset mapping for a {@code this} reference.
*
* @param target The type that the advice method expects for the {@code this} reference.
* @param readOnly Determines if the parameter is to be treated as read-only.
* @param typing The typing to apply.
* @param optional {@code true} if the parameter should be bound to {@code null} if the instrumented method is static.
*/
protected ForThisReference(TypeDescription.Generic target, boolean readOnly, Assigner.Typing typing, boolean optional) {
this.target = target;
this.readOnly = readOnly;
this.typing = typing;
this.optional = optional;
}
@Override
public Target resolve(TypeDescription instrumentedType, MethodDescription instrumentedMethod, Assigner assigner, Context context) {
if (instrumentedMethod.isStatic() || !context.isInitialized()) {
if (optional) {
return readOnly
? new Target.ForDefaultValue.ReadOnly(instrumentedType.getDeclaringType())
: new Target.ForDefaultValue.ReadWrite(instrumentedType.getDeclaringType());
} else {
throw new IllegalStateException("Cannot map this reference for static method or constructor start: " + instrumentedMethod);
}
}
StackManipulation readAssignment = assigner.assign(instrumentedType.asGenericType(), target, typing);
if (!readAssignment.isValid()) {
throw new IllegalStateException("Cannot assign " + instrumentedType + " to " + target);
} else if (readOnly) {
return new Target.ForVariable.ReadOnly(instrumentedType.asGenericType(), THIS_REFERENCE, readAssignment);
} else {
StackManipulation writeAssignment = assigner.assign(target, instrumentedType.asGenericType(), typing);
if (!writeAssignment.isValid()) {
throw new IllegalStateException("Cannot assign " + target + " to " + instrumentedType);
}
return new Target.ForVariable.ReadWrite(instrumentedType.asGenericType(), THIS_REFERENCE, readAssignment, writeAssignment);
}
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
ForThisReference that = (ForThisReference) object;
return readOnly == that.readOnly
&& optional == that.optional
&& target.equals(that.target)
&& typing == that.typing;
}
@Override
public int hashCode() {
int result = target.hashCode();
result = 31 * result + (readOnly ? 1 : 0);
result = 31 * result + typing.hashCode();
result = 31 * result + (optional ? 1 : 0);
return result;
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.ForThisReference{" +
"target=" + target +
", readOnly=" + readOnly +
", typing=" + typing +
", optional=" + optional +
'}';
}
/**
* A factory for creating a {@link ForThisReference} offset mapping.
*/
protected enum Factory implements OffsetMapping.Factory {
/**
* A factory that does not allow writing to the mapped parameter.
*/
READ_ONLY(true),
/**
* A factory that allows writing to the mapped parameter.
*/
READ_WRITE(false);
/**
* {@code true} if the parameter is read-only.
*/
private final boolean readOnly;
/**
* Creates a new factory.
*
* @param readOnly {@code true} if the parameter is read-only.
*/
Factory(boolean readOnly) {
this.readOnly = readOnly;
}
@Override
public OffsetMapping make(ParameterDescription.InDefinedShape parameterDescription) {
AnnotationDescription.Loadable<This> annotation = parameterDescription.getDeclaredAnnotations().ofType(This.class);
if (annotation == null) {
return UNDEFINED;
} else if (readOnly && !annotation.loadSilent().readOnly()) {
throw new IllegalStateException("Cannot write to this reference for " + parameterDescription + " in read-only context");
} else {
return new ForThisReference(parameterDescription.getType(), annotation.loadSilent());
}
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.ForThisReference.Factory." + name();
}
}
}
/**
* An offset mapping that maps an array containing all arguments of the instrumented method.
*/
class ForAllArguments implements OffsetMapping {
/**
* The component target type.
*/
private final TypeDescription.Generic target;
/**
* {@code true} if the array is read-only.
*/
private final boolean readOnly;
/**
* The typing to apply.
*/
private final Assigner.Typing typing;
/**
* Creates a new offset mapping for an array containing all arguments.
*
* @param target The component target type.
* @param annotation The mapped annotation.
*/
protected ForAllArguments(TypeDescription.Generic target, AllArguments annotation) {
this(target, annotation.readOnly(), annotation.typing());
}
/**
* Creates a new offset mapping for an array containing all arguments.
*
* @param target The component target type.
* @param readOnly {@code true} if the array is read-only.
* @param typing The typing to apply.
*/
protected ForAllArguments(TypeDescription.Generic target, boolean readOnly, Assigner.Typing typing) {
this.target = target;
this.readOnly = readOnly;
this.typing = typing;
}
@Override
public Target resolve(TypeDescription instrumentedType, MethodDescription instrumentedMethod, Assigner assigner, Context context) {
List<StackManipulation> valueReads = new ArrayList<StackManipulation>(instrumentedMethod.getParameters().size());
for (ParameterDescription parameterDescription : instrumentedMethod.getParameters()) {
StackManipulation readAssignment = assigner.assign(parameterDescription.getType(), target, typing);
if (!readAssignment.isValid()) {
throw new IllegalStateException("Cannot assign " + parameterDescription + " to " + target);
}
valueReads.add(new StackManipulation.Compound(
MethodVariableAccess.of(parameterDescription.getType()).loadFrom(parameterDescription.getOffset()),
readAssignment
));
}
if (readOnly) {
return new Target.ForArray.ReadOnly(target, valueReads);
} else {
List<StackManipulation> valueWrites = new ArrayList<StackManipulation>(instrumentedMethod.getParameters().size());
for (ParameterDescription parameterDescription : instrumentedMethod.getParameters()) {
StackManipulation writeAssignment = assigner.assign(target, parameterDescription.getType(), typing);
if (!writeAssignment.isValid()) {
throw new IllegalStateException("Cannot assign " + target + " to " + parameterDescription);
}
valueWrites.add(new StackManipulation.Compound(
writeAssignment,
MethodVariableAccess.of(parameterDescription.getType()).storeAt(parameterDescription.getOffset())
));
}
return new Target.ForArray.ReadWrite(target, valueReads, valueWrites);
}
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
ForAllArguments that = (ForAllArguments) object;
return readOnly == that.readOnly && target.equals(that.target) && typing == that.typing;
}
@Override
public int hashCode() {
int result = target.hashCode();
result = 31 * result + (readOnly ? 1 : 0);
result = 31 * result + typing.hashCode();
return result;
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.ForAllArguments{" +
"target=" + target +
", readOnly=" + readOnly +
", typing=" + typing +
'}';
}
/**
* A factory for an offset mapping that maps all arguments values of the instrumented method.
*/
protected enum Factory implements OffsetMapping.Factory {
/**
* A read-only offset mapping for an array containing all arguments.
*/
READ_ONLY(true),
/**
* A writable offset mapping for an array containing all arguments.
*/
READ_WRITE(false);
/**
* {@code true} if the mapping is read-only.
*/
private final boolean readOnly;
/**
* Creates a factory for an offset mapping for mapping an array of all arguments.
*
* @param readOnly {@code true} if the mapping is read-only.
*/
Factory(boolean readOnly) {
this.readOnly = readOnly;
}
@Override
public OffsetMapping make(ParameterDescription.InDefinedShape parameterDescription) {
AnnotationDescription.Loadable<AllArguments> annotation = parameterDescription.getDeclaredAnnotations().ofType(AllArguments.class);
if (annotation == null) {
return UNDEFINED;
} else if (!parameterDescription.getType().isArray()) {
throw new IllegalStateException("Cannot use AllArguments annotation on a non-array type");
} else if (readOnly && !annotation.loadSilent().readOnly()) {
throw new IllegalStateException("Cannot define writable field access for " + parameterDescription);
} else {
return new ForAllArguments(parameterDescription.getType().getComponentType(), annotation.loadSilent());
}
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.ForAllArguments.Factory." + name();
}
}
}
/**
* Maps the declaring type of the instrumented method.
*/
enum ForInstrumentedType implements OffsetMapping {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public Target resolve(TypeDescription instrumentedType, MethodDescription instrumentedMethod, Assigner assigner, Context context) {
return Target.ForStackManipulation.of(instrumentedType);
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.ForInstrumentedType." + name();
}
}
/**
* Maps a constant representing the instrumented method.
*/
enum ForInstrumentedMethod implements OffsetMapping {
/**
* A constant that must be a {@link Method} instance.
*/
METHOD {
@Override
protected boolean isRepresentable(MethodDescription instrumentedMethod) {
return instrumentedMethod.isMethod();
}
},
/**
* A constant that must be a {@link Constructor} instance.
*/
CONSTRUCTOR {
@Override
protected boolean isRepresentable(MethodDescription instrumentedMethod) {
return instrumentedMethod.isConstructor();
}
},
/**
* A constant that must be a {@code java.lang.reflect.Executable} instance.
*/
EXECUTABLE {
@Override
protected boolean isRepresentable(MethodDescription instrumentedMethod) {
return true;
}
};
@Override
public Target resolve(TypeDescription instrumentedType, MethodDescription instrumentedMethod, Assigner assigner, Context context) {
if (!isRepresentable(instrumentedMethod)) {
throw new IllegalStateException("Cannot represent " + instrumentedMethod + " as given method constant");
}
return Target.ForStackManipulation.of(instrumentedMethod.asDefined());
}
/**
* Checks if the supplied method is representable for the assigned offset mapping.
*
* @param instrumentedMethod The instrumented method to represent.
* @return {@code true} if this method is representable.
*/
protected abstract boolean isRepresentable(MethodDescription instrumentedMethod);
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.ForInstrumentedMethod." + name();
}
}
/**
* An offset mapping for a field.
*/
abstract class ForField implements OffsetMapping {
/**
* The {@link FieldValue#value()} method.
*/
private static final MethodDescription.InDefinedShape VALUE;
/**
* The {@link FieldValue#declaringType()}} method.
*/
private static final MethodDescription.InDefinedShape DECLARING_TYPE;
/**
* The {@link FieldValue#readOnly()}} method.
*/
private static final MethodDescription.InDefinedShape READ_ONLY;
/**
* The {@link FieldValue#typing()}} method.
*/
private static final MethodDescription.InDefinedShape TYPING;
/*
* Looks up all annotation properties to avoid loading of the declaring field type.
*/
static {
MethodList<MethodDescription.InDefinedShape> methods = new TypeDescription.ForLoadedType(FieldValue.class).getDeclaredMethods();
VALUE = methods.filter(named("value")).getOnly();
DECLARING_TYPE = methods.filter(named("declaringType")).getOnly();
READ_ONLY = methods.filter(named("readOnly")).getOnly();
TYPING = methods.filter(named("typing")).getOnly();
}
/**
* The expected type that the field can be assigned to.
*/
protected final TypeDescription.Generic target;
/**
* The name of the field.
*/
protected final String name;
/**
* {@code true} if this mapping is read-only.
*/
protected final boolean readOnly;
/**
* The typing to apply.
*/
protected final Assigner.Typing typing;
/**
* Creates an offset mapping for a field.
*
* @param target The target type.
* @param name The name of the field.
* @param readOnly {@code true} if this mapping is read-only.
* @param typing The typing to apply.
*/
protected ForField(TypeDescription.Generic target, String name, boolean readOnly, Assigner.Typing typing) {
this.target = target;
this.name = name;
this.readOnly = readOnly;
this.typing = typing;
}
@Override
public Target resolve(TypeDescription instrumentedType, MethodDescription instrumentedMethod, Assigner assigner, Context context) {
FieldLocator.Resolution resolution = fieldLocator(instrumentedType).locate(name);
if (!resolution.isResolved()) {
throw new IllegalStateException("Cannot locate field named " + name + " for " + instrumentedMethod);
} else if (!resolution.getField().isStatic() && instrumentedMethod.isStatic()) {
throw new IllegalStateException("Cannot read non-static field " + resolution.getField() + " from static method " + instrumentedMethod);
} else if (!context.isInitialized() && !resolution.getField().isStatic()) {
throw new IllegalStateException("Cannot access non-static field before calling constructor: " + instrumentedMethod);
}
StackManipulation readAssignment = assigner.assign(resolution.getField().getType(), target, typing);
if (!readAssignment.isValid()) {
throw new IllegalStateException("Cannot assign " + resolution.getField() + " to " + target);
} else if (readOnly) {
return new Target.ForField.ReadOnly(resolution.getField(), readAssignment);
} else {
StackManipulation writeAssignment = assigner.assign(target, resolution.getField().getType(), typing);
if (!writeAssignment.isValid()) {
throw new IllegalStateException("Cannot assign " + target + " to " + resolution.getField());
}
return new Target.ForField.ReadWrite(resolution.getField().asDefined(), readAssignment, writeAssignment);
}
}
/**
* Returns a field locator for this instance.
*
* @param instrumentedType The instrumented type.
* @return An appropriate field locator.
*/
protected abstract FieldLocator fieldLocator(TypeDescription instrumentedType);
/**
* An offset mapping for a field with an implicit declaring type.
*/
protected static class WithImplicitType extends ForField {
/**
* Creates an offset mapping for a field with an implicit declaring type.
*
* @param target The target type.
* @param annotation The annotation to represent.
*/
protected WithImplicitType(TypeDescription.Generic target, AnnotationDescription.Loadable<FieldValue> annotation) {
this(target,
annotation.getValue(VALUE).resolve(String.class),
annotation.getValue(READ_ONLY).resolve(Boolean.class),
annotation.getValue(TYPING).loadSilent(Assigner.Typing.class.getClassLoader()).resolve(Assigner.Typing.class));
}
/**
* Creates an offset mapping for a field with an implicit declaring type.
*
* @param target The target type.
* @param name The name of the field.
* @param readOnly {@code true} if the field is read-only.
* @param typing The typing to apply.
*/
protected WithImplicitType(TypeDescription.Generic target, String name, boolean readOnly, Assigner.Typing typing) {
super(target, name, readOnly, typing);
}
@Override
protected FieldLocator fieldLocator(TypeDescription instrumentedType) {
return new FieldLocator.ForClassHierarchy(instrumentedType);
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.ForField.WithImplicitType{" +
"target=" + target +
", name=" + name +
", readOnly=" + readOnly +
", typing=" + typing +
'}';
}
}
/**
* An offset mapping for a field with an explicit declaring type.
*/
protected static class WithExplicitType extends ForField {
/**
* The type declaring the field.
*/
private final TypeDescription declaringType;
/**
* Creates an offset mapping for a field with an explicit declaring type.
*
* @param target The target type.
* @param annotation The annotation to represent.
* @param declaringType The field's declaring type.
*/
protected WithExplicitType(TypeDescription.Generic target, AnnotationDescription.Loadable<FieldValue> annotation, TypeDescription declaringType) {
this(target,
annotation.getValue(VALUE).resolve(String.class),
annotation.getValue(READ_ONLY).resolve(Boolean.class),
annotation.getValue(TYPING).loadSilent(Assigner.Typing.class.getClassLoader()).resolve(Assigner.Typing.class),
declaringType);
}
/**
* Creates an offset mapping for a field with an explicit declaring type.
*
* @param target The target type.
* @param name The name of the field.
* @param readOnly {@code true} if the field is read-only.
* @param typing The typing to apply.
* @param declaringType The field's declaring type.
*/
protected WithExplicitType(TypeDescription.Generic target, String name, boolean readOnly, Assigner.Typing typing, TypeDescription declaringType) {
super(target, name, readOnly, typing);
this.declaringType = declaringType;
}
@Override
protected FieldLocator fieldLocator(TypeDescription instrumentedType) {
if (!instrumentedType.isAssignableTo(declaringType)) {
throw new IllegalStateException(declaringType + " is no super type of " + instrumentedType);
}
return new FieldLocator.ForExactType(declaringType);
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
WithExplicitType that = (WithExplicitType) object;
return declaringType.equals(that.declaringType);
}
@Override
public int hashCode() {
return declaringType.hashCode();
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.ForField.WithExplicitType{" +
"target=" + target +
", name=" + name +
", readOnly=" + readOnly +
", typing=" + typing +
", declaringType=" + declaringType +
'}';
}
}
/**
* A factory for a {@link ForField} offset mapping.
*/
protected enum Factory implements OffsetMapping.Factory {
/**
* A factory that does not allow writing to the mapped parameter.
*/
READ_ONLY(true),
/**
* A factory that allows writing to the mapped parameter.
*/
READ_WRITE(false);
/**
* {@code true} if the parameter is read-only.
*/
private final boolean readOnly;
/**
* Creates a new factory.
*
* @param readOnly {@code true} if the parameter is read-only.
*/
Factory(boolean readOnly) {
this.readOnly = readOnly;
}
@Override
public OffsetMapping make(ParameterDescription.InDefinedShape parameterDescription) {
AnnotationDescription.Loadable<FieldValue> annotation = parameterDescription.getDeclaredAnnotations().ofType(FieldValue.class);
if (annotation == null) {
return UNDEFINED;
} else if (readOnly && !annotation.getValue(ForField.READ_ONLY).resolve(Boolean.class)) {
throw new IllegalStateException("Cannot write to field for " + parameterDescription + " in read-only context");
} else {
TypeDescription declaringType = annotation.getValue(DECLARING_TYPE).resolve(TypeDescription.class);
return declaringType.represents(void.class)
? new WithImplicitType(parameterDescription.getType(), annotation)
: new WithExplicitType(parameterDescription.getType(), annotation, declaringType);
}
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.ForField.Factory." + name();
}
}
}
/**
* An offset mapping for the {@link Advice.Origin} annotation.
*/
class ForOrigin implements OffsetMapping {
/**
* The delimiter character.
*/
private static final char DELIMITER = '
/**
* The escape character.
*/
private static final char ESCAPE = '\\';
/**
* The renderers to apply.
*/
private final List<Renderer> renderers;
/**
* Creates a new offset mapping for an origin value.
*
* @param renderers The renderers to apply.
*/
protected ForOrigin(List<Renderer> renderers) {
this.renderers = renderers;
}
/**
* Parses a pattern of an origin annotation.
*
* @param pattern The supplied pattern.
* @return An appropriate offset mapping.
*/
protected static OffsetMapping parse(String pattern) {
if (pattern.equals(Origin.DEFAULT)) {
return new ForOrigin(Collections.<Renderer>singletonList(Renderer.ForStringRepresentation.INSTANCE));
} else {
List<Renderer> renderers = new ArrayList<Renderer>(pattern.length());
int from = 0;
for (int to = pattern.indexOf(DELIMITER); to != -1; to = pattern.indexOf(DELIMITER, from)) {
if (to != 0 && pattern.charAt(to - 1) == ESCAPE && (to == 1 || pattern.charAt(to - 2) != ESCAPE)) {
renderers.add(new Renderer.ForConstantValue(pattern.substring(from, Math.max(0, to - 1)) + DELIMITER));
from = to + 1;
continue;
} else if (pattern.length() == to + 1) {
throw new IllegalStateException("Missing sort descriptor for " + pattern + " at index " + to);
}
renderers.add(new Renderer.ForConstantValue(pattern.substring(from, to).replace("" + ESCAPE + ESCAPE, "" + ESCAPE)));
switch (pattern.charAt(to + 1)) {
case Renderer.ForMethodName.SYMBOL:
renderers.add(Renderer.ForMethodName.INSTANCE);
break;
case Renderer.ForTypeName.SYMBOL:
renderers.add(Renderer.ForTypeName.INSTANCE);
break;
case Renderer.ForDescriptor.SYMBOL:
renderers.add(Renderer.ForDescriptor.INSTANCE);
break;
case Renderer.ForReturnTypeName.SYMBOL:
renderers.add(Renderer.ForReturnTypeName.INSTANCE);
break;
case Renderer.ForJavaSignature.SYMBOL:
renderers.add(Renderer.ForJavaSignature.INSTANCE);
break;
default:
throw new IllegalStateException("Illegal sort descriptor " + pattern.charAt(to + 1) + " for " + pattern);
}
from = to + 2;
}
renderers.add(new Renderer.ForConstantValue(pattern.substring(from)));
return new ForOrigin(renderers);
}
}
@Override
public Target resolve(TypeDescription instrumentedType, MethodDescription instrumentedMethod, Assigner assigner, Context context) {
StringBuilder stringBuilder = new StringBuilder();
for (Renderer renderer : renderers) {
stringBuilder.append(renderer.apply(instrumentedType, instrumentedMethod));
}
return Target.ForStackManipulation.of(stringBuilder.toString());
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null || getClass() != other.getClass()) return false;
ForOrigin forOrigin = (ForOrigin) other;
return renderers.equals(forOrigin.renderers);
}
@Override
public int hashCode() {
return renderers.hashCode();
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.ForOrigin{" +
"renderers=" + renderers +
'}';
}
/**
* A renderer for an origin pattern element.
*/
protected interface Renderer {
/**
* Returns a string representation for this renderer.
*
* @param instrumentedType The instrumented type.
* @param instrumentedMethod The instrumented method.
* @return The string representation.
*/
String apply(TypeDescription instrumentedType, MethodDescription instrumentedMethod);
/**
* A renderer for a method's internal name.
*/
enum ForMethodName implements Renderer {
/**
* The singleton instance.
*/
INSTANCE;
/**
* The method name symbol.
*/
public static final char SYMBOL = 'm';
@Override
public String apply(TypeDescription instrumentedType, MethodDescription instrumentedMethod) {
return instrumentedMethod.getInternalName();
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.ForOrigin.Renderer.ForMethodName." + name();
}
}
/**
* A renderer for a method declaring type's binary name.
*/
enum ForTypeName implements Renderer {
/**
* The singleton instance.
*/
INSTANCE;
/**
* The type name symbol.
*/
public static final char SYMBOL = 't';
@Override
public String apply(TypeDescription instrumentedType, MethodDescription instrumentedMethod) {
return instrumentedType.getName();
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.ForOrigin.Renderer.ForTypeName." + name();
}
}
/**
* A renderer for a method descriptor.
*/
enum ForDescriptor implements Renderer {
/**
* The singleton instance.
*/
INSTANCE;
/**
* The descriptor symbol.
*/
public static final char SYMBOL = 'd';
@Override
public String apply(TypeDescription instrumentedType, MethodDescription instrumentedMethod) {
return instrumentedMethod.getDescriptor();
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.ForOrigin.Renderer.ForDescriptor." + name();
}
}
/**
* A renderer for a method's Java signature in binary form.
*/
enum ForJavaSignature implements Renderer {
/**
* The singleton instance.
*/
INSTANCE;
/**
* The signature symbol.
*/
public static final char SYMBOL = 's';
@Override
public String apply(TypeDescription instrumentedType, MethodDescription instrumentedMethod) {
StringBuilder stringBuilder = new StringBuilder("(");
boolean comma = false;
for (TypeDescription typeDescription : instrumentedMethod.getParameters().asTypeList().asErasures()) {
if (comma) {
stringBuilder.append(',');
} else {
comma = true;
}
stringBuilder.append(typeDescription.getName());
}
return stringBuilder.append(')').toString();
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.ForOrigin.Renderer.ForJavaSignature." + name();
}
}
/**
* A renderer for a method's return type in binary form.
*/
enum ForReturnTypeName implements Renderer {
/**
* The singleton instance.
*/
INSTANCE;
/**
* The return type symbol.
*/
public static final char SYMBOL = 'r';
@Override
public String apply(TypeDescription instrumentedType, MethodDescription instrumentedMethod) {
return instrumentedMethod.getReturnType().asErasure().getName();
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.ForOrigin.Renderer.ForReturnTypeName." + name();
}
}
/**
* A renderer for a method's {@link Object#toString()} representation.
*/
enum ForStringRepresentation implements Renderer {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public String apply(TypeDescription instrumentedType, MethodDescription instrumentedMethod) {
return instrumentedMethod.toString();
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.ForOrigin.Renderer.ForStringRepresentation." + name();
}
}
/**
* A renderer for a constant value.
*/
class ForConstantValue implements Renderer {
/**
* The constant value.
*/
private final String value;
/**
* Creates a new renderer for a constant value.
*
* @param value The constant value.
*/
protected ForConstantValue(String value) {
this.value = value;
}
@Override
public String apply(TypeDescription instrumentedType, MethodDescription instrumentedMethod) {
return value;
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null || getClass() != other.getClass()) return false;
ForConstantValue that = (ForConstantValue) other;
return value.equals(that.value);
}
@Override
public int hashCode() {
return value.hashCode();
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.ForOrigin.Renderer.ForConstantValue{" +
"value='" + value + '\'' +
'}';
}
}
}
/**
* A factory for a method origin.
*/
protected enum Factory implements OffsetMapping.Factory {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public OffsetMapping make(ParameterDescription.InDefinedShape parameterDescription) {
AnnotationDescription.Loadable<Origin> origin = parameterDescription.getDeclaredAnnotations().ofType(Origin.class);
if (origin == null) {
return UNDEFINED;
} else if (parameterDescription.getType().asErasure().represents(Class.class)) {
return OffsetMapping.ForInstrumentedType.INSTANCE;
} else if (parameterDescription.getType().asErasure().represents(Method.class)) {
return OffsetMapping.ForInstrumentedMethod.METHOD;
} else if (parameterDescription.getType().asErasure().represents(Constructor.class)) {
return OffsetMapping.ForInstrumentedMethod.CONSTRUCTOR;
} else if (JavaType.EXECUTABLE.getTypeStub().equals(parameterDescription.getType().asErasure())) {
return OffsetMapping.ForInstrumentedMethod.EXECUTABLE;
} else if (parameterDescription.getType().asErasure().isAssignableFrom(String.class)) {
return ForOrigin.parse(origin.loadSilent().value());
} else {
throw new IllegalStateException("Non-supported type " + parameterDescription.getType() + " for @Origin annotation");
}
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.ForOrigin.Factory." + name();
}
}
}
/**
* An offset mapping for a parameter where assignments are fully ignored and that always return the parameter type's default value.
*/
class ForUnusedValue implements OffsetMapping {
/**
* The unused type.
*/
private final TypeDefinition target;
/**
* Creates a new offset mapping for an unused type.
*
* @param target The unused type.
*/
protected ForUnusedValue(TypeDefinition target) {
this.target = target;
}
@Override
public Target resolve(TypeDescription instrumentedType, MethodDescription instrumentedMethod, Assigner assigner, Context context) {
return new Target.ForDefaultValue.ReadWrite(target);
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
ForUnusedValue that = (ForUnusedValue) object;
return target.equals(that.target);
}
@Override
public int hashCode() {
return target.hashCode();
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.ForUnusedValue{" +
"target=" + target +
'}';
}
/**
* A factory for an offset mapping for an unused value.
*/
enum Factory implements OffsetMapping.Factory {
/**
* A factory for representing an unused value.
*/
INSTANCE;
@Override
public OffsetMapping make(ParameterDescription.InDefinedShape parameterDescription) {
return parameterDescription.getDeclaredAnnotations().isAnnotationPresent(Unused.class)
? new ForUnusedValue(parameterDescription.getType())
: UNDEFINED;
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.ForUnusedValue.Factory." + name();
}
}
}
/**
* An offset mapping for a parameter where assignments are fully ignored and that is assigned a boxed version of the instrumented
* method's return valueor {@code null} if the return type is not primitive or {@code void}.
*/
enum ForStubValue implements OffsetMapping, Factory {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public Target resolve(TypeDescription instrumentedType, MethodDescription instrumentedMethod, Assigner assigner, Context context) {
return new Target.ForDefaultValue.ReadOnly(instrumentedMethod.getReturnType(), assigner.assign(instrumentedMethod.getReturnType(),
TypeDescription.Generic.OBJECT,
Assigner.Typing.DYNAMIC));
}
@Override
public OffsetMapping make(ParameterDescription.InDefinedShape parameterDescription) {
if (!parameterDescription.getDeclaredAnnotations().isAnnotationPresent(StubValue.class)) {
return UNDEFINED;
} else if (!parameterDescription.getType().represents(Object.class)) {
throw new IllegalStateException("Cannot use StubValue on non-Object parameter type " + parameterDescription);
} else {
return this;
}
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.ForStubValue." + name();
}
}
/**
* An offset mapping that provides access to the value that is returned by the enter advice.
*/
class ForEnterValue implements OffsetMapping {
/**
* The represented target type.
*/
private final TypeDescription.Generic target;
/**
* The enter type.
*/
private final TypeDescription.Generic enterType;
/**
* {@code true} if the annotated value is read-only.
*/
private final boolean readOnly;
/**
* The typing to apply.
*/
private final Assigner.Typing typing;
/**
* Creates a new offset mapping for the enter type.
*
* @param target The represented target type.
* @param enterType The enter type.
* @param enter The represented annotation.
*/
protected ForEnterValue(TypeDescription.Generic target, TypeDescription.Generic enterType, Enter enter) {
this(target, enterType, enter.readOnly(), enter.typing());
}
/**
* Creates a new offset mapping for the enter type.
*
* @param target The represented target type.
* @param enterType The enter type.
* @param readOnly {@code true} if the annotated value is read-only.
* @param typing The typing to apply.
*/
protected ForEnterValue(TypeDescription.Generic target, TypeDescription.Generic enterType, boolean readOnly, Assigner.Typing typing) {
this.target = target;
this.enterType = enterType;
this.readOnly = readOnly;
this.typing = typing;
}
@Override
public Target resolve(TypeDescription instrumentedType, MethodDescription instrumentedMethod, Assigner assigner, Context context) {
StackManipulation readAssignment = assigner.assign(enterType, target, typing);
if (!readAssignment.isValid()) {
throw new IllegalStateException("Cannot assign " + enterType + " to " + target);
} else if (readOnly) {
return new Target.ForVariable.ReadOnly(target, instrumentedMethod.getStackSize(), readAssignment);
} else {
StackManipulation writeAssignment = assigner.assign(target, enterType, typing);
if (!writeAssignment.isValid()) {
throw new IllegalStateException("Cannot assign " + target + " to " + enterType);
}
return new Target.ForVariable.ReadWrite(target, instrumentedMethod.getStackSize(), readAssignment, writeAssignment);
}
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
ForEnterValue that = (ForEnterValue) object;
return readOnly == that.readOnly
&& target.equals(that.target)
&& enterType.equals(that.enterType)
&& typing == that.typing;
}
@Override
public int hashCode() {
int result = target.hashCode();
result = 31 * result + enterType.hashCode();
result = 31 * result + (readOnly ? 1 : 0);
result = 31 * result + typing.hashCode();
return result;
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.ForEnterValue{" +
"target=" + target +
", enterType=" + enterType +
", readOnly=" + readOnly +
", typing=" + typing +
'}';
}
/**
* A factory for creating a {@link ForEnterValue} offset mapping.
*/
protected static class Factory implements OffsetMapping.Factory {
/**
* The supplied type of the enter method.
*/
private final TypeDefinition enterType;
/**
* Indicates that the mapped parameter is read-only.
*/
private final boolean readOnly;
/**
* Creates a new factory for creating a {@link ForEnterValue} offset mapping.
*
* @param enterType The supplied type of the enter method.
* @param readOnly Indicates that the mapped parameter is read-only.
*/
protected Factory(TypeDefinition enterType, boolean readOnly) {
this.enterType = enterType;
this.readOnly = readOnly;
}
@Override
public OffsetMapping make(ParameterDescription.InDefinedShape parameterDescription) {
AnnotationDescription.Loadable<Enter> annotation = parameterDescription.getDeclaredAnnotations().ofType(Enter.class);
if (annotation != null) {
return new ForEnterValue(parameterDescription.getType(), enterType.asGenericType(), annotation.loadSilent());
} else {
return UNDEFINED;
}
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null || getClass() != other.getClass()) return false;
Factory factory = (Factory) other;
return readOnly == factory.readOnly && enterType.equals(factory.enterType);
}
@Override
public int hashCode() {
int result = enterType.hashCode();
result = 31 * result + (readOnly ? 1 : 0);
return result;
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.ForEnterValue.Factory{" +
"enterType=" + enterType +
"m readOnly=" + readOnly +
'}';
}
}
}
/**
* An offset mapping that provides access to the value that is returned by the instrumented method.
*/
class ForReturnValue implements OffsetMapping {
/**
* The type that the advice method expects for the return value.
*/
private final TypeDescription.Generic target;
/**
* Determines if the parameter is to be treated as read-only.
*/
private final boolean readOnly;
/**
* The typing to apply.
*/
private final Assigner.Typing typing;
/**
* Creates a new offset mapping for a return value.
*
* @param target The type that the advice method expects for the return value.
* @param annotation The annotation being bound.
*/
protected ForReturnValue(TypeDescription.Generic target, Return annotation) {
this(target, annotation.readOnly(), annotation.typing());
}
/**
* Creates a new offset mapping for a return value.
*
* @param target The type that the advice method expects for the return value.
* @param readOnly Determines if the parameter is to be treated as read-only.
* @param typing The typing to apply.
*/
protected ForReturnValue(TypeDescription.Generic target, boolean readOnly, Assigner.Typing typing) {
this.target = target;
this.readOnly = readOnly;
this.typing = typing;
}
@Override
public Target resolve(TypeDescription instrumentedType, MethodDescription instrumentedMethod, Assigner assigner, Context context) {
int offset = instrumentedMethod.getStackSize() + context.getPadding();
StackManipulation readAssignment = assigner.assign(instrumentedMethod.getReturnType(), target, typing);
if (!readAssignment.isValid()) {
throw new IllegalStateException("Cannot assign " + instrumentedMethod.getReturnType() + " to " + target);
} else if (readOnly) {
return instrumentedMethod.getReturnType().represents(void.class)
? new Target.ForDefaultValue.ReadOnly(target)
: new Target.ForVariable.ReadOnly(instrumentedMethod.getReturnType(), offset, readAssignment);
} else {
StackManipulation writeAssignment = assigner.assign(target, instrumentedMethod.getReturnType(), typing);
if (!writeAssignment.isValid()) {
throw new IllegalStateException("Cannot assign " + target + " to " + instrumentedMethod.getReturnType());
}
return instrumentedMethod.getReturnType().represents(void.class)
? new Target.ForDefaultValue.ReadWrite(target)
: new Target.ForVariable.ReadWrite(instrumentedMethod.getReturnType(), offset, readAssignment, writeAssignment);
}
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
ForReturnValue that = (ForReturnValue) object;
return readOnly == that.readOnly
&& target.equals(that.target)
&& typing == that.typing;
}
@Override
public int hashCode() {
int result = target.hashCode();
result = 31 * result + (readOnly ? 1 : 0);
result = 31 * result + typing.hashCode();
return result;
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.ForReturnValue{" +
"target=" + target +
", readOnly=" + readOnly +
", typing=" + typing +
'}';
}
/**
* A factory for creating a {@link ForReturnValue} offset mapping.
*/
protected enum Factory implements OffsetMapping.Factory {
/**
* A factory that does not allow writing to the mapped parameter.
*/
READ_ONLY(true),
/**
* A factory that allows writing to the mapped parameter.
*/
READ_WRITE(false);
/**
* {@code true} if the parameter is read-only.
*/
private final boolean readOnly;
/**
* Creates a new factory.
*
* @param readOnly {@code true} if the parameter is read-only.
*/
Factory(boolean readOnly) {
this.readOnly = readOnly;
}
@Override
public OffsetMapping make(ParameterDescription.InDefinedShape parameterDescription) {
AnnotationDescription.Loadable<Return> annotation = parameterDescription.getDeclaredAnnotations().ofType(Return.class);
if (annotation == null) {
return UNDEFINED;
} else if (readOnly && !annotation.loadSilent().readOnly()) {
throw new IllegalStateException("Cannot write return value for " + parameterDescription + " in read-only context");
} else {
return new ForReturnValue(parameterDescription.getType(), annotation.loadSilent());
}
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.ForReturnValue.Factory." + name();
}
}
}
/**
* An offset mapping for accessing a {@link Throwable} of the instrumented method.
*/
class ForThrowable implements OffsetMapping {
/**
* The type of parameter that is being accessed.
*/
private final TypeDescription.Generic target;
/**
* {@code true} if the parameter is read-only.
*/
private final boolean readOnly;
/**
* The typing to apply.
*/
private final Assigner.Typing typing;
/**
* Creates a new offset mapping for access of the exception that is thrown by the instrumented method..
*
* @param target The type of parameter that is being accessed.
* @param annotation The annotation to bind.
*/
protected ForThrowable(TypeDescription.Generic target, Thrown annotation) {
this(target, annotation.readOnly(), annotation.typing());
}
/**
* Creates a new offset mapping for access of the exception that is thrown by the instrumented method..
*
* @param target The type of parameter that is being accessed.
* @param readOnly {@code true} if the parameter is read-only.
* @param typing The typing to apply.
*/
protected ForThrowable(TypeDescription.Generic target, boolean readOnly, Assigner.Typing typing) {
this.target = target;
this.readOnly = readOnly;
this.typing = typing;
}
@Override
public Target resolve(TypeDescription instrumentedType, MethodDescription instrumentedMethod, Assigner assigner, Context context) {
int offset = instrumentedMethod.getStackSize() + context.getPadding() + instrumentedMethod.getReturnType().getStackSize().getSize();
StackManipulation readAssignment = assigner.assign(TypeDescription.THROWABLE.asGenericType(), target, typing);
if (!readAssignment.isValid()) {
throw new IllegalStateException("Cannot assign Throwable to " + target);
} else if (readOnly) {
return new Target.ForVariable.ReadOnly(TypeDescription.THROWABLE, offset, readAssignment);
} else {
StackManipulation writeAssignment = assigner.assign(target, TypeDescription.THROWABLE.asGenericType(), typing);
if (!writeAssignment.isValid()) {
throw new IllegalStateException("Cannot assign " + target + " to Throwable");
}
return new Target.ForVariable.ReadWrite(TypeDescription.THROWABLE, offset, readAssignment, writeAssignment);
}
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
ForThrowable that = (ForThrowable) object;
return readOnly == that.readOnly
&& target.equals(that.target)
&& typing == that.typing;
}
@Override
public int hashCode() {
int result = target.hashCode();
result = 31 * result + (readOnly ? 1 : 0);
result = 31 * result + typing.hashCode();
return result;
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.ForThrowable{" +
"target=" + target +
", readOnly=" + readOnly +
", typing=" + typing +
'}';
}
/**
* A factory for accessing an exception that was thrown by the instrumented method.
*/
protected static class Factory implements OffsetMapping.Factory {
/**
* {@code true} if the parameter is read-only.
*/
private final boolean readOnly;
/**
* Creates a new factory for access of the exception that is thrown by the instrumented method..
*
* @param readOnly {@code true} if the parameter is read-only.
*/
protected Factory(boolean readOnly) {
this.readOnly = readOnly;
}
/**
* Resolves an appropriate offset mapping factory for the {@link Thrown} parameter annotation.
*
* @param adviceMethod The exit advice method, annotated with {@link OnMethodExit}.
* @param readOnly {@code true} if the parameter is read-only.
* @return An appropriate offset mapping factory.
*/
@SuppressWarnings("unchecked") // In absence of @SafeVarargs for Java 6
protected static OffsetMapping.Factory of(MethodDescription.InDefinedShape adviceMethod, boolean readOnly) {
return adviceMethod.getDeclaredAnnotations()
.ofType(OnMethodExit.class)
.getValue(ON_THROWABLE)
.resolve(TypeDescription.class)
.represents(NoExceptionHandler.class) ? new OffsetMapping.Illegal(Thrown.class) : new Factory(readOnly);
}
@Override
public OffsetMapping make(ParameterDescription.InDefinedShape parameterDescription) {
AnnotationDescription.Loadable<Thrown> annotation = parameterDescription.getDeclaredAnnotations().ofType(Thrown.class);
if (annotation == null) {
return UNDEFINED;
} else if (readOnly && !annotation.loadSilent().readOnly()) {
throw new IllegalStateException("Cannot use writable " + parameterDescription + " on read-only parameter");
} else {
return new ForThrowable(parameterDescription.getType(), annotation.loadSilent());
}
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
Factory factory = (Factory) object;
return readOnly == factory.readOnly;
}
@Override
public int hashCode() {
return (readOnly ? 1 : 0);
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.ForThrowable.Factory{" +
"readOnly=" + readOnly +
'}';
}
}
}
/**
* Represents an offset mapping for a user-defined value.
*
* @param <T> The mapped annotation type.
*/
class ForUserValue<T extends Annotation> implements OffsetMapping {
/**
* The target parameter that is bound.
*/
private final ParameterDescription.InDefinedShape target;
/**
* The annotation value that triggered the binding.
*/
private final AnnotationDescription.Loadable<T> annotation;
/**
* The dynamic value that is bound.
*/
private final DynamicValue<T> dynamicValue;
/**
* Creates a new offset mapping for a user-defined value.
*
* @param target The target parameter that is bound.
* @param annotation The annotation value that triggered the binding.
* @param dynamicValue The dynamic value that is bound.
*/
protected ForUserValue(ParameterDescription.InDefinedShape target,
AnnotationDescription.Loadable<T> annotation,
DynamicValue<T> dynamicValue) {
this.target = target;
this.annotation = annotation;
this.dynamicValue = dynamicValue;
}
@Override
public Target resolve(TypeDescription instrumentedType, MethodDescription instrumentedMethod, Assigner assigner, Context context) {
return new Target.ForStackManipulation(dynamicValue.resolve(instrumentedType,
instrumentedMethod,
target,
annotation,
assigner,
context.isInitialized()));
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null || getClass() != other.getClass()) return false;
ForUserValue that = (ForUserValue) other;
return target.equals(that.target)
&& annotation.equals(that.annotation)
&& dynamicValue.equals(that.dynamicValue);
}
@Override
public int hashCode() {
int result = target.hashCode();
result = 31 * result + annotation.hashCode();
result = 31 * result + dynamicValue.hashCode();
return result;
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.ForUserValue{" +
"target=" + target +
", annotation=" + annotation +
", dynamicValue=" + dynamicValue +
'}';
}
/**
* A factory for mapping a user-defined dynamic value.
*
* @param <S> The mapped annotation type.
*/
protected static class Factory<S extends Annotation> implements OffsetMapping.Factory {
/**
* The mapped annotation type.
*/
private final Class<S> type;
/**
* The dynamic value instance used for resolving a binding.
*/
private final DynamicValue<S> dynamicValue;
/**
* Creates a new factory for a user-defined dynamic value.
*
* @param type The mapped annotation type.
* @param dynamicValue The dynamic value instance used for resolving a binding.
*/
protected Factory(Class<S> type, DynamicValue<S> dynamicValue) {
this.type = type;
this.dynamicValue = dynamicValue;
}
/**
* Creates a new factory for mapping a user value.
*
* @param type The mapped annotation type.
* @param dynamicValue The dynamic value instance used for resolving a binding.
* @return An appropriate factory for such a offset mapping.
*/
@SuppressWarnings("unchecked")
protected static OffsetMapping.Factory of(Class<? extends Annotation> type, DynamicValue<?> dynamicValue) {
return new Factory(type, dynamicValue);
}
@Override
public OffsetMapping make(ParameterDescription.InDefinedShape parameterDescription) {
AnnotationDescription.Loadable<S> annotation = parameterDescription.getDeclaredAnnotations().ofType(type);
return annotation == null
? UNDEFINED
: new ForUserValue<S>(parameterDescription, annotation, dynamicValue);
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null || getClass() != other.getClass()) return false;
Factory factory = (Factory) other;
return type.equals(factory.type) && dynamicValue.equals(factory.dynamicValue);
}
@Override
public int hashCode() {
int result = type.hashCode();
result = 31 * result + dynamicValue.hashCode();
return result;
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.ForUserValue.Factory{" +
"type=" + type +
", dynamicValue=" + dynamicValue +
'}';
}
}
}
class Illegal implements Factory {
private final List<? extends Class<? extends Annotation>> annotations;
@SuppressWarnings("unchecked") // In absence of @SafeVarargs for Java 6
protected Illegal(Class<? extends Annotation>... annotation) {
this(Arrays.asList(annotation));
}
protected Illegal(List<? extends Class<? extends Annotation>> annotations) {
this.annotations = annotations;
}
@Override
public OffsetMapping make(ParameterDescription.InDefinedShape parameterDescription) {
for (Class<? extends Annotation> annotation : annotations) {
if (parameterDescription.getDeclaredAnnotations().isAnnotationPresent(annotation)) {
throw new IllegalStateException("Illegal annotation " + annotation + " for " + parameterDescription);
}
}
return UNDEFINED;
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null || getClass() != other.getClass()) return false;
Illegal illegal = (Illegal) other;
return annotations.equals(illegal.annotations);
}
@Override
public int hashCode() {
return annotations.hashCode();
}
@Override
public String toString() {
return "Advice.Dispatcher.OffsetMapping.Illegal{" +
"annotations=" + annotations +
'}';
}
}
}
/**
* A suppression handler for optionally suppressing exceptions.
*/
interface SuppressionHandler {
/**
* Binds the suppression handler for instrumenting a specific method.
*
* @return A bound version of the suppression handler.
*/
Bound bind();
/**
* A producer for a default return value if this is applicable.
*/
interface ReturnValueProducer {
/**
* Instructs this return value producer to assure the production of a default value for the return type of the currently handled method.
*
* @param methodVisitor The method visitor to write the default value to.
*/
void onDefaultValue(MethodVisitor methodVisitor);
}
/**
* A bound version of a suppression handler that must not be reused.
*/
interface Bound {
/**
* Invoked to prepare the suppression handler, i.e. to write an exception handler entry if appropriate.
*
* @param methodVisitor The method visitor to apply the preparation to.
*/
void onPrepare(MethodVisitor methodVisitor);
/**
* Invoked at the start of a method.
*
* @param methodVisitor The method visitor of the instrumented method.
* @param methodSizeHandler A handler for computing the method size requirements.
*/
void onStart(MethodVisitor methodVisitor, MethodSizeHandler.ForAdvice methodSizeHandler);
/**
* Invoked at the end of a method.
*
* @param methodVisitor The method visitor of the instrumented method.
* @param stackMapFrameHandler A handler for translating and injecting stack map frames.
* @param returnValueProducer A producer for defining a default return value of the advised method.
*/
void onEnd(MethodVisitor methodVisitor, StackMapFrameHandler.ForAdvice stackMapFrameHandler, ReturnValueProducer returnValueProducer);
/**
* Invoked at the end of a method. Additionally indicates that the handler block should be surrounding by a skipping instruction. This method
* is always followed by a stack map frame (if it is required for the class level and class writer setting).
*
* @param methodVisitor The method visitor of the instrumented method.
* @param stackMapFrameHandler A handler for translating and injecting stack map frames.
* @param returnValueProducer A producer for defining a default return value of the advised method.
*/
void onEndSkipped(MethodVisitor methodVisitor, StackMapFrameHandler.ForAdvice stackMapFrameHandler, ReturnValueProducer returnValueProducer);
}
/**
* A non-operational suppression handler that does not suppress any method.
*/
enum NoOp implements SuppressionHandler, Bound {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public Bound bind() {
return this;
}
@Override
public void onPrepare(MethodVisitor methodVisitor) {
/* do nothing */
}
@Override
public void onStart(MethodVisitor methodVisitor, MethodSizeHandler.ForAdvice methodSizeHandler) {
/* do nothing */
}
@Override
public void onEnd(MethodVisitor methodVisitor, StackMapFrameHandler.ForAdvice stackMapFrameHandler, ReturnValueProducer returnValueProducer) {
/* do nothing */
}
@Override
public void onEndSkipped(MethodVisitor methodVisitor, StackMapFrameHandler.ForAdvice stackMapFrameHandler, ReturnValueProducer returnValueProducer) {
/* do nothing */
}
@Override
public String toString() {
return "Advice.Dispatcher.SuppressionHandler.NoOp." + name();
}
}
/**
* A suppression handler that suppresses a given throwable type.
*/
class Suppressing implements SuppressionHandler {
/**
* The suppressed throwable type.
*/
private final TypeDescription suppressedType;
/**
* Creates a new suppressing suppression handler.
*
* @param suppressedType The suppressed throwable type.
*/
protected Suppressing(TypeDescription suppressedType) {
this.suppressedType = suppressedType;
}
/**
* Resolves an appropriate suppression handler.
*
* @param suppressedType The suppressed type or {@link NoExceptionHandler} if no type should be suppressed.
* @return An appropriate suppression handler.
*/
protected static SuppressionHandler of(TypeDescription suppressedType) {
return suppressedType.represents(NoExceptionHandler.class)
? NoOp.INSTANCE
: new Suppressing(suppressedType);
}
@Override
public SuppressionHandler.Bound bind() {
return new Bound(suppressedType);
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null || getClass() != other.getClass()) return false;
Suppressing that = (Suppressing) other;
return suppressedType.equals(that.suppressedType);
}
@Override
public int hashCode() {
return suppressedType.hashCode();
}
@Override
public String toString() {
return "Advice.Dispatcher.SuppressionHandler.Suppressing{" +
"suppressedType=" + suppressedType +
'}';
}
/**
* An active, bound suppression handler.
*/
protected static class Bound implements SuppressionHandler.Bound {
/**
* The suppressed throwable type.
*/
private final TypeDescription suppressedType;
/**
* A label indicating the start of the method.
*/
private final Label startOfMethod;
/**
* A label indicating the end of the method.
*/
private final Label endOfMethod;
/**
* Creates a new active, bound suppression handler.
*
* @param suppressedType The suppressed throwable type.
*/
protected Bound(TypeDescription suppressedType) {
this.suppressedType = suppressedType;
startOfMethod = new Label();
endOfMethod = new Label();
}
@Override
public void onPrepare(MethodVisitor methodVisitor) {
methodVisitor.visitTryCatchBlock(startOfMethod, endOfMethod, endOfMethod, suppressedType.getInternalName());
}
@Override
public void onStart(MethodVisitor methodVisitor, MethodSizeHandler.ForAdvice methodSizeHandler) {
methodVisitor.visitLabel(startOfMethod);
methodSizeHandler.requireStackSize(StackSize.SINGLE.getSize());
}
@Override
public void onEnd(MethodVisitor methodVisitor, StackMapFrameHandler.ForAdvice stackMapFrameHandler, ReturnValueProducer returnValueProducer) {
methodVisitor.visitLabel(endOfMethod);
stackMapFrameHandler.injectExceptionFrame(methodVisitor);
methodVisitor.visitInsn(Opcodes.POP);
returnValueProducer.onDefaultValue(methodVisitor);
}
@Override
public void onEndSkipped(MethodVisitor methodVisitor, StackMapFrameHandler.ForAdvice stackMapFrameHandler, ReturnValueProducer returnValueProducer) {
Label endOfHandler = new Label();
methodVisitor.visitJumpInsn(Opcodes.GOTO, endOfHandler);
onEnd(methodVisitor, stackMapFrameHandler, returnValueProducer);
methodVisitor.visitLabel(endOfHandler);
}
@Override
public String toString() {
return "Advice.Dispatcher.SuppressionHandler.Suppressing.Bound{" +
"suppressedType=" + suppressedType +
", startOfMethod=" + startOfMethod +
", endOfMethod=" + endOfMethod +
'}';
}
}
}
}
/**
* Represents a resolved dispatcher.
*/
interface Resolved extends Dispatcher {
/**
* Binds this dispatcher for resolution to a specific method.
*
* @param instrumentedType The instrumented type.
* @param instrumentedMethod The instrumented method.
* @param methodVisitor The method visitor for writing the instrumented method.
* @param implementationContext The implementation context to use.
* @param assigner The assigner to use.
* @param methodSizeHandler A handler for computing the method size requirements.
* @param stackMapFrameHandler A handler for translating and injecting stack map frames.
* @return A dispatcher that is bound to the instrumented method.
*/
Bound bind(TypeDescription instrumentedType,
MethodDescription instrumentedMethod,
MethodVisitor methodVisitor,
Implementation.Context implementationContext,
Assigner assigner,
MethodSizeHandler.ForInstrumentedMethod methodSizeHandler,
StackMapFrameHandler.ForInstrumentedMethod stackMapFrameHandler);
/**
* Represents a resolved dispatcher for entering a method.
*/
interface ForMethodEnter extends Resolved {
/**
* Returns the type that this dispatcher supplies as a result of its advice or a description of {@code void} if
* no type is supplied as a result of the enter advice.
*
* @return The type that this dispatcher supplies as a result of its advice or a description of {@code void}.
*/
TypeDefinition getEnterType();
/**
* Returns {@code true} if the first discovered line number information should be prepended to the advice code.
*
* @return {@code true} if the first discovered line number information should be prepended to the advice code.
*/
boolean isPrependLineNumber();
@Override
Bound.ForMethodEnter bind(TypeDescription instrumentedType,
MethodDescription instrumentedMethod,
MethodVisitor methodVisitor,
Implementation.Context implementationContext,
Assigner assigner,
MethodSizeHandler.ForInstrumentedMethod methodSizeHandler,
StackMapFrameHandler.ForInstrumentedMethod stackMapFrameHandler);
/**
* A skip dispatcher is responsible for skipping the instrumented method depending on the
* return value of the enter advice method.
*/
interface SkipDispatcher {
/**
* Applies this skip dispatcher.
*
* @param methodVisitor The method visitor to write to.
* @param methodSizeHandler The method size handler of the advice method to use.
* @param stackMapFrameHandler The stack map frame handler of the advice method to use.
* @param instrumentedMethod The instrumented method.
* @param skipHandler The skip handler to use.
*/
void apply(MethodVisitor methodVisitor,
MethodSizeHandler.ForAdvice methodSizeHandler,
StackMapFrameHandler.ForAdvice stackMapFrameHandler,
MethodDescription instrumentedMethod,
Bound.SkipHandler skipHandler);
/**
* A disabled skip dispatcher where the instrumented method is always executed.
*/
enum Disabled implements SkipDispatcher {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public void apply(MethodVisitor methodVisitor,
MethodSizeHandler.ForAdvice methodSizeHandler,
StackMapFrameHandler.ForAdvice stackMapFrameHandler,
MethodDescription instrumentedMethod,
Bound.SkipHandler skipHandler) {
/* do nothing */
}
@Override
public String toString() {
return "Advice.Dispatcher.Resolved.ForMethodEnter.SkipDispatcher.Disabled." + name();
}
}
/**
* A skip dispatcher where the instrumented method is skipped for any default value of the advice method's return type.
* If the return type is {@code boolean}, the relationship is inversed, where the instrumented is skipped for a {@code true}
* return value.
*/
enum ForValue implements SkipDispatcher {
/**
* A skip dispatcher for a {@code boolean}, {@code byte}, {@code short}, {@code char} or {@code int} value.
*/
FOR_INTEGER(Opcodes.ILOAD, Opcodes.IFNE, Opcodes.IFEQ) {
@Override
protected void convertValue(MethodVisitor methodVisitor, MethodSizeHandler.ForAdvice methodSizeHandler) {
/* do nothing */
}
},
/**
* A skip dispatcher for a {@code long} value.
*/
FOR_LONG(Opcodes.LLOAD, Opcodes.IFNE, Opcodes.IFEQ) {
@Override
protected void convertValue(MethodVisitor methodVisitor, MethodSizeHandler.ForAdvice methodSizeHandler) {
methodVisitor.visitInsn(Opcodes.L2I);
}
},
/**
* A skip dispatcher for a {@code float} value.
*/
FOR_FLOAT(Opcodes.FLOAD, Opcodes.IFNE, Opcodes.IFEQ) {
@Override
protected void convertValue(MethodVisitor methodVisitor, MethodSizeHandler.ForAdvice methodSizeHandler) {
methodVisitor.visitInsn(Opcodes.FCONST_0);
methodVisitor.visitInsn(Opcodes.FCMPL);
methodSizeHandler.requireStackSize(2);
}
},
/**
* A skip dispatcher for a {@code double} value.
*/
FOR_DOUBLE(Opcodes.DLOAD, Opcodes.IFNE, Opcodes.IFEQ) {
@Override
protected void convertValue(MethodVisitor methodVisitor, MethodSizeHandler.ForAdvice methodSizeHandler) {
methodVisitor.visitInsn(Opcodes.DCONST_0);
methodVisitor.visitInsn(Opcodes.DCMPL);
methodSizeHandler.requireStackSize(4);
}
},
/**
* A skip dispatcher for a reference value.
*/
FOR_REFERENCE(Opcodes.ALOAD, Opcodes.IFNONNULL, Opcodes.IFNULL) {
@Override
protected void convertValue(MethodVisitor methodVisitor, MethodSizeHandler.ForAdvice methodSizeHandler) {
/* do nothing */
}
};
/**
* The load opcode for this skip dispatcher.
*/
private final int load;
/**
* The jump instruction that triggers skipping upon observing a value's default value.
*/
private final int defaultJump;
/**
* The jump instruction that triggers skipping upon observing a value's non-default value.
*/
private final int nonDefaultJump;
/**
* Creates a new skip dispatcher.
*
* @param load The load opcode for this skip dispatcher.
* @param defaultJump The jump instruction that triggers skipping upon observing a value's default value.
* @param nonDefaultJump The jump instruction that triggers skipping upon observing a value's non-default value.
*/
ForValue(int load, int defaultJump, int nonDefaultJump) {
this.load = load;
this.defaultJump = defaultJump;
this.nonDefaultJump = nonDefaultJump;
}
/**
* Creates an appropriate skip dispatcher.
*
* @param typeDefinition The type for which to skip a value.
* @param inverted {@code true} if the skip condition should be inverted to trigger upon non-default values.
* @return An appropriate skip dispatcher.
*/
protected static SkipDispatcher of(TypeDefinition typeDefinition, boolean inverted) {
ForValue skipDispatcher;
if (typeDefinition.represents(long.class)) {
skipDispatcher = FOR_LONG;
} else if (typeDefinition.represents(float.class)) {
skipDispatcher = FOR_FLOAT;
} else if (typeDefinition.represents(double.class)) {
skipDispatcher = FOR_DOUBLE;
} else if (typeDefinition.represents(void.class)) {
throw new IllegalStateException("Cannot skip on default value for void return type");
} else if (typeDefinition.isPrimitive()) { // anyOf(byte, short, char, int)
skipDispatcher = FOR_INTEGER;
} else {
skipDispatcher = FOR_REFERENCE;
}
return inverted
? skipDispatcher.inverted()
: skipDispatcher;
}
@Override
public void apply(MethodVisitor methodVisitor,
MethodSizeHandler.ForAdvice methodSizeHandler,
StackMapFrameHandler.ForAdvice stackMapFrameHandler,
MethodDescription instrumentedMethod,
Bound.SkipHandler skipHandler) {
doApply(methodVisitor, methodSizeHandler, stackMapFrameHandler, instrumentedMethod, skipHandler, false);
}
/**
* Applies this skip dispatcher.
*
* @param methodVisitor The method visitor to write to.
* @param methodSizeHandler The method size handler of the advice method to use.
* @param stackMapFrameHandler The stack map frame handler of the advice method to use.
* @param instrumentedMethod The instrumented method.
* @param skipHandler The skip handler to use.
* @param inverted {@code true} if the skip condition should be inverted.
*/
protected void doApply(MethodVisitor methodVisitor,
MethodSizeHandler.ForAdvice methodSizeHandler,
StackMapFrameHandler.ForAdvice stackMapFrameHandler,
MethodDescription instrumentedMethod,
Bound.SkipHandler skipHandler,
boolean inverted) {
methodVisitor.visitVarInsn(load, instrumentedMethod.getStackSize());
convertValue(methodVisitor, methodSizeHandler);
Label noSkip = new Label();
methodVisitor.visitJumpInsn(inverted
? nonDefaultJump
: defaultJump, noSkip);
skipHandler.apply(methodVisitor);
methodVisitor.visitLabel(noSkip);
stackMapFrameHandler.injectCompletionFrame(methodVisitor, true);
}
/**
* Converts the return value to an {@code int} value.
*
* @param methodVisitor The method visitor to use.
* @param methodSizeHandler The method size handler of the advice method to use.
*/
protected abstract void convertValue(MethodVisitor methodVisitor, MethodSizeHandler.ForAdvice methodSizeHandler);
/**
* Returns an inverted version of this skip dispatcher.
*
* @return An inverted version of this skip dispatcher.
*/
private SkipDispatcher inverted() {
return new Inverted();
}
@Override
public String toString() {
return "Advice.Dispatcher.Resolved.ForMethodEnter.SkipDispatcher.ForValue." + name();
}
/**
* An inverted version of a value-based skipped dispatcher that triggers upon observing a non-default value.
*/
protected class Inverted implements SkipDispatcher {
@Override
public void apply(MethodVisitor methodVisitor,
MethodSizeHandler.ForAdvice methodSizeHandler,
StackMapFrameHandler.ForAdvice stackMapFrameHandler,
MethodDescription instrumentedMethod,
Bound.SkipHandler skipHandler) {
doApply(methodVisitor, methodSizeHandler, stackMapFrameHandler, instrumentedMethod, skipHandler, true);
}
/**
* Returns the outer instance.
*
* @return The outer instance.
*/
private SkipDispatcher getOuter() {
return ForValue.this;
}
@Override
public int hashCode() {
return ForValue.this.hashCode();
}
@Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if (!(other instanceof Inverted)) {
return false;
}
Inverted inverted = (Inverted) other;
return inverted.getOuter().equals(ForValue.this);
}
@Override
public String toString() {
return "Advice.Dispatcher.Resolved.ForMethodEnter.SkipDispatcher.ForValue.Inverted{" +
"outer=" + ForValue.this +
"}";
}
}
}
/**
* A skip dispatcher that skips a value if it is of a given instance.
*/
class ForType implements SkipDispatcher {
/**
* The type for which to skip instances.
*/
private final TypeDescription typeDescription;
/**
* Creates a new skip dispatcher for a given type.
*
* @param typeDescription The type for which to skip instances.
*/
protected ForType(TypeDescription typeDescription) {
this.typeDescription = typeDescription;
}
/**
* Creates a skip dispatcher for an advice method.
*
* @param adviceMethod The advice method for which to resolve a skip dispatcher.
* @return An appropriate skip dispatcher.
*/
public static SkipDispatcher of(MethodDescription adviceMethod) {
return of(adviceMethod.getDeclaredAnnotations()
.ofType(OnMethodEnter.class)
.getValue(SKIP_ON)
.resolve(TypeDescription.class), adviceMethod);
}
/**
* Creates a skip dispatcher for a given annotation type and advice method.
*
* @param typeDescription The type that was specified as an annotation value.
* @param adviceMethod The advice method.
* @return An appropriate skip dispatcher.
*/
protected static SkipDispatcher of(TypeDescription typeDescription, MethodDescription adviceMethod) {
if (typeDescription.represents(void.class)) {
return Disabled.INSTANCE;
} else if (typeDescription.represents(OnDefaultValue.class)) {
return ForValue.of(adviceMethod.getReturnType(), false);
} else if (typeDescription.represents(OnNonDefaultValue.class)) {
return ForValue.of(adviceMethod.getReturnType(), true);
} else if (typeDescription.isPrimitive() || adviceMethod.getReturnType().isPrimitive()) {
throw new IllegalStateException("Cannot skip method by instance type for primitive return value on " + adviceMethod);
} else {
return new ForType(typeDescription);
}
}
@Override
public void apply(MethodVisitor methodVisitor,
MethodSizeHandler.ForAdvice methodSizeHandler,
StackMapFrameHandler.ForAdvice stackMapFrameHandler,
MethodDescription instrumentedMethod,
Bound.SkipHandler skipHandler) {
methodVisitor.visitVarInsn(Opcodes.ALOAD, instrumentedMethod.getStackSize());
methodVisitor.visitTypeInsn(Opcodes.INSTANCEOF, typeDescription.getInternalName());
Label noSkip = new Label();
methodVisitor.visitJumpInsn(Opcodes.IFEQ, noSkip);
skipHandler.apply(methodVisitor);
methodVisitor.visitLabel(noSkip);
stackMapFrameHandler.injectCompletionFrame(methodVisitor, true);
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null || getClass() != other.getClass()) return false;
ForType forType = (ForType) other;
return typeDescription.equals(forType.typeDescription);
}
@Override
public int hashCode() {
return typeDescription.hashCode();
}
@Override
public String toString() {
return "Advice.Dispatcher.Resolved.ForMethodEnter.SkipDispatcher.ForType{" +
"typeDescription=" + typeDescription +
'}';
}
}
}
}
/**
* Represents a resolved dispatcher for exiting a method.
*/
interface ForMethodExit extends Resolved {
/**
* Returns the type of throwable for which this exit advice is supposed to be invoked.
*
* @return The {@link Throwable} type for which to invoke this exit advice or a description of {@link NoExceptionHandler}
* if this exit advice does not expect to be invoked upon any throwable.
*/
TypeDescription getThrowable();
@Override
Bound.ForMethodExit bind(TypeDescription instrumentedType,
MethodDescription instrumentedMethod,
MethodVisitor methodVisitor,
Implementation.Context implementationContext,
Assigner assigner,
MethodSizeHandler.ForInstrumentedMethod methodSizeHandler,
StackMapFrameHandler.ForInstrumentedMethod stackMapFrameHandler);
}
}
/**
* A bound resolution of an advice method.
*/
interface Bound {
/**
* Prepares the advice method's exception handlers.
*/
void prepare();
/**
* A skip handler is responsible for writing code that skips the invocation of the original code
* within the instrumented method.
*/
interface SkipHandler {
/**
* Applies this skip handler.
*
* @param methodVisitor The method visitor to write the code to.
*/
void apply(MethodVisitor methodVisitor);
}
/**
* A bound dispatcher for a method enter.
*/
interface ForMethodEnter extends Bound {
/**
* Applies this dispatcher.
*
* @param skipHandler The skip handler to use.
*/
void apply(SkipHandler skipHandler);
}
/**
* A bound dispatcher for a method exit.
*/
interface ForMethodExit extends Bound {
/**
* Applies this dispatcher.
*/
void apply();
}
}
/**
* An implementation for inactive devise that does not write any byte code.
*/
enum Inactive implements Dispatcher.Unresolved, Resolved.ForMethodEnter, Resolved.ForMethodExit, Bound.ForMethodEnter, Bound.ForMethodExit {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public boolean isAlive() {
return false;
}
@Override
public boolean isBinary() {
return false;
}
@Override
public TypeDescription getThrowable() {
return NoExceptionHandler.DESCRIPTION;
}
@Override
public TypeDefinition getEnterType() {
return TypeDescription.VOID;
}
@Override
public boolean isPrependLineNumber() {
return false;
}
@Override
public Resolved.ForMethodEnter asMethodEnter(List<? extends OffsetMapping.Factory> userFactories,
ClassReader classReader) {
return this;
}
@Override
public Resolved.ForMethodExit asMethodExitTo(List<? extends OffsetMapping.Factory> userFactories,
ClassReader classReader,
Resolved.ForMethodEnter dispatcher) {
return this;
}
@Override
public void prepare() {
/* do nothing */
}
@Override
public void apply() {
/* do nothing */
}
@Override
public void apply(SkipHandler skipHandler) {
/* do nothing */
}
@Override
public Inactive bind(TypeDescription instrumentedType,
MethodDescription instrumentedMethod,
MethodVisitor methodVisitor,
Implementation.Context implementationContext,
Assigner assigner,
MethodSizeHandler.ForInstrumentedMethod methodSizeHandler,
StackMapFrameHandler.ForInstrumentedMethod stackMapFrameHandler) {
return this;
}
@Override
public String toString() {
return "Advice.Dispatcher.Inactive." + name();
}
}
/**
* A dispatcher for an advice method that is being inlined into the instrumented method.
*/
class Inlining implements Unresolved {
/**
* The advice method.
*/
protected final MethodDescription.InDefinedShape adviceMethod;
/**
* Creates a dispatcher for inlined advice method.
*
* @param adviceMethod The advice method.
*/
protected Inlining(MethodDescription.InDefinedShape adviceMethod) {
this.adviceMethod = adviceMethod;
}
@Override
public boolean isAlive() {
return true;
}
@Override
public boolean isBinary() {
return true;
}
@Override
public Dispatcher.Resolved.ForMethodEnter asMethodEnter(List<? extends OffsetMapping.Factory> userFactories,
ClassReader classReader) {
return new Resolved.ForMethodEnter(adviceMethod, userFactories, classReader);
}
@Override
public Dispatcher.Resolved.ForMethodExit asMethodExitTo(List<? extends OffsetMapping.Factory> userFactories,
ClassReader classReader,
Dispatcher.Resolved.ForMethodEnter dispatcher) {
return Resolved.ForMethodExit.of(adviceMethod, userFactories, classReader, dispatcher.getEnterType());
}
@Override
public boolean equals(Object other) {
return this == other || !(other == null || getClass() != other.getClass()) && adviceMethod.equals(((Inlining) other).adviceMethod);
}
@Override
public int hashCode() {
return adviceMethod.hashCode();
}
@Override
public String toString() {
return "Advice.Dispatcher.Inlining{" +
"adviceMethod=" + adviceMethod +
'}';
}
/**
* A resolved version of a dispatcher.
*/
protected abstract static class Resolved implements Dispatcher.Resolved {
/**
* Indicates a read-only mapping for an offset.
*/
private static final boolean READ_ONLY = true;
/**
* The represented advice method.
*/
protected final MethodDescription.InDefinedShape adviceMethod;
/**
* A class reader to query for the class file of the advice method.
*/
protected final ClassReader classReader;
/**
* An unresolved mapping of offsets of the advice method based on the annotations discovered on each method parameter.
*/
protected final Map<Integer, OffsetMapping> offsetMappings;
/**
* The suppression handler to use.
*/
protected final SuppressionHandler suppressionHandler;
/**
* Creates a new resolved version of a dispatcher.
*
* @param adviceMethod The represented advice method.
* @param factories A list of factories to resolve for the parameters of the advice method.
* @param classReader A class reader to query for the class file of the advice method.
* @param throwableType The type to handle by a suppression handler or {@link NoExceptionHandler} to not handle any exceptions.
*/
protected Resolved(MethodDescription.InDefinedShape adviceMethod,
List<OffsetMapping.Factory> factories,
ClassReader classReader,
TypeDescription throwableType) {
this.adviceMethod = adviceMethod;
offsetMappings = new HashMap<Integer, OffsetMapping>();
for (ParameterDescription.InDefinedShape parameterDescription : adviceMethod.getParameters()) {
OffsetMapping offsetMapping = OffsetMapping.Factory.UNDEFINED;
for (OffsetMapping.Factory factory : factories) {
OffsetMapping possible = factory.make(parameterDescription);
if (possible != null) {
if (offsetMapping == null) {
offsetMapping = possible;
} else {
throw new IllegalStateException(parameterDescription + " is bound to both " + possible + " and " + offsetMapping);
}
}
}
offsetMappings.put(parameterDescription.getOffset(), offsetMapping == null
? new OffsetMapping.ForArgument(parameterDescription, READ_ONLY, Assigner.Typing.STATIC)
: offsetMapping);
}
this.classReader = classReader;
suppressionHandler = SuppressionHandler.Suppressing.of(throwableType);
}
@Override
public boolean isAlive() {
return true;
}
/**
* Applies a resolution for a given instrumented method.
*
* @param methodVisitor A method visitor for writing byte code to the instrumented method.
* @param implementationContext The implementation context to use.
* @param assigner The assigner to use.
* @param methodSizeHandler A handler for computing the method size requirements.
* @param stackMapFrameHandler A handler for translating and injecting stack map frames.
* @param instrumentedType A description of the instrumented type.
* @param instrumentedMethod A description of the instrumented method.
* @param suppressionHandler The bound suppression handler that is used for suppressing exceptions of this advice method.
* @return A method visitor for visiting the advice method's byte code.
*/
protected abstract MethodVisitor apply(MethodVisitor methodVisitor,
Implementation.Context implementationContext,
Assigner assigner,
MethodSizeHandler.ForInstrumentedMethod methodSizeHandler,
StackMapFrameHandler.ForInstrumentedMethod stackMapFrameHandler,
TypeDescription instrumentedType,
MethodDescription instrumentedMethod,
SuppressionHandler.Bound suppressionHandler);
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null || getClass() != other.getClass()) return false;
Inlining.Resolved resolved = (Inlining.Resolved) other;
return adviceMethod.equals(resolved.adviceMethod) && offsetMappings.equals(resolved.offsetMappings);
}
@Override
public int hashCode() {
int result = adviceMethod.hashCode();
result = 31 * result + offsetMappings.hashCode();
return result;
}
/**
* A bound advice method that copies the code by first extracting the exception table and later appending the
* code of the method without copying any meta data.
*/
protected abstract class AdviceMethodInliner extends ClassVisitor implements Bound {
/**
* A description of the instrumented type.
*/
protected final TypeDescription instrumentedType;
/**
* The instrumented method.
*/
protected final MethodDescription instrumentedMethod;
/**
* The method visitor for writing the instrumented method.
*/
protected final MethodVisitor methodVisitor;
/**
* The implementation context to use.
*/
protected final Implementation.Context implementationContext;
/**
* The assigner to use.
*/
protected final Assigner assigner;
/**
* A handler for computing the method size requirements.
*/
protected final MethodSizeHandler.ForInstrumentedMethod methodSizeHandler;
/**
* A handler for translating and injecting stack map frames.
*/
protected final StackMapFrameHandler.ForInstrumentedMethod stackMapFrameHandler;
/**
* A bound suppression handler that is used for suppressing exceptions of this advice method.
*/
protected final SuppressionHandler.Bound suppressionHandler;
/**
* A class reader for parsing the class file containing the represented advice method.
*/
protected final ClassReader classReader;
/**
* The labels that were found during parsing the method's exception handler in the order of their discovery.
*/
protected List<Label> labels;
/**
* Creates a new advice method inliner.
*
* @param instrumentedType A description of the instrumented type.
* @param instrumentedMethod The instrumented method.
* @param methodVisitor The method visitor for writing the instrumented method.
* @param implementationContext The implementation context to use.
* @param assigner The assigner to use.
* @param methodSizeHandler A handler for computing the method size requirements.
* @param stackMapFrameHandler A handler for translating and injecting stack map frames.
* @param suppressionHandler A bound suppression handler that is used for suppressing exceptions of this advice method.
* @param classReader A class reader for parsing the class file containing the represented advice method.
*/
protected AdviceMethodInliner(TypeDescription instrumentedType,
MethodDescription instrumentedMethod,
MethodVisitor methodVisitor,
Implementation.Context implementationContext,
Assigner assigner,
MethodSizeHandler.ForInstrumentedMethod methodSizeHandler,
StackMapFrameHandler.ForInstrumentedMethod stackMapFrameHandler,
SuppressionHandler.Bound suppressionHandler,
ClassReader classReader) {
super(Opcodes.ASM5);
this.instrumentedType = instrumentedType;
this.instrumentedMethod = instrumentedMethod;
this.methodVisitor = methodVisitor;
this.implementationContext = implementationContext;
this.assigner = assigner;
this.methodSizeHandler = methodSizeHandler;
this.stackMapFrameHandler = stackMapFrameHandler;
this.suppressionHandler = suppressionHandler;
this.classReader = classReader;
labels = new ArrayList<Label>();
}
@Override
public void prepare() {
classReader.accept(new ExceptionTableExtractor(), ClassReader.SKIP_FRAMES | ClassReader.SKIP_DEBUG);
suppressionHandler.onPrepare(methodVisitor);
}
/**
* Inlines the advice method.
*/
protected void doApply() {
classReader.accept(this, ClassReader.SKIP_DEBUG | stackMapFrameHandler.getReaderHint());
}
@Override
public MethodVisitor visitMethod(int modifiers, String internalName, String descriptor, String signature, String[] exception) {
return adviceMethod.getInternalName().equals(internalName) && adviceMethod.getDescriptor().equals(descriptor)
? new ExceptionTableSubstitutor(Inlining.Resolved.this.apply(methodVisitor,
implementationContext,
assigner,
methodSizeHandler,
stackMapFrameHandler,
instrumentedType,
instrumentedMethod,
suppressionHandler)) : IGNORE_METHOD;
}
/**
* A class visitor that extracts the exception tables of the advice method.
*/
protected class ExceptionTableExtractor extends ClassVisitor {
/**
* Creates a new exception table extractor.
*/
protected ExceptionTableExtractor() {
super(Opcodes.ASM5);
}
@Override
public MethodVisitor visitMethod(int modifiers, String internalName, String descriptor, String signature, String[] exception) {
return adviceMethod.getInternalName().equals(internalName) && adviceMethod.getDescriptor().equals(descriptor)
? new ExceptionTableCollector(methodVisitor)
: IGNORE_METHOD;
}
@Override
public String toString() {
return "Advice.Dispatcher.Inlining.Resolved.AdviceMethodInliner.ExceptionTableExtractor{" +
"methodVisitor=" + methodVisitor +
'}';
}
}
/**
* A visitor that only writes try-catch-finally blocks to the supplied method visitor. All labels of these tables are collected
* for substitution when revisiting the reminder of the method.
*/
protected class ExceptionTableCollector extends MethodVisitor {
/**
* The method visitor for which the try-catch-finally blocks should be written.
*/
private final MethodVisitor methodVisitor;
/**
* Creates a new exception table collector.
*
* @param methodVisitor The method visitor for which the try-catch-finally blocks should be written.
*/
protected ExceptionTableCollector(MethodVisitor methodVisitor) {
super(Opcodes.ASM5);
this.methodVisitor = methodVisitor;
}
@Override
public void visitTryCatchBlock(Label start, Label end, Label handler, String type) {
methodVisitor.visitTryCatchBlock(start, end, handler, type);
labels.addAll(Arrays.asList(start, end, handler));
}
@Override
public AnnotationVisitor visitTryCatchAnnotation(int typeReference, TypePath typePath, String descriptor, boolean visible) {
return methodVisitor.visitTryCatchAnnotation(typeReference, typePath, descriptor, visible);
}
@Override
public String toString() {
return "Advice.Dispatcher.Inlining.Resolved.AdviceMethodInliner.ExceptionTableCollector{" +
"methodVisitor=" + methodVisitor +
'}';
}
}
/**
* A label substitutor allows to visit an advice method a second time after the exception handlers were already written.
* Doing so, this visitor substitutes all labels that were already created during the first visit to keep the mapping
* consistent. It is not required to resolve labels for non-code instructions as meta information is not propagated to
* the target method visitor for advice code.
*/
protected class ExceptionTableSubstitutor extends MethodVisitor {
/**
* A map containing resolved substitutions.
*/
private final Map<Label, Label> substitutions;
/**
* The current index of the visited labels that are used for try-catch-finally blocks.
*/
private int index;
/**
* Creates a label substitor.
*
* @param methodVisitor The method visitor for which to substitute labels.
*/
protected ExceptionTableSubstitutor(MethodVisitor methodVisitor) {
super(Opcodes.ASM5, methodVisitor);
substitutions = new IdentityHashMap<Label, Label>();
}
@Override
public void visitTryCatchBlock(Label start, Label end, Label handler, String type) {
substitutions.put(start, labels.get(index++));
substitutions.put(end, labels.get(index++));
Label actualHandler = labels.get(index++);
substitutions.put(handler, actualHandler);
((CodeTranslationVisitor) mv).propagateHandler(actualHandler);
}
@Override
public AnnotationVisitor visitTryCatchAnnotation(int typeReference, TypePath typePath, String descriptor, boolean visible) {
return IGNORE_ANNOTATION;
}
@Override
public void visitLabel(Label label) {
super.visitLabel(resolve(label));
}
@Override
public void visitJumpInsn(int opcode, Label label) {
super.visitJumpInsn(opcode, resolve(label));
}
@Override
public void visitTableSwitchInsn(int minimum, int maximum, Label defaultOption, Label... label) {
super.visitTableSwitchInsn(minimum, maximum, defaultOption, resolve(label));
}
@Override
public void visitLookupSwitchInsn(Label defaultOption, int[] keys, Label[] label) {
super.visitLookupSwitchInsn(resolve(defaultOption), keys, resolve(label));
}
/**
* Resolves an array of labels.
*
* @param label The labels to resolved.
* @return An array containing the resolved arrays.
*/
private Label[] resolve(Label[] label) {
Label[] resolved = new Label[label.length];
int index = 0;
for (Label aLabel : label) {
resolved[index++] = resolve(aLabel);
}
return resolved;
}
/**
* Resolves a single label if mapped or returns the original label.
*
* @param label The label to resolve.
* @return The resolved label.
*/
private Label resolve(Label label) {
Label substitution = substitutions.get(label);
return substitution == null
? label
: substitution;
}
@Override
public String toString() {
return "Advice.Dispatcher.Inlining.Resolved.AdviceMethodInliner.ExceptionTableSubstitutor{" +
"methodVisitor=" + methodVisitor +
", substitutions=" + substitutions +
", index=" + index +
'}';
}
}
}
/**
* A resolved dispatcher for implementing method enter advice.
*/
protected static class ForMethodEnter extends Inlining.Resolved implements Dispatcher.Resolved.ForMethodEnter {
/**
* The skip dispatcher to use.
*/
private final SkipDispatcher skipDispatcher;
/**
* {@code true} if the first discovered line number information should be prepended to the advice code.
*/
private final boolean prependLineNumber;
/**
* Creates a new resolved dispatcher for implementing method enter advice.
*
* @param adviceMethod The represented advice method.
* @param userFactories A list of user-defined factories for offset mappings.
* @param classReader A class reader to query for the class file of the advice method.
*/
@SuppressWarnings("unchecked") // In absence of @SafeVarargs for Java 6
protected ForMethodEnter(MethodDescription.InDefinedShape adviceMethod,
List<? extends OffsetMapping.Factory> userFactories,
ClassReader classReader) {
super(adviceMethod,
CompoundList.of(Arrays.asList(OffsetMapping.ForArgument.Factory.READ_WRITE,
OffsetMapping.ForAllArguments.Factory.READ_WRITE,
OffsetMapping.ForThisReference.Factory.READ_WRITE,
OffsetMapping.ForField.Factory.READ_WRITE,
OffsetMapping.ForOrigin.Factory.INSTANCE,
OffsetMapping.ForUnusedValue.Factory.INSTANCE,
OffsetMapping.ForStubValue.INSTANCE,
new OffsetMapping.Illegal(Thrown.class, Enter.class, Return.class)), userFactories),
classReader,
adviceMethod.getDeclaredAnnotations().ofType(OnMethodEnter.class).getValue(SUPPRESS_ENTER).resolve(TypeDescription.class));
skipDispatcher = SkipDispatcher.ForType.of(adviceMethod);
prependLineNumber = adviceMethod.getDeclaredAnnotations().ofType(OnMethodEnter.class).getValue(PREPEND_LINE_NUMBER).resolve(Boolean.class);
}
@Override
public Bound.ForMethodEnter bind(TypeDescription instrumentedType,
MethodDescription instrumentedMethod,
MethodVisitor methodVisitor,
Implementation.Context implementationContext,
Assigner assigner,
MethodSizeHandler.ForInstrumentedMethod methodSizeHandler,
StackMapFrameHandler.ForInstrumentedMethod stackMapFrameHandler) {
return new AdviceMethodInliner(instrumentedType,
instrumentedMethod,
methodVisitor,
implementationContext,
assigner,
methodSizeHandler,
stackMapFrameHandler,
suppressionHandler.bind(),
classReader,
skipDispatcher);
}
@Override
public TypeDefinition getEnterType() {
return adviceMethod.getReturnType();
}
@Override
public boolean isPrependLineNumber() {
return prependLineNumber;
}
@Override
protected MethodVisitor apply(MethodVisitor methodVisitor,
Implementation.Context implementationContext,
Assigner assigner,
MethodSizeHandler.ForInstrumentedMethod methodSizeHandler,
StackMapFrameHandler.ForInstrumentedMethod stackMapFrameHandler,
TypeDescription instrumentedType,
MethodDescription instrumentedMethod,
SuppressionHandler.Bound suppressionHandler) {
Map<Integer, OffsetMapping.Target> offsetMappings = new HashMap<Integer, OffsetMapping.Target>();
for (Map.Entry<Integer, OffsetMapping> entry : this.offsetMappings.entrySet()) {
offsetMappings.put(entry.getKey(), entry.getValue().resolve(instrumentedType,
instrumentedMethod,
assigner,
OffsetMapping.Context.ForMethodEntry.of(instrumentedMethod)));
}
return new CodeTranslationVisitor.ForMethodEnter(methodVisitor,
implementationContext,
methodSizeHandler.bindEntry(adviceMethod),
stackMapFrameHandler.bindEntry(adviceMethod),
instrumentedMethod,
adviceMethod,
offsetMappings,
suppressionHandler);
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null || getClass() != other.getClass()) return false;
if (!super.equals(other)) return false;
Inlining.Resolved.ForMethodEnter that = (Inlining.Resolved.ForMethodEnter) other;
return skipDispatcher == that.skipDispatcher && prependLineNumber == that.prependLineNumber;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + skipDispatcher.hashCode();
result = 31 * result + (prependLineNumber ? 1 : 0);
return result;
}
@Override
public String toString() {
return "Advice.Dispatcher.Inlining.Resolved.ForMethodEnter{" +
"adviceMethod=" + adviceMethod +
", offsetMappings=" + offsetMappings +
", skipDispatcher=" + skipDispatcher +
", prependLineNumber=" + prependLineNumber +
'}';
}
/**
* An advice method inliner for a method enter.
*/
protected class AdviceMethodInliner extends Inlining.Resolved.AdviceMethodInliner implements Bound.ForMethodEnter {
/**
* The skip dispatcher to use.
*/
private final SkipDispatcher skipDispatcher;
/**
* Creates a new advice method inliner for a method enter.
*
* @param instrumentedType A description of the instrumented type.
* @param instrumentedMethod A description of the instrumented method.
* @param methodVisitor The method visitor for writing the instrumented method.
* @param implementationContext The implementation context to use.
* @param assigner The assigner to use.
* @param methodSizeHandler A handler for computing the method size requirements.
* @param stackMapFrameHandler A handler for translating and injecting stack map frames.
* @param suppressionHandler A bound suppression handler that is used for suppressing exceptions of this advice method.
* @param classReader A class reader for parsing the class file containing the represented advice method.
* @param skipDispatcher The skip dispatcher to use.
*/
protected AdviceMethodInliner(TypeDescription instrumentedType,
MethodDescription instrumentedMethod,
MethodVisitor methodVisitor,
Implementation.Context implementationContext,
Assigner assigner,
MethodSizeHandler.ForInstrumentedMethod methodSizeHandler,
StackMapFrameHandler.ForInstrumentedMethod stackMapFrameHandler,
SuppressionHandler.Bound suppressionHandler,
ClassReader classReader,
SkipDispatcher skipDispatcher) {
super(instrumentedType,
instrumentedMethod,
methodVisitor,
implementationContext,
assigner,
methodSizeHandler,
stackMapFrameHandler,
suppressionHandler,
classReader);
this.skipDispatcher = skipDispatcher;
}
@Override
public void apply(SkipHandler skipHandler) {
doApply();
skipDispatcher.apply(methodVisitor,
methodSizeHandler.bindEntry(adviceMethod),
stackMapFrameHandler.bindEntry(adviceMethod),
instrumentedMethod, skipHandler);
}
@Override
public String toString() {
return "Advice.Dispatcher.Inlining.Resolved.ForMethodEnter.AdviceMethodInliner{" +
"instrumentedType=" + instrumentedType +
", instrumentedMethod=" + instrumentedMethod +
", methodVisitor=" + methodVisitor +
", methodSizeHandler=" + methodSizeHandler +
", stackMapFrameHandler=" + stackMapFrameHandler +
", suppressionHandler=" + suppressionHandler +
", classReader=" + classReader +
", labels=" + labels +
", skipDispatcher=" + skipDispatcher +
'}';
}
}
}
/**
* A resolved dispatcher for implementing method exit advice.
*/
protected abstract static class ForMethodExit extends Inlining.Resolved implements Dispatcher.Resolved.ForMethodExit {
/**
* The additional stack size to consider when accessing the local variable array.
*/
private final TypeDefinition enterType;
/**
* Creates a new resolved dispatcher for implementing method exit advice.
*
* @param adviceMethod The represented advice method.
* @param userFactories A list of user-defined factories for offset mappings.
* @param classReader The class reader for parsing the advice method's class file.
* @param enterType The type of the value supplied by the enter advice method or
* a description of {@code void} if no such value exists.
*/
protected ForMethodExit(MethodDescription.InDefinedShape adviceMethod,
List<? extends OffsetMapping.Factory> userFactories,
ClassReader classReader,
TypeDefinition enterType) {
super(adviceMethod,
CompoundList.of(Arrays.asList(OffsetMapping.ForArgument.Factory.READ_WRITE,
OffsetMapping.ForAllArguments.Factory.READ_WRITE,
OffsetMapping.ForThisReference.Factory.READ_WRITE,
OffsetMapping.ForField.Factory.READ_WRITE,
OffsetMapping.ForOrigin.Factory.INSTANCE,
OffsetMapping.ForUnusedValue.Factory.INSTANCE,
OffsetMapping.ForStubValue.INSTANCE,
new OffsetMapping.ForEnterValue.Factory(enterType, false),
OffsetMapping.ForReturnValue.Factory.READ_WRITE,
OffsetMapping.ForThrowable.Factory.of(adviceMethod, false)
), userFactories),
classReader,
adviceMethod.getDeclaredAnnotations().ofType(OnMethodExit.class).getValue(SUPPRESS_EXIT).resolve(TypeDescription.class));
this.enterType = enterType;
}
/**
* Resolves exit advice that handles exceptions depending on the specification of the exit advice.
*
* @param adviceMethod The advice method.
* @param userFactories A list of user-defined factories for offset mappings.
* @param classReader The class reader for parsing the advice method's class file.
* @param enterType The type of the value supplied by the enter advice method or
* a description of {@code void} if no such value exists.
* @return An appropriate exit handler.
*/
protected static Resolved.ForMethodExit of(MethodDescription.InDefinedShape adviceMethod,
List<? extends OffsetMapping.Factory> userFactories,
ClassReader classReader,
TypeDefinition enterType) {
TypeDescription throwable = adviceMethod.getDeclaredAnnotations()
.ofType(OnMethodExit.class)
.getValue(ON_THROWABLE).resolve(TypeDescription.class);
return throwable.represents(NoExceptionHandler.class)
? new WithoutExceptionHandler(adviceMethod, userFactories, classReader, enterType)
: new WithExceptionHandler(adviceMethod, userFactories, classReader, enterType, throwable);
}
@Override
protected MethodVisitor apply(MethodVisitor methodVisitor,
Implementation.Context implementationContext,
Assigner assigner,
MethodSizeHandler.ForInstrumentedMethod methodSizeHandler,
StackMapFrameHandler.ForInstrumentedMethod stackMapFrameHandler,
TypeDescription instrumentedType,
MethodDescription instrumentedMethod,
SuppressionHandler.Bound suppressionHandler) {
Map<Integer, OffsetMapping.Target> offsetMappings = new HashMap<Integer, OffsetMapping.Target>();
for (Map.Entry<Integer, OffsetMapping> entry : this.offsetMappings.entrySet()) {
offsetMappings.put(entry.getKey(), entry.getValue().resolve(instrumentedType,
instrumentedMethod,
assigner,
OffsetMapping.Context.ForMethodExit.of(enterType)));
}
return new CodeTranslationVisitor.ForMethodExit(methodVisitor,
implementationContext,
methodSizeHandler.bindExit(adviceMethod, getThrowable().represents(NoExceptionHandler.class)),
stackMapFrameHandler.bindExit(adviceMethod),
instrumentedMethod,
adviceMethod,
offsetMappings,
suppressionHandler,
enterType.getStackSize().getSize() + getPadding().getSize());
}
@Override
public Bound.ForMethodExit bind(TypeDescription instrumentedType,
MethodDescription instrumentedMethod,
MethodVisitor methodVisitor,
Implementation.Context implementationContext,
Assigner assigner,
MethodSizeHandler.ForInstrumentedMethod methodSizeHandler,
StackMapFrameHandler.ForInstrumentedMethod stackMapFrameHandler) {
return new AdviceMethodInliner(instrumentedType,
instrumentedMethod,
methodVisitor,
implementationContext,
assigner,
methodSizeHandler,
stackMapFrameHandler,
suppressionHandler.bind(),
classReader);
}
/**
* Returns the additional padding this exit advice implies.
*
* @return The additional padding this exit advice implies.
*/
protected abstract StackSize getPadding();
@Override
public boolean equals(Object other) {
return this == other || !(other == null || getClass() != other.getClass())
&& super.equals(other)
&& enterType == ((Inlining.Resolved.ForMethodExit) other).enterType;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + enterType.hashCode();
return result;
}
/**
* An advice method inliner for a method exit.
*/
protected class AdviceMethodInliner extends Inlining.Resolved.AdviceMethodInliner implements Bound.ForMethodExit {
/**
* Creates a new advice method inliner for a method exit.
*
* @param instrumentedType A description of the instrumented type.
* @param instrumentedMethod A description of the instrumented method.
* @param methodVisitor The method visitor for writing the instrumented method.
* @param implementationContext The implementation context to use.
* @param assigner The assigner to use.
* @param methodSizeHandler A handler for computing the method size requirements.
* @param stackMapFrameHandler A handler for translating and injecting stack map frames.
* @param suppressionHandler A bound suppression handler that is used for suppressing exceptions of this advice method.
* @param classReader A class reader for parsing the class file containing the represented advice method.
*/
public AdviceMethodInliner(TypeDescription instrumentedType,
MethodDescription instrumentedMethod,
MethodVisitor methodVisitor,
Implementation.Context implementationContext,
Assigner assigner,
MethodSizeHandler.ForInstrumentedMethod methodSizeHandler,
StackMapFrameHandler.ForInstrumentedMethod stackMapFrameHandler,
SuppressionHandler.Bound suppressionHandler,
ClassReader classReader) {
super(instrumentedType,
instrumentedMethod,
methodVisitor,
implementationContext,
assigner,
methodSizeHandler,
stackMapFrameHandler,
suppressionHandler,
classReader);
}
@Override
public void apply() {
doApply();
}
@Override
public String toString() {
return "Advice.Dispatcher.Inlining.Resolved.ForMethodExit.AdviceMethodInliner{" +
"instrumentedType=" + instrumentedType +
", instrumentedMethod=" + instrumentedMethod +
", methodVisitor=" + methodVisitor +
", methodSizeHandler=" + methodSizeHandler +
", stackMapFrameHandler=" + stackMapFrameHandler +
", suppressionHandler=" + suppressionHandler +
", classReader=" + classReader +
", labels=" + labels +
'}';
}
}
/**
* Implementation of exit advice that handles exceptions.
*/
protected static class WithExceptionHandler extends Inlining.Resolved.ForMethodExit {
/**
* The type of the handled throwable type for which this advice is invoked.
*/
private final TypeDescription throwable;
/**
* Creates a new resolved dispatcher for implementing method exit advice that handles exceptions.
*
* @param adviceMethod The represented advice method.
* @param userFactories A list of user-defined factories for offset mappings.
* @param classReader The class reader for parsing the advice method's class file.
* @param enterType The type of the value supplied by the enter advice method or
* a description of {@code void} if no such value exists.
* @param throwable The type of the handled throwable type for which this advice is invoked.
*/
protected WithExceptionHandler(MethodDescription.InDefinedShape adviceMethod,
List<? extends OffsetMapping.Factory> userFactories,
ClassReader classReader,
TypeDefinition enterType,
TypeDescription throwable) {
super(adviceMethod, userFactories, classReader, enterType);
this.throwable = throwable;
}
@Override
protected StackSize getPadding() {
return throwable.getStackSize();
}
@Override
public TypeDescription getThrowable() {
return throwable;
}
@Override
public String toString() {
return "Advice.Dispatcher.Inlining.Resolved.ForMethodExit.WithExceptionHandler{" +
"adviceMethod=" + adviceMethod +
", offsetMappings=" + offsetMappings +
", throwable=" + throwable +
'}';
}
}
/**
* Implementation of exit advice that ignores exceptions.
*/
protected static class WithoutExceptionHandler extends Inlining.Resolved.ForMethodExit {
/**
* Creates a new resolved dispatcher for implementing method exit advice that does not handle exceptions.
*
* @param adviceMethod The represented advice method.
* @param userFactories A list of user-defined factories for offset mappings.
* @param classReader A class reader to query for the class file of the advice method.
* @param enterType The type of the value supplied by the enter advice method or
* a description of {@code void} if no such value exists.
*/
protected WithoutExceptionHandler(MethodDescription.InDefinedShape adviceMethod,
List<? extends OffsetMapping.Factory> userFactories,
ClassReader classReader,
TypeDefinition enterType) {
super(adviceMethod, userFactories, classReader, enterType);
}
@Override
protected StackSize getPadding() {
return StackSize.ZERO;
}
@Override
public TypeDescription getThrowable() {
return NoExceptionHandler.DESCRIPTION;
}
@Override
public String toString() {
return "Advice.Dispatcher.Inlining.Resolved.ForMethodExit.WithoutExceptionHandler{" +
"adviceMethod=" + adviceMethod +
", offsetMappings=" + offsetMappings +
'}';
}
}
}
}
/**
* A visitor for translating an advice method's byte code for inlining into the instrumented method.
*/
protected abstract static class CodeTranslationVisitor extends MethodVisitor implements SuppressionHandler.ReturnValueProducer {
/**
* The original method visitor to which all instructions are eventually written to.
*/
protected final MethodVisitor methodVisitor;
/**
* The implementation context to use.
*/
protected final Context implementationContext;
/**
* A handler for computing the method size requirements.
*/
protected final MethodSizeHandler.ForAdvice methodSizeHandler;
/**
* A handler for translating and injecting stack map frames.
*/
protected final StackMapFrameHandler.ForAdvice stackMapFrameHandler;
/**
* The instrumented method.
*/
protected final MethodDescription instrumentedMethod;
/**
* The advice method.
*/
protected final MethodDescription.InDefinedShape adviceMethod;
/**
* A mapping of offsets to resolved target offsets in the instrumented method.
*/
private final Map<Integer, Resolved.OffsetMapping.Target> offsetMappings;
/**
* A handler for optionally suppressing exceptions.
*/
private final SuppressionHandler.Bound suppressionHandler;
/**
* A label indicating the end of the advice byte code.
*/
protected final Label endOfMethod;
/**
* Creates a new code translation visitor.
*
* @param methodVisitor A method visitor for writing the instrumented method's byte code.
* @param implementationContext The implementation context to use.
* @param methodSizeHandler A handler for computing the method size requirements.
* @param stackMapFrameHandler A handler for translating and injecting stack map frames.
* @param instrumentedMethod The instrumented method.
* @param adviceMethod The advice method.
* @param offsetMappings A mapping of offsets to resolved target offsets in the instrumented method.
* @param suppressionHandler The suppression handler to use.
*/
protected CodeTranslationVisitor(MethodVisitor methodVisitor,
Context implementationContext,
MethodSizeHandler.ForAdvice methodSizeHandler,
StackMapFrameHandler.ForAdvice stackMapFrameHandler,
MethodDescription instrumentedMethod,
MethodDescription.InDefinedShape adviceMethod,
Map<Integer, OffsetMapping.Target> offsetMappings,
SuppressionHandler.Bound suppressionHandler) {
super(Opcodes.ASM5, new StackAwareMethodVisitor(methodVisitor, instrumentedMethod));
this.methodVisitor = methodVisitor;
this.implementationContext = implementationContext;
this.methodSizeHandler = methodSizeHandler;
this.stackMapFrameHandler = stackMapFrameHandler;
this.instrumentedMethod = instrumentedMethod;
this.adviceMethod = adviceMethod;
this.offsetMappings = offsetMappings;
this.suppressionHandler = suppressionHandler;
endOfMethod = new Label();
}
/**
* Propagates a label for an exception handler that is typically suppressed by the overlaying
* {@link Resolved.AdviceMethodInliner.ExceptionTableSubstitutor}.
*
* @param label The label to register as a target for an exception handler.
*/
protected void propagateHandler(Label label) {
((StackAwareMethodVisitor) mv).register(label, Collections.singletonList(StackSize.SINGLE));
}
@Override
public void visitParameter(String name, int modifiers) {
/* do nothing */
}
@Override
public AnnotationVisitor visitAnnotationDefault() {
return IGNORE_ANNOTATION;
}
@Override
public AnnotationVisitor visitAnnotation(String descriptor, boolean visible) {
return IGNORE_ANNOTATION;
}
@Override
public AnnotationVisitor visitTypeAnnotation(int typeReference, TypePath typePath, String descriptor, boolean visible) {
return IGNORE_ANNOTATION;
}
@Override
public AnnotationVisitor visitParameterAnnotation(int index, String descriptor, boolean visible) {
return IGNORE_ANNOTATION;
}
@Override
public void visitAttribute(Attribute attribute) {
/* do nothing */
}
@Override
public void visitCode() {
suppressionHandler.onStart(methodVisitor, methodSizeHandler);
}
@Override
public void visitFrame(int frameType, int localVariableLength, Object[] localVariable, int stackSize, Object[] stack) {
stackMapFrameHandler.translateFrame(methodVisitor, frameType, localVariableLength, localVariable, stackSize, stack);
}
@Override
public void visitEnd() {
suppressionHandler.onEnd(methodVisitor, stackMapFrameHandler, this);
methodVisitor.visitLabel(endOfMethod);
onMethodReturn();
stackMapFrameHandler.injectCompletionFrame(methodVisitor, false);
}
@Override
public void visitMaxs(int stackSize, int localVariableLength) {
methodSizeHandler.recordMaxima(stackSize, localVariableLength);
}
@Override
public void visitVarInsn(int opcode, int offset) {
Resolved.OffsetMapping.Target target = offsetMappings.get(offset);
if (target != null) {
StackManipulation stackManipulation;
StackSize expectedGrowth;
switch (opcode) {
case Opcodes.ILOAD:
case Opcodes.FLOAD:
case Opcodes.ALOAD:
stackManipulation = target.resolveRead();
expectedGrowth = StackSize.SINGLE;
break;
case Opcodes.DLOAD:
case Opcodes.LLOAD:
stackManipulation = target.resolveRead();
expectedGrowth = StackSize.DOUBLE;
break;
case Opcodes.ISTORE:
case Opcodes.FSTORE:
case Opcodes.ASTORE:
case Opcodes.LSTORE:
case Opcodes.DSTORE:
stackManipulation = target.resolveWrite();
expectedGrowth = StackSize.ZERO;
break;
default:
throw new IllegalStateException("Unexpected opcode: " + opcode);
}
methodSizeHandler.recordPadding(stackManipulation.apply(mv, implementationContext).getMaximalSize() - expectedGrowth.getSize());
} else {
mv.visitVarInsn(opcode, adjust(offset + instrumentedMethod.getStackSize() - adviceMethod.getStackSize()));
}
}
@Override
public void visitIincInsn(int offset, int value) {
Resolved.OffsetMapping.Target target = offsetMappings.get(offset);
if (target != null) {
methodSizeHandler.recordPadding(target.resolveIncrement(value).apply(mv, implementationContext).getMaximalSize());
} else {
mv.visitIincInsn(adjust(offset + instrumentedMethod.getStackSize() - adviceMethod.getStackSize()), value);
}
}
/**
* Adjusts the offset of a variable instruction within the advice method such that no arguments to
* the instrumented method are overridden.
*
* @param offset The original offset.
* @return The adjusted offset.
*/
protected abstract int adjust(int offset);
@Override
public abstract void visitInsn(int opcode);
/**
* Invoked after returning from the advice method.
*/
protected abstract void onMethodReturn();
/**
* A code translation visitor that retains the return value of the represented advice method.
*/
protected static class ForMethodEnter extends CodeTranslationVisitor {
/**
* {@code true} if the method can return non-exceptionally.
*/
private boolean doesReturn;
/**
* Creates a code translation visitor for translating exit advice.
*
* @param methodVisitor A method visitor for writing the instrumented method's byte code.
* @param implementationContext The implementation context to use.
* @param methodSizeHandler A handler for computing the method size requirements.
* @param stackMapFrameHandler A handler for translating and injecting stack map frames.
* @param instrumentedMethod The instrumented method.
* @param adviceMethod The advice method.
* @param offsetMappings A mapping of offsets to resolved target offsets in the instrumented method.
* @param suppressionHandler The suppression handler to use.
*/
protected ForMethodEnter(MethodVisitor methodVisitor,
Context implementationContext,
MethodSizeHandler.ForAdvice methodSizeHandler,
StackMapFrameHandler.ForAdvice stackMapFrameHandler,
MethodDescription instrumentedMethod,
MethodDescription.InDefinedShape adviceMethod,
Map<Integer, Resolved.OffsetMapping.Target> offsetMappings,
SuppressionHandler.Bound suppressionHandler) {
super(methodVisitor,
implementationContext,
methodSizeHandler,
stackMapFrameHandler,
instrumentedMethod,
adviceMethod,
offsetMappings,
suppressionHandler);
doesReturn = false;
}
@Override
public void visitInsn(int opcode) {
switch (opcode) {
case Opcodes.RETURN:
((StackAwareMethodVisitor) mv).drainStack();
break;
case Opcodes.IRETURN:
methodSizeHandler.requireLocalVariableLength(((StackAwareMethodVisitor) mv).drainStack(Opcodes.ISTORE, Opcodes.ILOAD, StackSize.SINGLE));
break;
case Opcodes.ARETURN:
methodSizeHandler.requireLocalVariableLength(((StackAwareMethodVisitor) mv).drainStack(Opcodes.ASTORE, Opcodes.ALOAD, StackSize.SINGLE));
break;
case Opcodes.FRETURN:
methodSizeHandler.requireLocalVariableLength(((StackAwareMethodVisitor) mv).drainStack(Opcodes.FSTORE, Opcodes.FLOAD, StackSize.SINGLE));
break;
case Opcodes.LRETURN:
methodSizeHandler.requireLocalVariableLength(((StackAwareMethodVisitor) mv).drainStack(Opcodes.LSTORE, Opcodes.LLOAD, StackSize.DOUBLE));
break;
case Opcodes.DRETURN:
methodSizeHandler.requireLocalVariableLength(((StackAwareMethodVisitor) mv).drainStack(Opcodes.DSTORE, Opcodes.DLOAD, StackSize.DOUBLE));
break;
default:
mv.visitInsn(opcode);
return;
}
mv.visitJumpInsn(Opcodes.GOTO, endOfMethod);
doesReturn = true;
}
@Override
protected int adjust(int offset) {
return offset;
}
@Override
public void onDefaultValue(MethodVisitor methodVisitor) {
if (adviceMethod.getReturnType().represents(boolean.class)
|| adviceMethod.getReturnType().represents(byte.class)
|| adviceMethod.getReturnType().represents(short.class)
|| adviceMethod.getReturnType().represents(char.class)
|| adviceMethod.getReturnType().represents(int.class)) {
methodVisitor.visitInsn(Opcodes.ICONST_0);
} else if (adviceMethod.getReturnType().represents(long.class)) {
methodVisitor.visitInsn(Opcodes.LCONST_0);
} else if (adviceMethod.getReturnType().represents(float.class)) {
methodVisitor.visitInsn(Opcodes.FCONST_0);
} else if (adviceMethod.getReturnType().represents(double.class)) {
methodVisitor.visitInsn(Opcodes.DCONST_0);
} else if (!adviceMethod.getReturnType().represents(void.class)) {
methodVisitor.visitInsn(Opcodes.ACONST_NULL);
}
doesReturn = true;
}
@Override
protected void onMethodReturn() {
Type returnType = Type.getType(adviceMethod.getReturnType().asErasure().getDescriptor());
if (doesReturn && !returnType.equals(Type.VOID_TYPE)) {
stackMapFrameHandler.injectReturnFrame(methodVisitor);
methodVisitor.visitVarInsn(returnType.getOpcode(Opcodes.ISTORE), instrumentedMethod.getStackSize());
}
}
@Override
public String toString() {
return "Advice.Dispatcher.Inlining.CodeTranslationVisitor.ForMethodEnter{" +
"instrumentedMethod=" + instrumentedMethod +
", adviceMethod=" + adviceMethod +
", doesReturn=" + doesReturn +
'}';
}
}
/**
* A code translation visitor that discards the return value of the represented advice method.
*/
protected static class ForMethodExit extends CodeTranslationVisitor {
/**
* The padding after the instrumented method's arguments in the local variable array.
*/
private final int padding;
/**
* Creates a code translation visitor for translating exit advice.
*
* @param methodVisitor A method visitor for writing the instrumented method's byte code.
* @param implementationContext The implementation context to use.
* @param methodSizeHandler A handler for computing the method size requirements.
* @param stackMapFrameHandler A handler for translating and injecting stack map frames.
* @param instrumentedMethod The instrumented method.
* @param adviceMethod The advice method.
* @param offsetMappings A mapping of offsets to resolved target offsets in the instrumented method.
* @param suppressionHandler The suppression handler to use.
* @param padding The padding after the instrumented method's arguments in the local variable array.
*/
protected ForMethodExit(MethodVisitor methodVisitor,
Implementation.Context implementationContext,
MethodSizeHandler.ForAdvice methodSizeHandler,
StackMapFrameHandler.ForAdvice stackMapFrameHandler,
MethodDescription instrumentedMethod,
MethodDescription.InDefinedShape adviceMethod,
Map<Integer, Resolved.OffsetMapping.Target> offsetMappings,
SuppressionHandler.Bound suppressionHandler,
int padding) {
super(methodVisitor,
implementationContext,
methodSizeHandler,
stackMapFrameHandler,
instrumentedMethod,
adviceMethod,
offsetMappings,
suppressionHandler);
this.padding = padding;
}
@Override
public void visitInsn(int opcode) {
switch (opcode) {
case Opcodes.RETURN:
break;
case Opcodes.IRETURN:
case Opcodes.ARETURN:
case Opcodes.FRETURN:
mv.visitInsn(Opcodes.POP);
break;
case Opcodes.LRETURN:
case Opcodes.DRETURN:
mv.visitInsn(Opcodes.POP2);
break;
default:
mv.visitInsn(opcode);
return;
}
((StackAwareMethodVisitor) mv).drainStack();
mv.visitJumpInsn(Opcodes.GOTO, endOfMethod);
}
@Override
protected int adjust(int offset) {
return instrumentedMethod.getReturnType().getStackSize().getSize() + padding + offset;
}
@Override
public void onDefaultValue(MethodVisitor methodVisitor) {
/* do nothing */
}
@Override
protected void onMethodReturn() {
/* do nothing */
}
@Override
public String toString() {
return "Advice.Dispatcher.Inlining.CodeTranslationVisitor.ForMethodExit{" +
"instrumentedMethod=" + instrumentedMethod +
", adviceMethod=" + adviceMethod +
", padding=" + padding +
'}';
}
}
}
}
/**
* A dispatcher for an advice method that is being invoked from the instrumented method.
*/
class Delegating implements Unresolved {
/**
* The advice method.
*/
protected final MethodDescription.InDefinedShape adviceMethod;
/**
* Creates a new delegating advice dispatcher.
*
* @param adviceMethod The advice method.
*/
protected Delegating(MethodDescription.InDefinedShape adviceMethod) {
this.adviceMethod = adviceMethod;
}
@Override
public boolean isAlive() {
return true;
}
@Override
public boolean isBinary() {
return false;
}
@Override
public Dispatcher.Resolved.ForMethodEnter asMethodEnter(List<? extends OffsetMapping.Factory> userFactories,
ClassReader classReader) {
return new Resolved.ForMethodEnter(adviceMethod, userFactories);
}
@Override
public Dispatcher.Resolved.ForMethodExit asMethodExitTo(List<? extends OffsetMapping.Factory> userFactories,
ClassReader classReader,
Dispatcher.Resolved.ForMethodEnter dispatcher) {
return Resolved.ForMethodExit.of(adviceMethod, userFactories, dispatcher.getEnterType());
}
@Override
public boolean equals(Object other) {
return this == other || !(other == null || getClass() != other.getClass()) && adviceMethod.equals(((Delegating) other).adviceMethod);
}
@Override
public int hashCode() {
return adviceMethod.hashCode();
}
@Override
public String toString() {
return "Advice.Dispatcher.Delegating{" +
"adviceMethod=" + adviceMethod +
'}';
}
/**
* A resolved version of a dispatcher.
*
* @param <T> The type of advice dispatcher that is bound.
*/
protected abstract static class Resolved<T extends Bound> implements Dispatcher.Resolved {
/**
* Indicates a read-only mapping for an offset.
*/
private static final boolean READ_ONLY = true;
/**
* The represented advice method.
*/
protected final MethodDescription.InDefinedShape adviceMethod;
/**
* An unresolved mapping of offsets of the advice method based on the annotations discovered on each method parameter.
*/
protected final List<OffsetMapping> offsetMappings;
/**
* The suppression handler to use.
*/
protected final SuppressionHandler suppressionHandler;
/**
* Creates a new resolved version of a dispatcher.
*
* @param adviceMethod The represented advice method.
* @param factories A list of factories to resolve for the parameters of the advice method.
* @param throwableType The type to handle by a suppression handler or {@link NoExceptionHandler} to not handle any exceptions.
*/
protected Resolved(MethodDescription.InDefinedShape adviceMethod, List<OffsetMapping.Factory> factories, TypeDescription throwableType) {
this.adviceMethod = adviceMethod;
offsetMappings = new ArrayList<OffsetMapping>(adviceMethod.getParameters().size());
for (ParameterDescription.InDefinedShape parameterDescription : adviceMethod.getParameters()) {
OffsetMapping offsetMapping = OffsetMapping.Factory.UNDEFINED;
for (OffsetMapping.Factory factory : factories) {
OffsetMapping possible = factory.make(parameterDescription);
if (possible != null) {
if (offsetMapping == null) {
offsetMapping = possible;
} else {
throw new IllegalStateException(parameterDescription + " is bound to both " + possible + " and " + offsetMapping);
}
}
}
offsetMappings.add(offsetMapping == null
? new OffsetMapping.ForArgument(parameterDescription, READ_ONLY, Assigner.Typing.STATIC)
: offsetMapping);
}
suppressionHandler = SuppressionHandler.Suppressing.of(throwableType);
}
@Override
public boolean isAlive() {
return true;
}
@Override
public T bind(TypeDescription instrumentedType,
MethodDescription instrumentedMethod,
MethodVisitor methodVisitor,
Implementation.Context implementationContext,
Assigner assigner,
MethodSizeHandler.ForInstrumentedMethod methodSizeHandler,
StackMapFrameHandler.ForInstrumentedMethod stackMapFrameHandler) {
if (!adviceMethod.isVisibleTo(instrumentedType)) {
throw new IllegalStateException(adviceMethod + " is not visible to " + instrumentedMethod.getDeclaringType());
}
return resolve(instrumentedType, instrumentedMethod, methodVisitor, implementationContext, assigner, methodSizeHandler, stackMapFrameHandler);
}
/**
* Binds this dispatcher for resolution to a specific method.
*
* @param instrumentedType A description of the instrumented type.
* @param instrumentedMethod The instrumented method that is being bound.
* @param methodVisitor The method visitor for writing to the instrumented method.
* @param implementationContext The implementation context to use.
* @param assigner The assigner to use.
* @param methodSizeHandler A handler for computing the method size requirements.
* @param stackMapFrameHandler A handler for translating and injecting stack map frames.
* @return An appropriate bound advice dispatcher.
*/
protected abstract T resolve(TypeDescription instrumentedType,
MethodDescription instrumentedMethod,
MethodVisitor methodVisitor,
Implementation.Context implementationContext,
Assigner assigner,
MethodSizeHandler.ForInstrumentedMethod methodSizeHandler,
StackMapFrameHandler.ForInstrumentedMethod stackMapFrameHandler);
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null || getClass() != other.getClass()) return false;
Delegating.Resolved resolved = (Delegating.Resolved) other;
return adviceMethod.equals(resolved.adviceMethod) && offsetMappings.equals(resolved.offsetMappings);
}
@Override
public int hashCode() {
int result = adviceMethod.hashCode();
result = 31 * result + offsetMappings.hashCode();
return result;
}
/**
* A bound advice method that copies the code by first extracting the exception table and later appending the
* code of the method without copying any meta data.
*/
protected abstract static class AdviceMethodWriter implements Bound, SuppressionHandler.ReturnValueProducer {
/**
* Indicates an empty local variable array which is not required for calling a method.
*/
private static final int EMPTY = 0;
/**
* The advice method.
*/
protected final MethodDescription.InDefinedShape adviceMethod;
/**
* The instrumented method.
*/
protected final MethodDescription instrumentedMethod;
/**
* The offset mappings available to this advice.
*/
private final List<OffsetMapping.Target> offsetMappings;
/**
* The method visitor for writing the instrumented method.
*/
protected final MethodVisitor methodVisitor;
/**
* The implementation context to use.
*/
protected final Implementation.Context implementationContext;
/**
* A handler for computing the method size requirements.
*/
protected final MethodSizeHandler.ForAdvice methodSizeHandler;
/**
* A handler for translating and injecting stack map frmes.
*/
protected final StackMapFrameHandler.ForAdvice stackMapFrameHandler;
/**
* A bound suppression handler that is used for suppressing exceptions of this advice method.
*/
private final SuppressionHandler.Bound suppressionHandler;
/**
* Creates a new advice method writer.
*
* @param adviceMethod The advice method.
* @param instrumentedMethod The instrumented method.
* @param offsetMappings The offset mappings available to this advice.
* @param methodVisitor The method visitor for writing the instrumented method.
* @param implementationContext The implementation context to use.
* @param methodSizeHandler A handler for computing the method size requirements.
* @param stackMapFrameHandler A handler for translating and injecting stack map frames.
* @param suppressionHandler A bound suppression handler that is used for suppressing exceptions of this advice method.
*/
protected AdviceMethodWriter(MethodDescription.InDefinedShape adviceMethod,
MethodDescription instrumentedMethod,
List<OffsetMapping.Target> offsetMappings,
MethodVisitor methodVisitor,
Context implementationContext,
MethodSizeHandler.ForAdvice methodSizeHandler,
StackMapFrameHandler.ForAdvice stackMapFrameHandler,
SuppressionHandler.Bound suppressionHandler) {
this.adviceMethod = adviceMethod;
this.instrumentedMethod = instrumentedMethod;
this.offsetMappings = offsetMappings;
this.methodVisitor = methodVisitor;
this.implementationContext = implementationContext;
this.methodSizeHandler = methodSizeHandler;
this.stackMapFrameHandler = stackMapFrameHandler;
this.suppressionHandler = suppressionHandler;
}
@Override
public void prepare() {
suppressionHandler.onPrepare(methodVisitor);
}
/**
* Writes the advice method invocation.
*/
protected void doApply() {
suppressionHandler.onStart(methodVisitor, methodSizeHandler);
int index = 0, currentStackSize = 0, maximumStackSize = 0;
for (OffsetMapping.Target offsetMapping : offsetMappings) {
Type type = Type.getType(adviceMethod.getParameters().get(index++).getType().asErasure().getDescriptor());
currentStackSize += type.getSize();
maximumStackSize = Math.max(maximumStackSize, currentStackSize + offsetMapping.resolveRead()
.apply(methodVisitor, implementationContext)
.getMaximalSize());
}
methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC,
adviceMethod.getDeclaringType().getInternalName(),
adviceMethod.getInternalName(),
adviceMethod.getDescriptor(),
false);
onMethodReturn();
suppressionHandler.onEndSkipped(methodVisitor, stackMapFrameHandler, this);
stackMapFrameHandler.injectCompletionFrame(methodVisitor, false);
methodSizeHandler.recordMaxima(Math.max(maximumStackSize, adviceMethod.getReturnType().getStackSize().getSize()), EMPTY);
}
/**
* Invoked directly after the advice method was called.
*/
protected abstract void onMethodReturn();
@Override
public String toString() {
return "Advice.Dispatcher.Delegating.Resolved.AdviceMethodWriter{" +
"instrumentedMethod=" + instrumentedMethod +
", methodVisitor=" + methodVisitor +
", methodSizeHandler=" + methodSizeHandler +
", stackMapFrameHandler=" + stackMapFrameHandler +
", suppressionHandler=" + suppressionHandler +
'}';
}
/**
* An advice method writer for a method entry.
*/
protected static class ForMethodEnter extends AdviceMethodWriter implements Bound.ForMethodEnter {
/**
* The skip dispatcher to use.
*/
private final Resolved.ForMethodEnter.SkipDispatcher skipDispatcher;
/**
* Creates a new advice method writer.
*
* @param adviceMethod The advice method.
* @param instrumentedMethod The instrumented method.
* @param offsetMappings The offset mappings available to this advice.
* @param methodVisitor The method visitor for writing the instrumented method.
* @param implementationContext The implementation context to use.
* @param methodSizeHandler A handler for computing the method size requirements.
* @param stackMapFrameHandler A handler for translating and injecting stack map frames.
* @param suppressionHandler A bound suppression handler that is used for suppressing exceptions of this advice method.
* @param skipDispatcher The skip dispatcher to use.
*/
protected ForMethodEnter(MethodDescription.InDefinedShape adviceMethod,
MethodDescription instrumentedMethod,
List<OffsetMapping.Target> offsetMappings,
MethodVisitor methodVisitor,
Implementation.Context implementationContext,
MethodSizeHandler.ForAdvice methodSizeHandler,
StackMapFrameHandler.ForAdvice stackMapFrameHandler,
SuppressionHandler.Bound suppressionHandler,
Resolved.ForMethodEnter.SkipDispatcher skipDispatcher) {
super(adviceMethod,
instrumentedMethod,
offsetMappings,
methodVisitor,
implementationContext,
methodSizeHandler,
stackMapFrameHandler,
suppressionHandler);
this.skipDispatcher = skipDispatcher;
}
@Override
protected void onMethodReturn() {
if (adviceMethod.getReturnType().represents(boolean.class)
|| adviceMethod.getReturnType().represents(byte.class)
|| adviceMethod.getReturnType().represents(short.class)
|| adviceMethod.getReturnType().represents(char.class)
|| adviceMethod.getReturnType().represents(int.class)) {
methodVisitor.visitVarInsn(Opcodes.ISTORE, instrumentedMethod.getStackSize());
} else if (adviceMethod.getReturnType().represents(long.class)) {
methodVisitor.visitVarInsn(Opcodes.LSTORE, instrumentedMethod.getStackSize());
} else if (adviceMethod.getReturnType().represents(float.class)) {
methodVisitor.visitVarInsn(Opcodes.FSTORE, instrumentedMethod.getStackSize());
} else if (adviceMethod.getReturnType().represents(double.class)) {
methodVisitor.visitVarInsn(Opcodes.DSTORE, instrumentedMethod.getStackSize());
} else if (!adviceMethod.getReturnType().represents(void.class)) {
methodVisitor.visitVarInsn(Opcodes.ASTORE, instrumentedMethod.getStackSize());
}
}
@Override
public void apply(SkipHandler skipHandler) {
doApply();
skipDispatcher.apply(methodVisitor, methodSizeHandler, stackMapFrameHandler, instrumentedMethod, skipHandler);
}
@Override
public void onDefaultValue(MethodVisitor methodVisitor) {
if (adviceMethod.getReturnType().represents(boolean.class)
|| adviceMethod.getReturnType().represents(byte.class)
|| adviceMethod.getReturnType().represents(short.class)
|| adviceMethod.getReturnType().represents(char.class)
|| adviceMethod.getReturnType().represents(int.class)) {
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitVarInsn(Opcodes.ISTORE, instrumentedMethod.getStackSize());
} else if (adviceMethod.getReturnType().represents(long.class)) {
methodVisitor.visitInsn(Opcodes.LCONST_0);
methodVisitor.visitVarInsn(Opcodes.LSTORE, instrumentedMethod.getStackSize());
} else if (adviceMethod.getReturnType().represents(float.class)) {
methodVisitor.visitInsn(Opcodes.FCONST_0);
methodVisitor.visitVarInsn(Opcodes.FSTORE, instrumentedMethod.getStackSize());
} else if (adviceMethod.getReturnType().represents(double.class)) {
methodVisitor.visitInsn(Opcodes.DCONST_0);
methodVisitor.visitVarInsn(Opcodes.DSTORE, instrumentedMethod.getStackSize());
} else if (!adviceMethod.getReturnType().represents(void.class)) {
methodVisitor.visitInsn(Opcodes.ACONST_NULL);
methodVisitor.visitVarInsn(Opcodes.ASTORE, instrumentedMethod.getStackSize());
}
}
@Override
public String toString() {
return "Advice.Dispatcher.Delegating.Resolved.AdviceMethodWriter.ForMethodEnter{" +
"instrumentedMethod=" + instrumentedMethod +
", adviceMethod=" + adviceMethod +
"}";
}
}
/**
* An advice method writer for a method exit.
*/
protected static class ForMethodExit extends AdviceMethodWriter implements Bound.ForMethodExit {
/**
* Creates a new advice method writer.
*
* @param adviceMethod The advice method.
* @param instrumentedMethod The instrumented method.
* @param offsetMappings The offset mappings available to this advice.
* @param methodVisitor The method visitor for writing the instrumented method.
* @param implementationContext The implementation context to use.
* @param methodSizeHandler A handler for computing the method size requirements.
* @param stackMapFrameHandler A handler for translating and injecting stack map frames.
* @param suppressionHandler A bound suppression handler that is used for suppressing exceptions of this advice method.
*/
protected ForMethodExit(MethodDescription.InDefinedShape adviceMethod,
MethodDescription instrumentedMethod,
List<OffsetMapping.Target> offsetMappings,
MethodVisitor methodVisitor,
Implementation.Context implementationContext,
MethodSizeHandler.ForAdvice methodSizeHandler,
StackMapFrameHandler.ForAdvice stackMapFrameHandler,
SuppressionHandler.Bound suppressionHandler) {
super(adviceMethod,
instrumentedMethod,
offsetMappings,
methodVisitor,
implementationContext,
methodSizeHandler,
stackMapFrameHandler,
suppressionHandler);
}
@Override
public void apply() {
doApply();
}
@Override
protected void onMethodReturn() {
switch (adviceMethod.getReturnType().getStackSize()) {
case ZERO:
return;
case SINGLE:
methodVisitor.visitInsn(Opcodes.POP);
return;
case DOUBLE:
methodVisitor.visitInsn(Opcodes.POP2);
return;
default:
throw new IllegalStateException("Unexpected size: " + adviceMethod.getReturnType().getStackSize());
}
}
@Override
public void onDefaultValue(MethodVisitor methodVisitor) {
/* do nothing */
}
@Override
public String toString() {
return "Advice.Dispatcher.Delegating.Resolved.AdviceMethodWriter.ForMethodExit{" +
"instrumentedMethod=" + instrumentedMethod +
", adviceMethod=" + adviceMethod +
"}";
}
}
}
/**
* A resolved dispatcher for implementing method enter advice.
*/
protected static class ForMethodEnter extends Delegating.Resolved<Bound.ForMethodEnter> implements Dispatcher.Resolved.ForMethodEnter {
/**
* The skip dispatcher to use.
*/
private final SkipDispatcher skipDispatcher;
/**
* {@code true} if the first discovered line number information should be prepended to the advice code.
*/
private final boolean prependLineNumber;
/**
* Creates a new resolved dispatcher for implementing method enter advice.
*
* @param adviceMethod The represented advice method.
* @param userFactories A list of user-defined factories for offset mappings.
*/
@SuppressWarnings("unchecked") // In absence of @SafeVarargs for Java 6
protected ForMethodEnter(MethodDescription.InDefinedShape adviceMethod, List<? extends OffsetMapping.Factory> userFactories) {
super(adviceMethod,
CompoundList.of(Arrays.asList(OffsetMapping.ForArgument.Factory.READ_ONLY,
OffsetMapping.ForAllArguments.Factory.READ_ONLY,
OffsetMapping.ForThisReference.Factory.READ_ONLY,
OffsetMapping.ForField.Factory.READ_ONLY,
OffsetMapping.ForOrigin.Factory.INSTANCE,
OffsetMapping.ForUnusedValue.Factory.INSTANCE,
OffsetMapping.ForStubValue.INSTANCE,
new OffsetMapping.Illegal(Thrown.class, Enter.class, Return.class)), userFactories),
adviceMethod.getDeclaredAnnotations().ofType(OnMethodEnter.class).getValue(SUPPRESS_ENTER).resolve(TypeDescription.class));
skipDispatcher = SkipDispatcher.ForType.of(adviceMethod);
prependLineNumber = adviceMethod.getDeclaredAnnotations().ofType(OnMethodEnter.class).getValue(PREPEND_LINE_NUMBER).resolve(Boolean.class);
}
@Override
public TypeDefinition getEnterType() {
return adviceMethod.getReturnType();
}
@Override
public boolean isPrependLineNumber() {
return prependLineNumber;
}
@Override
protected Bound.ForMethodEnter resolve(TypeDescription instrumentedType,
MethodDescription instrumentedMethod,
MethodVisitor methodVisitor,
Implementation.Context implementationContext,
Assigner assigner,
MethodSizeHandler.ForInstrumentedMethod methodSizeHandler,
StackMapFrameHandler.ForInstrumentedMethod stackMapFrameHandler) {
List<OffsetMapping.Target> offsetMappings = new ArrayList<OffsetMapping.Target>(this.offsetMappings.size());
for (OffsetMapping offsetMapping : this.offsetMappings) {
offsetMappings.add(offsetMapping.resolve(instrumentedType,
instrumentedMethod,
assigner,
OffsetMapping.Context.ForMethodEntry.of(instrumentedMethod)));
}
return new AdviceMethodWriter.ForMethodEnter(adviceMethod,
instrumentedMethod,
offsetMappings,
methodVisitor,
implementationContext,
methodSizeHandler.bindEntry(adviceMethod),
stackMapFrameHandler.bindEntry(adviceMethod),
suppressionHandler.bind(),
skipDispatcher);
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null || getClass() != other.getClass()) return false;
if (!super.equals(other)) return false;
Delegating.Resolved.ForMethodEnter that = (Delegating.Resolved.ForMethodEnter) other;
return skipDispatcher == that.skipDispatcher && prependLineNumber == that.prependLineNumber;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + skipDispatcher.hashCode();
result = 31 * result + (prependLineNumber ? 1 : 0);
return result;
}
@Override
public String toString() {
return "Advice.Dispatcher.Delegating.Resolved.ForMethodEnter{" +
"adviceMethod=" + adviceMethod +
", offsetMappings=" + offsetMappings +
", skipDispatcher=" + skipDispatcher +
", prependLineNumber=" + prependLineNumber +
'}';
}
}
/**
* A resolved dispatcher for implementing method exit advice.
*/
protected abstract static class ForMethodExit extends Delegating.Resolved<Bound.ForMethodExit> implements Dispatcher.Resolved.ForMethodExit {
/**
* The additional stack size to consider when accessing the local variable array.
*/
private final TypeDefinition enterType;
/**
* Creates a new resolved dispatcher for implementing method exit advice.
*
* @param adviceMethod The represented advice method.
* @param userFactories A list of user-defined factories for offset mappings.
* @param enterType The type of the value supplied by the enter advice method or
* a description of {@code void} if no such value exists.
*/
protected ForMethodExit(MethodDescription.InDefinedShape adviceMethod,
List<? extends OffsetMapping.Factory> userFactories,
TypeDefinition enterType) {
super(adviceMethod,
CompoundList.of(Arrays.asList(OffsetMapping.ForArgument.Factory.READ_ONLY,
OffsetMapping.ForAllArguments.Factory.READ_ONLY,
OffsetMapping.ForThisReference.Factory.READ_ONLY,
OffsetMapping.ForField.Factory.READ_ONLY,
OffsetMapping.ForOrigin.Factory.INSTANCE,
OffsetMapping.ForUnusedValue.Factory.INSTANCE,
OffsetMapping.ForStubValue.INSTANCE,
new OffsetMapping.ForEnterValue.Factory(enterType, true),
OffsetMapping.ForReturnValue.Factory.READ_ONLY,
OffsetMapping.ForThrowable.Factory.of(adviceMethod, true)
), userFactories),
adviceMethod.getDeclaredAnnotations().ofType(OnMethodExit.class).getValue(SUPPRESS_EXIT).resolve(TypeDescription.class));
this.enterType = enterType;
}
/**
* Resolves exit advice that handles exceptions depending on the specification of the exit advice.
*
* @param adviceMethod The advice method.
* @param userFactories A list of user-defined factories for offset mappings.
* @param enterType The type of the value supplied by the enter advice method or
* a description of {@code void} if no such value exists.
* @return An appropriate exit handler.
*/
protected static Resolved.ForMethodExit of(MethodDescription.InDefinedShape adviceMethod,
List<? extends OffsetMapping.Factory> userFactories,
TypeDefinition enterType) {
TypeDescription throwable = adviceMethod.getDeclaredAnnotations()
.ofType(OnMethodExit.class)
.getValue(ON_THROWABLE).resolve(TypeDescription.class);
return throwable.represents(NoExceptionHandler.class)
? new WithoutExceptionHandler(adviceMethod, userFactories, enterType)
: new WithExceptionHandler(adviceMethod, userFactories, enterType, throwable);
}
@Override
protected Bound.ForMethodExit resolve(TypeDescription instrumentedType,
MethodDescription instrumentedMethod,
MethodVisitor methodVisitor,
Implementation.Context implementationContext,
Assigner assigner,
MethodSizeHandler.ForInstrumentedMethod methodSizeHandler,
StackMapFrameHandler.ForInstrumentedMethod stackMapFrameHandler) {
List<OffsetMapping.Target> offsetMappings = new ArrayList<OffsetMapping.Target>(this.offsetMappings.size());
for (OffsetMapping offsetMapping : this.offsetMappings) {
offsetMappings.add(offsetMapping.resolve(instrumentedType,
instrumentedMethod,
assigner,
OffsetMapping.Context.ForMethodExit.of(enterType)));
}
return new AdviceMethodWriter.ForMethodExit(adviceMethod,
instrumentedMethod,
offsetMappings,
methodVisitor,
implementationContext,
methodSizeHandler.bindExit(adviceMethod, getThrowable().represents(NoExceptionHandler.class)),
stackMapFrameHandler.bindExit(adviceMethod),
suppressionHandler.bind());
}
@Override
public boolean equals(Object other) {
return this == other || !(other == null || getClass() != other.getClass())
&& super.equals(other)
&& enterType == ((Delegating.Resolved.ForMethodExit) other).enterType;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + enterType.hashCode();
return result;
}
/**
* Implementation of exit advice that handles exceptions.
*/
protected static class WithExceptionHandler extends Delegating.Resolved.ForMethodExit {
/**
* The type of the handled throwable type for which this advice is invoked.
*/
private final TypeDescription throwable;
/**
* Creates a new resolved dispatcher for implementing method exit advice that handles exceptions.
*
* @param adviceMethod The represented advice method.
* @param userFactories A list of user-defined factories for offset mappings.
* @param enterType The type of the value supplied by the enter advice method or
* a description of {@code void} if no such value exists.
* @param throwable The type of the handled throwable type for which this advice is invoked.
*/
protected WithExceptionHandler(MethodDescription.InDefinedShape adviceMethod,
List<? extends OffsetMapping.Factory> userFactories,
TypeDefinition enterType,
TypeDescription throwable) {
super(adviceMethod, userFactories, enterType);
this.throwable = throwable;
}
@Override
public TypeDescription getThrowable() {
return throwable;
}
@Override
public String toString() {
return "Advice.Dispatcher.Delegating.Resolved.ForMethodExit.WithExceptionHandler{" +
"adviceMethod=" + adviceMethod +
", offsetMappings=" + offsetMappings +
", throwable=" + throwable +
'}';
}
}
/**
* Implementation of exit advice that ignores exceptions.
*/
protected static class WithoutExceptionHandler extends Delegating.Resolved.ForMethodExit {
/**
* Creates a new resolved dispatcher for implementing method exit advice that does not handle exceptions.
*
* @param adviceMethod The represented advice method.
* @param userFactories A list of user-defined factories for offset mappings.
* @param enterType The type of the value supplied by the enter advice method or
* a description of {@code void} if no such value exists.
*/
protected WithoutExceptionHandler(MethodDescription.InDefinedShape adviceMethod,
List<? extends OffsetMapping.Factory> userFactories,
TypeDefinition enterType) {
super(adviceMethod, userFactories, enterType);
}
@Override
public TypeDescription getThrowable() {
return NoExceptionHandler.DESCRIPTION;
}
@Override
public String toString() {
return "Advice.Dispatcher.Delegating.Resolved.ForMethodExit.WithoutExceptionHandler{" +
"adviceMethod=" + adviceMethod +
", offsetMappings=" + offsetMappings +
'}';
}
}
}
}
}
}
/**
* A method visitor that weaves the advice methods' byte codes.
*/
protected abstract static class AdviceVisitor extends ExceptionTableSensitiveMethodVisitor implements Dispatcher.Bound.SkipHandler {
/**
* Indicates a zero offset.
*/
private static final int NO_OFFSET = 0;
/**
* The actual method visitor that is underlying this method visitor to which all instructions are written.
*/
protected final MethodVisitor methodVisitor;
/**
* A description of the instrumented method.
*/
protected final MethodDescription instrumentedMethod;
/**
* The required padding before using local variables after the instrumented method's arguments.
*/
private final int padding;
/**
* The dispatcher to be used for method entry.
*/
private final Dispatcher.Bound.ForMethodEnter methodEnter;
/**
* The dispatcher to be used for method exit.
*/
protected final Dispatcher.Bound.ForMethodExit methodExit;
/**
* A handler for computing the method size requirements.
*/
protected final MethodSizeHandler.ForInstrumentedMethod methodSizeHandler;
/**
* A handler for translating and injecting stack map frames.
*/
protected final StackMapFrameHandler.ForInstrumentedMethod stackMapFrameHandler;
/**
* Creates a new advice visitor.
*
* @param methodVisitor The actual method visitor that is underlying this method visitor to which all instructions are written.
* @param delegate A delegate to which all instructions of the original method are written to. Must delegate to {@code methodVisitor}.
* @param implementationContext The implementation context to use.
* @param assigner The assigner to use.
* @param instrumentedType A description of the instrumented type.
* @param instrumentedMethod The instrumented method.
* @param methodEnter The method enter advice.
* @param methodExit The method exit advice.
* @param yieldedTypes The types that are expected to be added after the instrumented method returns.
* @param writerFlags The ASM writer flags that were set.
* @param readerFlags The ASM reader flags that were set.
*/
protected AdviceVisitor(MethodVisitor methodVisitor,
MethodVisitor delegate,
Implementation.Context implementationContext,
Assigner assigner,
TypeDescription instrumentedType,
MethodDescription instrumentedMethod,
Dispatcher.Resolved.ForMethodEnter methodEnter,
Dispatcher.Resolved.ForMethodExit methodExit,
List<? extends TypeDescription> yieldedTypes,
int writerFlags,
int readerFlags) {
super(Opcodes.ASM5, delegate);
this.methodVisitor = methodVisitor;
this.instrumentedMethod = instrumentedMethod;
padding = methodEnter.getEnterType().getStackSize().getSize();
List<TypeDescription> requiredTypes = methodEnter.getEnterType().represents(void.class)
? Collections.<TypeDescription>emptyList()
: Collections.singletonList(methodEnter.getEnterType().asErasure());
methodSizeHandler = MethodSizeHandler.Default.of(instrumentedMethod, requiredTypes, yieldedTypes, writerFlags);
stackMapFrameHandler = StackMapFrameHandler.Default.of(instrumentedType,
instrumentedMethod,
requiredTypes,
yieldedTypes,
implementationContext.getClassFileVersion(),
writerFlags,
readerFlags);
this.methodEnter = methodEnter.bind(instrumentedType,
instrumentedMethod,
methodVisitor,
implementationContext,
assigner,
methodSizeHandler,
stackMapFrameHandler);
this.methodExit = methodExit.bind(instrumentedType,
instrumentedMethod,
methodVisitor,
implementationContext,
assigner,
methodSizeHandler,
stackMapFrameHandler);
}
@Override
protected void onAfterExceptionTable() {
methodEnter.prepare();
onUserPrepare();
methodExit.prepare();
methodEnter.apply(this);
onUserStart();
}
/**
* Invoked when the user method's exception handler (if any) is supposed to be prepared.
*/
protected abstract void onUserPrepare();
/**
* Writes the advice for entering the instrumented method.
*/
protected abstract void onUserStart();
@Override
protected void onVisitVarInsn(int opcode, int offset) {
mv.visitVarInsn(opcode, resolve(offset));
}
@Override
protected void onVisitIincInsn(int offset, int increment) {
mv.visitIincInsn(resolve(offset), increment);
}
/**
* Access the first variable after the instrumented variables and return type are stored.
*
* @param opcode The opcode for accessing the variable.
*/
protected void variable(int opcode) {
variable(opcode, NO_OFFSET);
}
/**
* Access the first variable after the instrumented variables and return type are stored.
*
* @param opcode The opcode for accessing the variable.
* @param offset The additional offset of the variable.
*/
protected void variable(int opcode, int offset) {
methodVisitor.visitVarInsn(opcode, instrumentedMethod.getStackSize() + padding + offset);
}
@Override
public void visitFrame(int frameType, int localVariableLength, Object[] localVariable, int stackSize, Object[] stack) {
stackMapFrameHandler.translateFrame(methodVisitor, frameType, localVariableLength, localVariable, stackSize, stack);
}
@Override
public void visitMaxs(int stackSize, int localVariableLength) {
onUserEnd();
methodVisitor.visitMaxs(methodSizeHandler.compoundStackSize(stackSize), methodSizeHandler.compoundLocalVariableLength(localVariableLength));
}
@Override
public void visitLocalVariable(String name, String descriptor, String signature, Label start, Label end, int index) {
mv.visitLocalVariable(name, descriptor, signature, start, end, resolve(index));
}
@Override
public AnnotationVisitor visitLocalVariableAnnotation(int typeReference,
TypePath typePath,
Label[] start,
Label[] end,
int[] index,
String descriptor,
boolean visible) {
return mv.visitLocalVariableAnnotation(typeReference, typePath, start, end, resolve(index), descriptor, visible);
}
/**
* Resolves the index of a local variable in the context of the instrumentation.
*
* @param index The indices to adjust.
* @return An array with adjusted indices.
*/
private int[] resolve(int[] index) {
int[] resolved = new int[index.length];
for (int anIndex = 0; anIndex < index.length; anIndex++) {
resolved[anIndex] = resolve(index[anIndex]);
}
return resolved;
}
/**
* Resolves the index of a local variable in the context of the instrumentation.
*
* @param index The index to adjust.
* @return The adjusted index.
*/
private int resolve(int index) {
return index < instrumentedMethod.getStackSize()
? index
: padding + index;
}
/**
* Writes the advice for completing the instrumented method.
*/
protected abstract void onUserEnd();
/**
* An advice visitor that does not apply exit advice.
*/
protected static class WithoutExitAdvice extends AdviceVisitor {
/**
* Creates an advice visitor that does not apply exit advice.
*
* @param methodVisitor The method visitor for the instrumented method.
* @param implementationContext The implementation context to use.
* @param assigner The assigner to use.
* @param instrumentedType A description of the instrumented type.
* @param instrumentedMethod A description of the instrumented method.
* @param methodEnter The dispatcher to be used for method entry.
* @param writerFlags The ASM writer flags that were set.
* @param readerFlags The ASM reader flags that were set.
*/
protected WithoutExitAdvice(MethodVisitor methodVisitor,
Implementation.Context implementationContext,
Assigner assigner,
TypeDescription instrumentedType,
MethodDescription instrumentedMethod,
Dispatcher.Resolved.ForMethodEnter methodEnter,
int writerFlags,
int readerFlags) {
super(methodVisitor,
methodVisitor,
implementationContext,
assigner,
instrumentedType,
instrumentedMethod,
methodEnter,
Dispatcher.Inactive.INSTANCE,
Collections.<TypeDescription>emptyList(),
writerFlags,
readerFlags);
}
@Override
protected void onUserPrepare() {
/* do nothing */
}
@Override
protected void onUserStart() {
/* do nothing */
}
@Override
protected void onUserEnd() {
/* do nothing */
}
@Override
public void apply(MethodVisitor methodVisitor) {
if (instrumentedMethod.getReturnType().represents(boolean.class)
|| instrumentedMethod.getReturnType().represents(byte.class)
|| instrumentedMethod.getReturnType().represents(short.class)
|| instrumentedMethod.getReturnType().represents(char.class)
|| instrumentedMethod.getReturnType().represents(int.class)) {
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitInsn(Opcodes.IRETURN);
} else if (instrumentedMethod.getReturnType().represents(long.class)) {
methodVisitor.visitInsn(Opcodes.LCONST_0);
methodVisitor.visitInsn(Opcodes.LRETURN);
} else if (instrumentedMethod.getReturnType().represents(float.class)) {
methodVisitor.visitInsn(Opcodes.FCONST_0);
methodVisitor.visitInsn(Opcodes.FRETURN);
} else if (instrumentedMethod.getReturnType().represents(double.class)) {
methodVisitor.visitInsn(Opcodes.DCONST_0);
methodVisitor.visitInsn(Opcodes.DRETURN);
} else if (instrumentedMethod.getReturnType().represents(void.class)) {
methodVisitor.visitInsn(Opcodes.RETURN);
} else {
methodVisitor.visitInsn(Opcodes.ACONST_NULL);
methodVisitor.visitInsn(Opcodes.ARETURN);
}
}
@Override
public String toString() {
return "Advice.AdviceVisitor.WithoutExitAdvice{" +
", instrumentedMethod=" + instrumentedMethod +
"}";
}
}
/**
* An advice visitor that applies exit advice.
*/
protected abstract static class WithExitAdvice extends AdviceVisitor {
/**
* Indicates the handler for the value returned by the advice method.
*/
protected final Label returnHandler;
/**
* {@code true} if the advice method ever returns non-exceptionally.
*/
protected boolean doesReturn;
/**
* Creates an advice visitor that applies exit advice.
*
* @param methodVisitor The method visitor for the instrumented method.
* @param implementationContext The implementation context to use.
* @param assigner The assigner to use.
* @param instrumentedType A description of the instrumented type.
* @param instrumentedMethod A description of the instrumented method.
* @param methodEnter The dispatcher to be used for method entry.
* @param methodExit The dispatcher to be used for method exit.
* @param yieldedTypes The types that are expected to be added after the instrumented method returns.
* @param writerFlags The ASM writer flags that were set.
* @param readerFlags The ASM reader flags that were set.
*/
protected WithExitAdvice(MethodVisitor methodVisitor,
Implementation.Context implementationContext,
Assigner assigner,
TypeDescription instrumentedType,
MethodDescription instrumentedMethod,
Dispatcher.Resolved.ForMethodEnter methodEnter,
Dispatcher.Resolved.ForMethodExit methodExit,
List<? extends TypeDescription> yieldedTypes,
int writerFlags,
int readerFlags) {
super(methodVisitor,
new StackAwareMethodVisitor(methodVisitor, instrumentedMethod),
implementationContext,
assigner,
instrumentedType,
instrumentedMethod,
methodEnter,
methodExit,
yieldedTypes,
writerFlags, readerFlags);
returnHandler = new Label();
doesReturn = false;
}
@Override
public void apply(MethodVisitor methodVisitor) {
if (instrumentedMethod.getReturnType().represents(boolean.class)
|| instrumentedMethod.getReturnType().represents(byte.class)
|| instrumentedMethod.getReturnType().represents(short.class)
|| instrumentedMethod.getReturnType().represents(char.class)
|| instrumentedMethod.getReturnType().represents(int.class)) {
methodVisitor.visitInsn(Opcodes.ICONST_0);
} else if (instrumentedMethod.getReturnType().represents(long.class)) {
methodVisitor.visitInsn(Opcodes.LCONST_0);
} else if (instrumentedMethod.getReturnType().represents(float.class)) {
methodVisitor.visitInsn(Opcodes.FCONST_0);
} else if (instrumentedMethod.getReturnType().represents(double.class)) {
methodVisitor.visitInsn(Opcodes.DCONST_0);
} else if (!instrumentedMethod.getReturnType().represents(void.class)) {
methodVisitor.visitInsn(Opcodes.ACONST_NULL);
}
methodVisitor.visitJumpInsn(Opcodes.GOTO, returnHandler);
doesReturn = true;
}
@Override
protected void onVisitInsn(int opcode) {
switch (opcode) {
case Opcodes.RETURN:
((StackAwareMethodVisitor) mv).drainStack();
break;
case Opcodes.IRETURN:
methodSizeHandler.requireLocalVariableLength(((StackAwareMethodVisitor) mv).drainStack(Opcodes.ISTORE, Opcodes.ILOAD, StackSize.SINGLE));
break;
case Opcodes.FRETURN:
methodSizeHandler.requireLocalVariableLength(((StackAwareMethodVisitor) mv).drainStack(Opcodes.FSTORE, Opcodes.FLOAD, StackSize.SINGLE));
break;
case Opcodes.DRETURN:
methodSizeHandler.requireLocalVariableLength(((StackAwareMethodVisitor) mv).drainStack(Opcodes.DSTORE, Opcodes.DLOAD, StackSize.DOUBLE));
break;
case Opcodes.LRETURN:
methodSizeHandler.requireLocalVariableLength((((StackAwareMethodVisitor) mv).drainStack(Opcodes.LSTORE, Opcodes.LLOAD, StackSize.DOUBLE)));
break;
case Opcodes.ARETURN:
methodSizeHandler.requireLocalVariableLength((((StackAwareMethodVisitor) mv).drainStack(Opcodes.ASTORE, Opcodes.ALOAD, StackSize.SINGLE)));
break;
default:
mv.visitInsn(opcode);
return;
}
mv.visitJumpInsn(Opcodes.GOTO, returnHandler);
doesReturn = true;
}
@Override
protected void onUserEnd() {
Type returnType = Type.getType(instrumentedMethod.getReturnType().asErasure().getDescriptor());
methodVisitor.visitLabel(returnHandler);
if (doesReturn) {
stackMapFrameHandler.injectReturnFrame(methodVisitor);
if (!returnType.equals(Type.VOID_TYPE)) {
variable(returnType.getOpcode(Opcodes.ISTORE));
}
}
onUserReturn();
methodExit.apply();
onExitAdviceReturn();
if (returnType.equals(Type.VOID_TYPE)) {
methodVisitor.visitInsn(Opcodes.RETURN);
} else {
variable(returnType.getOpcode(Opcodes.ILOAD));
methodVisitor.visitInsn(returnType.getOpcode(Opcodes.IRETURN));
}
}
/**
* Invoked after the user method has returned.
*/
protected abstract void onUserReturn();
/**
* Invoked after the exit advice method has returned.
*/
protected abstract void onExitAdviceReturn();
/**
* An advice visitor that does not capture exceptions.
*/
protected static class WithoutExceptionHandling extends WithExitAdvice {
/**
* Creates a new advice visitor that does not capture exceptions.
*
* @param methodVisitor The method visitor for the instrumented method.
* @param implementationContext The implementation context to use.
* @param assigner The assigner to use.
* @param instrumentedType A description of the instrumented type.
* @param instrumentedMethod A description of the instrumented method.
* @param methodEnter The dispatcher to be used for method entry.
* @param methodExit The dispatcher to be used for method exit.
* @param writerFlags The ASM writer flags that were set.
* @param readerFlags The ASM reader flags that were set.
*/
protected WithoutExceptionHandling(MethodVisitor methodVisitor,
Implementation.Context implementationContext,
Assigner assigner,
TypeDescription instrumentedType,
MethodDescription instrumentedMethod,
Dispatcher.Resolved.ForMethodEnter methodEnter,
Dispatcher.Resolved.ForMethodExit methodExit,
int writerFlags,
int readerFlags) {
super(methodVisitor,
implementationContext,
assigner,
instrumentedType,
instrumentedMethod,
methodEnter,
methodExit,
instrumentedMethod.getReturnType().represents(void.class)
? Collections.<TypeDescription>emptyList()
: Collections.singletonList(instrumentedMethod.getReturnType().asErasure()),
writerFlags,
readerFlags);
}
@Override
protected void onUserPrepare() {
/* empty */
}
@Override
protected void onUserStart() {
/* empty */
}
@Override
protected void onUserReturn() {
if (!doesReturn || !instrumentedMethod.getReturnType().represents(void.class)) {
stackMapFrameHandler.injectCompletionFrame(methodVisitor, false);
}
}
@Override
protected void onExitAdviceReturn() {
/* empty */
}
@Override
public String toString() {
return "Advice.AdviceVisitor.WithExitAdvice.WithoutExceptionHandling{" +
"instrumentedMethod=" + instrumentedMethod +
", doesReturn=" + doesReturn +
"}";
}
}
/**
* An advice visitor that captures exceptions by weaving try-catch blocks around user code.
*/
protected static class WithExceptionHandling extends WithExitAdvice {
/**
* The type of the handled throwable type for which this advice is invoked.
*/
private final TypeDescription throwable;
/**
* Indicates the start of the user method.
*/
private final Label userStart;
/**
* Indicates the exception handler.
*/
private final Label exceptionHandler;
/**
* Creates a new advice visitor that captures exception by weaving try-catch blocks around user code.
*
* @param methodVisitor The method visitor for the instrumented method.
* @param instrumentedType A description of the instrumented type.
* @param implementationContext The implementation context to use.
* @param assigner The assigner to use.
* @param instrumentedMethod A description of the instrumented method.
* @param methodEnter The dispatcher to be used for method entry.
* @param methodExit The dispatcher to be used for method exit.
* @param writerFlags The ASM writer flags that were set.
* @param readerFlags The ASM reader flags that were set.
* @param throwable The type of the handled throwable type for which this advice is invoked.
*/
protected WithExceptionHandling(MethodVisitor methodVisitor,
Implementation.Context implementationContext,
Assigner assigner,
TypeDescription instrumentedType,
MethodDescription instrumentedMethod,
Dispatcher.Resolved.ForMethodEnter methodEnter,
Dispatcher.Resolved.ForMethodExit methodExit,
int writerFlags,
int readerFlags,
TypeDescription throwable) {
super(methodVisitor,
implementationContext,
assigner,
instrumentedType,
instrumentedMethod,
methodEnter,
methodExit,
instrumentedMethod.getReturnType().represents(void.class)
? Collections.singletonList(TypeDescription.THROWABLE)
: Arrays.asList(instrumentedMethod.getReturnType().asErasure(), TypeDescription.THROWABLE),
writerFlags,
readerFlags);
this.throwable = throwable;
userStart = new Label();
exceptionHandler = new Label();
}
@Override
protected void onUserPrepare() {
methodVisitor.visitTryCatchBlock(userStart, returnHandler, exceptionHandler, throwable.getInternalName());
}
@Override
protected void onUserStart() {
methodVisitor.visitLabel(userStart);
}
@Override
protected void onUserReturn() {
Label endOfHandler = new Label();
if (doesReturn) {
methodVisitor.visitInsn(Opcodes.ACONST_NULL);
variable(Opcodes.ASTORE, instrumentedMethod.getReturnType().getStackSize().getSize());
methodVisitor.visitJumpInsn(Opcodes.GOTO, endOfHandler);
}
methodVisitor.visitLabel(exceptionHandler);
stackMapFrameHandler.injectExceptionFrame(methodVisitor);
variable(Opcodes.ASTORE, instrumentedMethod.getReturnType().getStackSize().getSize());
storeDefaultReturn();
if (doesReturn) {
methodVisitor.visitLabel(endOfHandler);
}
stackMapFrameHandler.injectCompletionFrame(methodVisitor, false);
}
@Override
protected void onExitAdviceReturn() {
variable(Opcodes.ALOAD, instrumentedMethod.getReturnType().getStackSize().getSize());
Label endOfHandler = new Label();
methodVisitor.visitJumpInsn(Opcodes.IFNULL, endOfHandler);
variable(Opcodes.ALOAD, instrumentedMethod.getReturnType().getStackSize().getSize());
methodVisitor.visitInsn(Opcodes.ATHROW);
methodVisitor.visitLabel(endOfHandler);
stackMapFrameHandler.injectCompletionFrame(methodVisitor, true);
}
/**
* Stores a default return value in the designated slot of the local variable array.
*/
private void storeDefaultReturn() {
if (instrumentedMethod.getReturnType().represents(boolean.class)
|| instrumentedMethod.getReturnType().represents(byte.class)
|| instrumentedMethod.getReturnType().represents(short.class)
|| instrumentedMethod.getReturnType().represents(char.class)
|| instrumentedMethod.getReturnType().represents(int.class)) {
methodVisitor.visitInsn(Opcodes.ICONST_0);
variable(Opcodes.ISTORE);
} else if (instrumentedMethod.getReturnType().represents(long.class)) {
methodVisitor.visitInsn(Opcodes.LCONST_0);
variable(Opcodes.LSTORE);
} else if (instrumentedMethod.getReturnType().represents(float.class)) {
methodVisitor.visitInsn(Opcodes.FCONST_0);
variable(Opcodes.FSTORE);
} else if (instrumentedMethod.getReturnType().represents(double.class)) {
methodVisitor.visitInsn(Opcodes.DCONST_0);
variable(Opcodes.DSTORE);
} else if (!instrumentedMethod.getReturnType().represents(void.class)) {
methodVisitor.visitInsn(Opcodes.ACONST_NULL);
variable(Opcodes.ASTORE);
}
}
@Override
public String toString() {
return "Advice.AdviceVisitor.WithExitAdvice.WithExceptionHandling{" +
"instrumentedMethod=" + instrumentedMethod +
", throwable=" + throwable +
", doesReturn=" + doesReturn +
"}";
}
}
}
}
/**
* A byte code appender for implementing {@link Advice}.
*/
protected static class Appender implements ByteCodeAppender {
/**
* The advice to implement.
*/
private final Advice advice;
/**
* The current implementation target.
*/
private final Implementation.Target implementationTarget;
/**
* The delegate byte code appender.
*/
private final ByteCodeAppender delegate;
/**
* Creates a new appender for an advice component.
*
* @param advice The advice to implement.
* @param implementationTarget The current implementation target.
* @param delegate The delegate byte code appender.
*/
protected Appender(Advice advice, Target implementationTarget, ByteCodeAppender delegate) {
this.advice = advice;
this.implementationTarget = implementationTarget;
this.delegate = delegate;
}
@Override
public Size apply(MethodVisitor methodVisitor, Context implementationContext, MethodDescription instrumentedMethod) {
EmulatingMethodVisitor emulatingMethodVisitor = new EmulatingMethodVisitor(methodVisitor, delegate);
methodVisitor = advice.doWrap(implementationTarget.getInstrumentedType(),
instrumentedMethod,
emulatingMethodVisitor,
implementationContext,
AsmVisitorWrapper.NO_FLAGS,
AsmVisitorWrapper.NO_FLAGS);
return emulatingMethodVisitor.resolve(methodVisitor, implementationContext, instrumentedMethod);
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null || getClass() != other.getClass()) return false;
Appender appender = (Appender) other;
return advice.equals(appender.advice)
&& delegate.equals(appender.delegate)
&& implementationTarget.equals(appender.implementationTarget);
}
@Override
public int hashCode() {
int result = advice.hashCode();
result = 31 * result + implementationTarget.hashCode();
result = 31 * result + delegate.hashCode();
return result;
}
@Override
public String toString() {
return "Advice.Appender{" +
"advice=" + advice +
", implementationTarget=" + implementationTarget +
", delegate=" + delegate +
'}';
}
/**
* A method visitor that allows for the emulation of a full method visitor invocation circle without delegating initial
* and ending visitations to the underlying visitor.
*/
protected static class EmulatingMethodVisitor extends MethodVisitor {
/**
* The delegate byte code appender.
*/
private final ByteCodeAppender delegate;
/**
* The currently recorded minimal required stack size.
*/
private int stackSize;
/**
* The currently recorded minimal required local variable array length.
*/
private int localVariableLength;
/**
* Creates a new emulating method visitor.
*
* @param methodVisitor The underlying method visitor.
* @param delegate The delegate byte code appender.
*/
protected EmulatingMethodVisitor(MethodVisitor methodVisitor, ByteCodeAppender delegate) {
super(Opcodes.ASM5, methodVisitor);
this.delegate = delegate;
}
/**
* Resolves this this advice emulating method visitor for its delegate.
*
* @param methodVisitor The method visitor to apply.
* @param implementationContext The implementation context to apply.
* @param instrumentedMethod The instrumented method.
* @return The resulting size of the implemented method.
*/
protected ByteCodeAppender.Size resolve(MethodVisitor methodVisitor,
Implementation.Context implementationContext,
MethodDescription instrumentedMethod) {
methodVisitor.visitCode();
Size size = delegate.apply(methodVisitor, implementationContext, instrumentedMethod);
methodVisitor.visitMaxs(size.getOperandStackSize(), size.getLocalVariableSize());
methodVisitor.visitEnd();
return new ByteCodeAppender.Size(stackSize, localVariableLength);
}
@Override
public void visitCode() {
/* do nothing */
}
@Override
public void visitMaxs(int stackSize, int localVariableLength) {
this.stackSize = stackSize;
this.localVariableLength = localVariableLength;
}
@Override
public void visitEnd() {
/* do nothing */
}
@Override
public String toString() {
return "Advice.Appender.EmulatingMethodVisitor{" +
"delegate=" + delegate +
", stackSize=" + stackSize +
", localVariableLength=" + localVariableLength +
'}';
}
}
}
/**
* <p>
* Indicates that this method should be inlined before the matched method is invoked. Any class must declare
* at most one method with this annotation. The annotated method must be static. When instrumenting constructors,
* the {@code this} values can only be accessed for writing fields but not for reading fields or invoking methods.
* </p>
* <p>
* The annotated method can return a value that is made accessible to another method annotated by {@link OnMethodExit}.
* </p>
*
* @see Advice
* @see Argument
* @see This
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@java.lang.annotation.Target(ElementType.METHOD)
public @interface OnMethodEnter {
/**
* Determines if the annotated method should be inlined into the instrumented method or invoked from it. When a method
* is inlined, its byte code is copied into the body of the target method. this makes it is possible to execute code
* with the visibility privileges of the instrumented method while loosing the privileges of the declared method methods.
* When a method is not inlined, it is invoked similarly to a common Java method call. Note that it is not possible to
* set breakpoints within a method when it is inlined as no debugging information is copied from the advice method into
* the instrumented method.
*
* @return {@code true} if the annotated method should be inlined into the instrumented method.
*/
boolean inline() default true;
/**
* Indicates that this advice should suppress any {@link Throwable} type being thrown during the advice's execution.
*
* @return The type of {@link Throwable} to suppress.
*/
Class<? extends Throwable> suppress() default NoExceptionHandler.class;
Class<?> skipOn() default void.class;
/**
* If set to {@code true}, the instrumented method's line number information is adjusted such that stack traces generated within
* this advice method appear as if they were generated within the first line of the instrumented method. If set to {@code false},
* no line number information is made available for such stack traces.
*
* @return {@code true} if this advice code should appear as if it was added within the first line of the instrumented method.
*/
boolean prependLineNumber() default true;
}
/**
* <p>
* Indicates that this method should be executed before exiting the instrumented method. Any class must declare
* at most one method with this annotation. The annotated method must be static.
* </p>
* <p>
* By default, the annotated method is not invoked if the instrumented method terminates exceptionally. This behavior
* can be changed by setting the {@link OnMethodExit#onThrowable()} property to an exception type for which this advice
* method should be invoked. By setting the value to {@link Throwable}, the advice method is always invoked.
* </p>
*
* @see Advice
* @see Argument
* @see This
* @see Enter
* @see Return
* @see Thrown
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@java.lang.annotation.Target(ElementType.METHOD)
public @interface OnMethodExit {
/**
* Determines if the annotated method should be inlined into the instrumented method or invoked from it. When a method
* is inlined, its byte code is copied into the body of the target method. this makes it is possible to execute code
* with the visibility privileges of the instrumented method while loosing the privileges of the declared method methods.
* When a method is not inlined, it is invoked similarly to a common Java method call. Note that it is not possible to
* set breakpoints within a method when it is inlined as no debugging information is copied from the advice method into
* the instrumented method.
*
* @return {@code true} if the annotated method should be inlined into the instrumented method.
*/
boolean inline() default true;
/**
* Indicates that this advice should suppress any {@link Throwable} type being thrown during the advice's execution.
*
* @return The type of {@link Throwable} to suppress.
*/
Class<? extends Throwable> suppress() default NoExceptionHandler.class;
/**
* Indicates a {@link Throwable} super type for which this exit advice is invoked if it was thrown from the instrumented method.
* If an exception is thrown, it is available via the {@link Thrown} parameter annotation. If a method returns exceptionally,
* any parameter annotated with {@link Return} is assigned the parameter type's default value.
*
* @return The type of {@link Throwable} for which this exit advice handler is invoked.
*/
Class<? extends Throwable> onThrowable() default NoExceptionHandler.class;
}
/**
* Indicates that the annotated parameter should be mapped to the parameter with index {@link Argument#value()} of
* the instrumented method.
*
* @see Advice
* @see OnMethodEnter
* @see OnMethodExit
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@java.lang.annotation.Target(ElementType.PARAMETER)
public @interface Argument {
/**
* Returns the index of the mapped parameter.
*
* @return The index of the mapped parameter.
*/
int value();
/**
* Indicates if it is possible to write to this parameter. If this property is set to {@code false}, the annotated
* type must be equal to the parameter of the instrumented method if the typing is not also set to {@link Assigner.Typing#DYNAMIC}.
* If this property is set to {@code true}, the annotated parameter can be any super type of the instrumented methods parameter.
*
* @return {@code true} if this parameter is read-only.
*/
boolean readOnly() default true;
/**
* The typing that should be applied when assigning the argument.
*
* @return The typing to apply upon assignment.
*/
Assigner.Typing typing() default Assigner.Typing.STATIC;
}
/**
* Assigns an array containing all arguments of the instrumented method to the annotated parameter. The annotated parameter must
* be an array type. If the annotation indicates writability, the assigned array must have at least as many values as the
* instrumented method or an {@link ArrayIndexOutOfBoundsException} is thrown.
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@java.lang.annotation.Target(ElementType.PARAMETER)
public @interface AllArguments {
/**
* Indicates if it is possible to write to this parameter. If this property is set to {@code false}, the annotated
* type must be equal to the type declaring the instrumented method if the typing is not also set to {@link Assigner.Typing#DYNAMIC}.
* If this property is set to {@code true}, the annotated parameter can be any super type of the instrumented method's declaring type.
*
* @return {@code true} if this parameter is read-only.
*/
boolean readOnly() default true;
/**
* The typing that should be applied when assigning the arguments.
*
* @return The typing to apply upon assignment.
*/
Assigner.Typing typing() default Assigner.Typing.STATIC;
}
/**
* <p>
* Indicates that the annotated parameter should be mapped to the {@code this} reference of the instrumented method.
* </p>
* <p>
* <b>Important</b>: Parameters with this option must not be used when from a constructor in combination with
* {@link OnMethodEnter} where the {@code this} reference is not available.
* </p>
*
* @see Advice
* @see OnMethodEnter
* @see OnMethodExit
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@java.lang.annotation.Target(ElementType.PARAMETER)
public @interface This {
/**
* Indicates if it is possible to write to this parameter. If this property is set to {@code false}, the annotated
* type must be equal to the type declaring the instrumented method if the typing is not also set to {@link Assigner.Typing#DYNAMIC}.
* If this property is set to {@code true}, the annotated parameter can be any super type of the instrumented method's declaring type.
*
* @return {@code true} if this parameter is read-only.
*/
boolean readOnly() default true;
/**
* The typing that should be applied when assigning the {@code this} value.
*
* @return The typing to apply upon assignment.
*/
Assigner.Typing typing() default Assigner.Typing.STATIC;
/**
* Determines if the parameter should be assigned {@code null} if the instrumented method is static or a constructor within
* an entry method.
*
* @return {@code true} if the value assignment is optional.
*/
boolean optional() default false;
}
/**
* <p>
* Indicates that the annotated parameter should be mapped to a field in the scope of the instrumented method.
* </p>
* <p>
* <b>Important</b>: Parameters with this option must not be used when from a constructor in combination with
* {@link OnMethodEnter} and a non-static field where the {@code this} reference is not available.
* </p>
* <p>
* <b>Note</b>: As the mapping is virtual, Byte Buddy might be required to reserve more space on the operand stack than the
* optimal value when accessing this parameter. This does not normally matter as the additional space requirement is minimal.
* However, if the runtime performance of class creation is secondary, one can require ASM to recompute the optimal frames by
* setting {@link ClassWriter#COMPUTE_MAXS}. This is however only relevant when writing to a non-static field.
* </p>
*
* @see Advice
* @see OnMethodEnter
* @see OnMethodExit
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@java.lang.annotation.Target(ElementType.PARAMETER)
public @interface FieldValue {
/**
* Returns the name of the field.
*
* @return The name of the field.
*/
String value();
/**
* Returns the type that declares the field that should be mapped to the annotated parameter. If this property
* is set to {@code void}, the field is looked up implicitly within the instrumented class's class hierarchy.
*
* @return The type that declares the field or {@code void} if this type should be determined implicitly.
*/
Class<?> declaringType() default void.class;
/**
* Indicates if it is possible to write to this parameter. If this property is set to {@code false}, the annotated
* type must be equal to the mapped field type if the typing is not also set to {@link Assigner.Typing#DYNAMIC}.
* If this property is set to {@code true}, the annotated parameter can be any super type of the field type.
*
* @return {@code true} if this parameter is read-only.
*/
boolean readOnly() default true;
/**
* The typing that should be applied when assigning the field value.
*
* @return The typing to apply upon assignment.
*/
Assigner.Typing typing() default Assigner.Typing.STATIC;
}
/**
* <p>
* Indicates that the annotated parameter should be mapped to a string representation of the instrumented method,
* a constant representing the {@link Class} declaring the adviced method or a {@link Method}, {@link Constructor}
* or {@code java.lang.reflect.Executable} representing this method.
* </p>
* <p>
* <b>Note</b>: A constant representing a {@link Method} or {@link Constructor} is not cached but is recreated for
* every read.
* </p>
*
* @see Advice
* @see OnMethodEnter
* @see OnMethodExit
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@java.lang.annotation.Target(ElementType.PARAMETER)
public @interface Origin {
/**
* Indicates that the origin string should be indicated by the {@link Object#toString()} representation of the instrumented method.
*/
String DEFAULT = "";
/**
* Returns the pattern the annotated parameter should be assigned. By default, the {@link Origin#toString()} representation
* of the method is assigned. Alternatively, a pattern can be assigned where:
* <ul>
* <li>{@code #t} inserts the method's declaring type.</li>
* <li>{@code #m} inserts the name of the method ({@code <init>} for constructors and {@code <clinit>} for static initializers).</li>
* <li>{@code #d} for the method's descriptor.</li>
* <li>{@code #s} for the method's signature.</li>
* <li>{@code #r} for the method's return type.</li>
* </ul>
* Any other {@code #} character must be escaped by {@code \} which can be escaped by itself. This property is ignored if the annotated
* parameter is of type {@link Class}.
*
* @return The pattern the annotated parameter should be assigned.
*/
String value() default DEFAULT;
}
/**
* Indicates that the annotated parameter should always return a default value (i.e. {@code 0} for numeric values, {@code false}
* for {@code boolean} types and {@code null} for reference types). Any assignments to this variable are without any effect.
*
* @see Advice
* @see OnMethodEnter
* @see OnMethodExit
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@java.lang.annotation.Target(ElementType.PARAMETER)
public @interface Unused {
/* empty */
}
/**
* Indicates that the annotated parameter should always return a default a boxed version of the instrumented methods return value
* (i.e. {@code 0} for numeric values, {@code false} for {@code boolean} types and {@code null} for reference types). The annotated
* parameter must be of type {@link Object} and cannot be assigned a value.
*
* @see Advice
* @see OnMethodEnter
* @see OnMethodExit
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@java.lang.annotation.Target(ElementType.PARAMETER)
public @interface StubValue {
/* empty */
}
/**
* <p>
* Indicates that the annotated parameter should be mapped to the value that is returned by the advice method that is annotated
* by {@link OnMethodEnter}.
* </p>
* <p><b>Note</b></p>: This annotation must only be used within an exit advice and is only meaningful in combination with an entry advice.
*
* @see Advice
* @see OnMethodExit
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@java.lang.annotation.Target(ElementType.PARAMETER)
public @interface Enter {
/**
* Indicates if it is possible to write to this parameter. If this property is set to {@code false}, the annotated
* type must be equal to the parameter of the instrumented method if the typing is not also set to {@link Assigner.Typing#DYNAMIC}.
* If this property is set to {@code true}, the annotated parameter can be any super type of the instrumented methods parameter.
*
* @return {@code true} if this parameter is read-only.
*/
boolean readOnly() default true;
/**
* The typing that should be applied when assigning the enter value.
*
* @return The typing to apply upon assignment.
*/
Assigner.Typing typing() default Assigner.Typing.STATIC;
}
/**
* <p>
* Indicates that the annotated parameter should be mapped to the return value of the instrumented method. If the instrumented
* method terminates exceptionally, the type's default value is assigned to the parameter, i.e. {@code 0} for numeric types
* and {@code null} for reference types. If the return type is {@code void}, the annotated value is {@code null} if and only if
* {@link Return#typing()} is set to {@link Assigner.Typing#DYNAMIC}.
* </p>
* <p>
* <b>Note</b>: This annotation must only be used on exit advice methods.
* </p>
*
* @see Advice
* @see OnMethodExit
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@java.lang.annotation.Target(ElementType.PARAMETER)
public @interface Return {
/**
* Indicates if it is possible to write to this parameter. If this property is set to {@code false}, the annotated
* type must be equal to the parameter of the instrumented method if the typing is not also set to {@link Assigner.Typing#DYNAMIC}.
* If this property is set to {@code true}, the annotated parameter can be any super type of the instrumented methods parameter.
*
* @return {@code true} if this parameter is read-only.
*/
boolean readOnly() default true;
/**
* Determines the typing that is applied when assigning the return value.
*
* @return The typing to apply when assigning the annotated parameter.
*/
Assigner.Typing typing() default Assigner.Typing.STATIC;
}
/**
* <p>
* Indicates that the annotated parameter should be mapped to the return value of the instrumented method. If the instrumented method terminates
* regularly, {@code null} is assigned to the annotated parameter. Note that the Java runtime does not enforce checked exceptions. In order to
* capture any error, the parameter type should be of type {@link Throwable}.
* </p>
* <p>
* <b>Note</b>: This annotation must only be used on exit advice methods.
* </p>
*
* @see Advice
* @see OnMethodExit
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@java.lang.annotation.Target(ElementType.PARAMETER)
public @interface Thrown {
boolean readOnly() default true;
/**
* Determines the typing that is applied when assigning the captured {@link Throwable} to the annotated parameter.
*
* @return The typing to apply when assigning the annotated parameter.
*/
Assigner.Typing typing() default Assigner.Typing.DYNAMIC;
}
/**
* <p>
* A dynamic value allows to bind parameters of an {@link Advice} method to a custom, constant value.
* </p>
* <p>The mapped value must be a constant value that can be embedded into a Java class file. This holds for all primitive types,
* instances of {@link String} and for {@link Class} instances as well as their unloaded {@link TypeDescription} representations.
* </p>
*
* @param <T> The type of the annotation this dynamic value requires to provide a mapping.
* @see WithCustomMapping
*/
public interface DynamicValue<T extends Annotation> {
/**
* <p>
* Resolves a constant value that is mapped to a parameter that is annotated with a custom bound annotation:
* </p>
* <ul>
* <li>A primitive wrapper value allow binding of the primitive which is optionally boxed but never unboxed.</li>
* <li>A {@link Class} or {@link TypeDescription} indicate the binding of a type constant.</li>
* <li>A {@link FieldDescription} indicates binding the field value. The field must be visible and be declared by a super type or
* be static. A field value is optionally boxed but never unboxed,</li>
* <li>A {@link ParameterDescription} indicates binding the assigned argument value. The parameter must be declared by the instrumented method.
* The parameter value is optionally boxed but never unboxed,</li>
* <li>A {@link Serializable} value is serialized and stored Base64 encoded in the constant pool.</li>
* </ul>
*
* @param instrumentedType The instrumented type.
* @param instrumentedMethod The instrumented method onto which this advice is applied.
* @param target The target parameter that is bound.
* @param annotation The annotation that triggered this binding.
* @param assigner The assigner to use.
* @param initialized {@code true} if the method is initialized when the value is bound, i.e. that the value is not
* supplied to a constructor before the super constructor was invoked.
* @return A stack manipulation that loads the parameter's value onto the stack.
*/
StackManipulation resolve(TypeDescription instrumentedType,
MethodDescription instrumentedMethod,
ParameterDescription.InDefinedShape target,
AnnotationDescription.Loadable<T> annotation,
Assigner assigner,
boolean initialized);
/**
* <p>
* A {@link DynamicValue} implementation that always binds a fixed value.
* </p>
* <p>
* The mapped value must be a constant value that can be embedded into a Java class file. This holds for all primitive types,
* instances of {@link String} and for {@link Class} instances as well as their unloaded {@link TypeDescription} representations.
* </p>
*/
abstract class ForFixedValue implements DynamicValue<Annotation> {
@Override
public StackManipulation resolve(TypeDescription instrumentedType,
MethodDescription instrumentedMethod,
ParameterDescription.InDefinedShape target,
AnnotationDescription.Loadable<Annotation> annotation,
Assigner assigner,
boolean initialized) {
Object value = doResolve(instrumentedType, instrumentedMethod, target, annotation, assigner, initialized);
StackManipulation stackManipulation;
if (value == null) {
if (target.getType().isPrimitive()) {
throw new IllegalStateException("Cannot assign null to primitive " + target);
} else {
return NullConstant.INSTANCE;
}
} else if (value instanceof Boolean) {
stackManipulation = IntegerConstant.forValue((Boolean) value);
} else if (value instanceof Byte) {
stackManipulation = IntegerConstant.forValue((Byte) value);
} else if (value instanceof Short) {
stackManipulation = IntegerConstant.forValue((Short) value);
} else if (value instanceof Character) {
stackManipulation = IntegerConstant.forValue((Character) value);
} else if (value instanceof Integer) {
stackManipulation = IntegerConstant.forValue((Integer) value);
} else if (value instanceof Long) {
stackManipulation = LongConstant.forValue((Long) value);
} else if (value instanceof Float) {
stackManipulation = FloatConstant.forValue((Float) value);
} else if (value instanceof Double) {
stackManipulation = DoubleConstant.forValue((Double) value);
} else if (value instanceof TypeDescription) {
stackManipulation = ClassConstant.of((TypeDescription) value);
} else if (value instanceof String) {
stackManipulation = new TextConstant((String) value);
} else if (value instanceof JavaConstant) {
stackManipulation = ((JavaConstant) value).asStackManipulation();
} else {
throw new IllegalStateException("Not a constant value: " + value);
}
StackManipulation assignment = assigner.assign(new TypeDescription.ForLoadedType(value.getClass()).asUnboxed().asGenericType(),
target.getType(),
Assigner.Typing.STATIC);
return new StackManipulation.Compound(stackManipulation, assignment);
}
/**
* Resolves a constant value that is mapped to a parameter that is annotated with a custom bound annotation.
*
* @param instrumentedType The instrumented type.
* @param instrumentedMethod The instrumented method onto which this advice is applied.
* @param target The target parameter that is bound.
* @param annotation The annotation that triggered this binding.
* @param assigner The assigner to use.
* @param initialized {@code true} if the method is initialized when the value is bound, i.e. that the value is not
* supplied to a constructor before the super constructor was invoked.
* @return A constant value to bind to the supplied annotation.
*/
protected abstract Object doResolve(TypeDescription instrumentedType,
MethodDescription instrumentedMethod,
ParameterDescription.InDefinedShape target,
AnnotationDescription.Loadable<Annotation> annotation,
Assigner assigner,
boolean initialized);
/**
* A fixed value binding for a constant pool value.
*/
protected static class OfConstant extends ForFixedValue {
/**
* The constant value being bound.
*/
private final Object value;
/**
* Creates a dynamic binding for a fixed constant.
*
* @param value The constant value being bound.
*/
protected OfConstant(Object value) {
this.value = value;
}
@Override
protected Object doResolve(TypeDescription instrumentedType,
MethodDescription instrumentedMethod,
ParameterDescription.InDefinedShape target,
AnnotationDescription.Loadable<Annotation> annotation,
Assigner assigner,
boolean initialized) {
if (value == null) {
return null;
} else if (value instanceof Class) {
return new TypeDescription.ForLoadedType((Class<?>) value);
} else if (JavaType.METHOD_HANDLE.getTypeStub().isInstance(value)) {
return JavaConstant.MethodHandle.ofLoaded(value);
} else if (JavaType.METHOD_TYPE.getTypeStub().isInstance(value)) {
return JavaConstant.MethodType.ofLoaded(value);
} else {
return value;
}
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
OfConstant that = (OfConstant) object;
return value.equals(that.value);
}
@Override
public int hashCode() {
return value.hashCode();
}
@Override
public String toString() {
return "Advice.DynamicValue.ForFixedValue.OfConstant{" +
"value=" + value +
'}';
}
}
/**
* A dynamic value binding for an annotation property of an annotation on the bound parameter.
*/
protected static class OfAnnotationProperty extends ForFixedValue {
/**
* The annotation property to bind.
*/
private final MethodDescription.InDefinedShape property;
/**
* Creates a new fixed value binding for an annotation property.
*
* @param property The annotation property to bind.
*/
protected OfAnnotationProperty(MethodDescription.InDefinedShape property) {
this.property = property;
}
/**
* Resolves a fixed value for an annotation property.
*
* @param type The annotation type.
* @param property The name of the property.
* @param <T> The annotation type.
* @return A dynamic value binding for the supplied annotation's property.
*/
@SuppressWarnings("unchecked")
protected static <T extends Annotation> DynamicValue<T> of(Class<? extends T> type, String property) {
return (DynamicValue<T>) new OfAnnotationProperty(new TypeDescription.ForLoadedType(type).getDeclaredMethods().filter(named(property)).getOnly());
}
@Override
protected Object doResolve(TypeDescription instrumentedType,
MethodDescription instrumentedMethod,
ParameterDescription.InDefinedShape target,
AnnotationDescription.Loadable<Annotation> annotation,
Assigner assigner,
boolean initialized) {
return annotation.getValue(property).resolve();
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
OfAnnotationProperty that = (OfAnnotationProperty) object;
return property.equals(that.property);
}
@Override
public int hashCode() {
return property.hashCode();
}
@Override
public String toString() {
return "Advice.DynamicValue.ForFixedValue.OfAnnotationProperty{" +
"property=" + property +
'}';
}
}
}
/**
* A dynamic value binding for a field value.
*/
class ForFieldValue implements DynamicValue<Annotation> {
/**
* The field for which to bind a value.
*/
private final FieldDescription fieldDescription;
/**
* Creates a new dynamic value binding for a field value.
*
* @param fieldDescription The field for which to bind a value.
*/
protected ForFieldValue(FieldDescription fieldDescription) {
this.fieldDescription = fieldDescription;
}
@Override
public StackManipulation resolve(TypeDescription instrumentedType,
MethodDescription instrumentedMethod,
ParameterDescription.InDefinedShape target,
AnnotationDescription.Loadable<Annotation> annotation,
Assigner assigner,
boolean initialized) {
if (!fieldDescription.isStatic()) {
if (instrumentedMethod.isStatic()) {
throw new IllegalStateException("Cannot access " + instrumentedMethod + " from " + fieldDescription);
} else if (!instrumentedType.isAssignableTo(fieldDescription.getDeclaringType().asErasure())) {
throw new IllegalStateException(fieldDescription + " is not declared by " + instrumentedType);
}
}
if (!fieldDescription.isVisibleTo(instrumentedType)) {
throw new IllegalStateException("Cannot access " + fieldDescription + " from " + instrumentedType);
}
StackManipulation assignment = assigner.assign(fieldDescription.getType(), target.getType(), Assigner.Typing.STATIC);
if (!assignment.isValid()) {
throw new IllegalStateException("Cannot assign " + fieldDescription + " to " + target.getType());
}
return new StackManipulation.Compound(
fieldDescription.isStatic()
? StackManipulation.Trivial.INSTANCE
: MethodVariableAccess.REFERENCE.loadFrom(0),
FieldAccess.forField(fieldDescription).getter(),
assignment
);
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
ForFieldValue that = (ForFieldValue) object;
return fieldDescription.equals(that.fieldDescription);
}
@Override
public int hashCode() {
return fieldDescription.hashCode();
}
@Override
public String toString() {
return "Advice.DynamicValue.ForFieldValue{" +
"fieldDescription=" + fieldDescription +
'}';
}
}
/**
* A dynamic value binding for a method parameter.
*/
class ForParameterValue implements DynamicValue<Annotation> {
/**
* The parameter to bind.
*/
private final ParameterDescription parameterDescription;
/**
* Creates a new dynamic binding for a parameter.
*
* @param parameterDescription The parameter to bind.
*/
protected ForParameterValue(ParameterDescription parameterDescription) {
this.parameterDescription = parameterDescription;
}
@Override
public StackManipulation resolve(TypeDescription instrumentedType,
MethodDescription instrumentedMethod,
ParameterDescription.InDefinedShape target,
AnnotationDescription.Loadable<Annotation> annotation,
Assigner assigner,
boolean initialized) {
if (!parameterDescription.getDeclaringMethod().equals(instrumentedMethod)) {
throw new IllegalStateException(parameterDescription + " is not declared by " + instrumentedMethod);
}
StackManipulation assignment = assigner.assign(parameterDescription.getType(), target.getType(), Assigner.Typing.STATIC);
if (!assignment.isValid()) {
throw new IllegalStateException("Cannot assign " + parameterDescription + " to " + target.getType());
}
return new StackManipulation.Compound(
MethodVariableAccess.of(parameterDescription.getType()).loadFrom(parameterDescription.getOffset()),
assignment
);
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
ForParameterValue that = (ForParameterValue) object;
return parameterDescription.equals(that.parameterDescription);
}
@Override
public int hashCode() {
return parameterDescription.hashCode();
}
@Override
public String toString() {
return "Advice.DynamicValue.ForParameterValue{" +
"parameterDescription=" + parameterDescription +
'}';
}
}
/**
* A dynamic value binding that serializes the value as a string and deserializes this string on demand.
*/
class ForSerializedValue implements DynamicValue<Annotation> {
/**
* A charset that does not change the supplied byte array upon encoding or decoding.
*/
private static final String CHARSET = "ISO-8859-1";
/**
* The {@link String#getBytes(String)} method.
*/
private static final MethodDescription.InDefinedShape GET_BYTES;
/**
* The {@link ByteArrayInputStream#ByteArrayInputStream(byte[])} constructor.
*/
private static final MethodDescription.InDefinedShape CREATE_BYTE_ARRAY_INPUT_STREAM;
/**
* The {@link ObjectInputStream#ObjectInputStream()} constructor.
*/
private static final MethodDescription.InDefinedShape CREATE_OBJECT_INPUT_STREAM;
/**
* The {@link ObjectInputStream#readObject()} method.
*/
private static final MethodDescription.InDefinedShape READ_OBJECT;
/*
* Looks up method description for the methods to be invoked from this dynamic value.
*/
static {
GET_BYTES = new TypeDescription.ForLoadedType(String.class).getDeclaredMethods()
.filter(named("getBytes").and(takesArguments(String.class))).getOnly();
CREATE_BYTE_ARRAY_INPUT_STREAM = new TypeDescription.ForLoadedType(ByteArrayInputStream.class).getDeclaredMethods()
.filter(isConstructor().and(takesArguments(byte[].class))).getOnly();
CREATE_OBJECT_INPUT_STREAM = new TypeDescription.ForLoadedType(ObjectInputStream.class).getDeclaredMethods()
.filter(isConstructor().and(takesArguments(InputStream.class))).getOnly();
READ_OBJECT = new TypeDescription.ForLoadedType(ObjectInputStream.class).getDeclaredMethods()
.filter(named("readObject").and(takesArguments(0))).getOnly();
}
/**
* The represented type.
*/
private final TypeDescription typeDescription;
/**
* The string-representation of the serializable value.
*/
private final String value;
/**
* Creates a new dynamic value for representing a serializable value.
*
* @param typeDescription The represented type.
* @param value The string-representation of the serializable value.
*/
protected ForSerializedValue(TypeDescription typeDescription, String value) {
this.typeDescription = typeDescription;
this.value = value;
}
/**
* Creates a dynamic value for binding to an annotation for representing a serializable value.
*
* @param value The value to represent.
* @return A dynamic value binding for the supplied serializable value.
*/
protected static DynamicValue<Annotation> of(Serializable value) {
try {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
try {
objectOutputStream.writeObject(value);
} finally {
objectOutputStream.close();
}
return new ForSerializedValue(new TypeDescription.ForLoadedType(value.getClass()), byteArrayOutputStream.toString(CHARSET));
} catch (IOException exception) {
throw new IllegalStateException("Cannot serialize " + value, exception);
}
}
@Override
public StackManipulation resolve(TypeDescription instrumentedType,
MethodDescription instrumentedMethod,
ParameterDescription.InDefinedShape target,
AnnotationDescription.Loadable<Annotation> annotation,
Assigner assigner,
boolean initialized) {
StackManipulation assignment = assigner.assign(typeDescription.asGenericType(), target.getType(), Assigner.Typing.DYNAMIC);
if (!assignment.isValid()) {
throw new IllegalStateException("Cannot assign " + typeDescription + " to " + target.getType());
}
return new StackManipulation.Compound(
TypeCreation.of(new TypeDescription.ForLoadedType(ObjectInputStream.class)),
Duplication.SINGLE,
TypeCreation.of(new TypeDescription.ForLoadedType(ByteArrayInputStream.class)),
Duplication.SINGLE,
new TextConstant(value),
new TextConstant(CHARSET),
MethodInvocation.invoke(GET_BYTES),
MethodInvocation.invoke(CREATE_BYTE_ARRAY_INPUT_STREAM),
MethodInvocation.invoke(CREATE_OBJECT_INPUT_STREAM),
MethodInvocation.invoke(READ_OBJECT),
assignment
);
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
ForSerializedValue that = (ForSerializedValue) object;
return typeDescription.equals(that.typeDescription) && value.equals(that.value);
}
@Override
public int hashCode() {
int result = typeDescription.hashCode();
result = 31 * result + value.hashCode();
return result;
}
@Override
public String toString() {
return "Advice.DynamicValue.ForSerializedValue{" +
"typeDescription=" + typeDescription +
", value='" + value + '\'' +
'}';
}
}
}
/**
* A builder step for creating an {@link Advice} that uses custom mappings of annotations to constant pool values.
*/
public static class WithCustomMapping {
/**
* A map containing dynamically computed constant pool values that are mapped by their triggering annotation type.
*/
private final Map<Class<? extends Annotation>, DynamicValue<?>> dynamicValues;
/**
* Creates a new custom mapping builder step without including any custom mappings.
*/
protected WithCustomMapping() {
this(Collections.<Class<? extends Annotation>, DynamicValue<?>>emptyMap());
}
/**
* Creates a new custom mapping builder step with the given custom mappings.
*
* @param dynamicValues A map containing dynamically computed constant pool values that are mapped by their triggering annotation type.
*/
protected WithCustomMapping(Map<Class<? extends Annotation>, DynamicValue<?>> dynamicValues) {
this.dynamicValues = dynamicValues;
}
/**
* Binds the supplied annotation to a type constant of the supplied value. Constants can be strings, method handles, method types
* and any primitive or the value {@code null}.
*
* @param type The type of the annotation being bound.
* @param value The value to bind to the annotation.
* @param <T> The annotation type.
* @return A new builder for an advice that considers the supplied annotation type during binding.
* @see DynamicValue.ForFixedValue
*/
public <T extends Annotation> WithCustomMapping bind(Class<? extends T> type, Object value) {
return bind(type, new DynamicValue.ForFixedValue.OfConstant(value));
}
/**
* Binds the supplied annotation to the value of the supplied field. The field must be visible by the
* instrumented type and must be declared by a super type of the instrumented field.
*
* @param type The type of the annotation being bound.
* @param field The field to bind to this annotation.
* @param <T> The annotation type.
* @return A new builder for an advice that considers the supplied annotation type during binding.
* @see DynamicValue.ForFixedValue
*/
public <T extends Annotation> WithCustomMapping bind(Class<? extends T> type, Field field) {
return bind(type, new FieldDescription.ForLoadedField(field));
}
/**
* Binds the supplied annotation to the value of the supplied field. The field must be visible by the
* instrumented type and must be declared by a super type of the instrumented field.
*
* @param type The type of the annotation being bound.
* @param fieldDescription The field to bind to this annotation.
* @param <T> The annotation type.
* @return A new builder for an advice that considers the supplied annotation type during binding.
* @see DynamicValue.ForFixedValue
*/
public <T extends Annotation> WithCustomMapping bind(Class<? extends T> type, FieldDescription fieldDescription) {
return bind(type, new DynamicValue.ForFieldValue(fieldDescription));
}
/**
* Binds the supplied annotation to the supplied parameter's argument.
*
* @param type The type of the annotation being bound.
* @param method The method that defines the parameter.
* @param index The index of the parameter.
* @param <T> The annotation type.
* @return A new builder for an advice that considers the supplied annotation type during binding.
* @see DynamicValue.ForFixedValue
*/
public <T extends Annotation> WithCustomMapping bind(Class<? extends T> type, Method method, int index) {
if (index < 0) {
throw new IllegalArgumentException("A parameter cannot be negative: " + index);
} else if (method.getParameterTypes().length <= index) {
throw new IllegalArgumentException(method + " does not declare a parameter with index " + index);
}
return bind(type, new MethodDescription.ForLoadedMethod(method).getParameters().get(index));
}
/**
* Binds the supplied annotation to the supplied parameter's argument.
*
* @param type The type of the annotation being bound.
* @param constructor The constructor that defines the parameter.
* @param index The index of the parameter.
* @param <T> The annotation type.
* @return A new builder for an advice that considers the supplied annotation type during binding.
* @see DynamicValue.ForFixedValue
*/
public <T extends Annotation> WithCustomMapping bind(Class<? extends T> type, Constructor<?> constructor, int index) {
if (index < 0) {
throw new IllegalArgumentException("A parameter cannot be negative: " + index);
} else if (constructor.getParameterTypes().length <= index) {
throw new IllegalArgumentException(constructor + " does not declare a parameter with index " + index);
}
return bind(type, new MethodDescription.ForLoadedConstructor(constructor).getParameters().get(index));
}
/**
* Binds the supplied annotation to the supplied parameter's argument.
*
* @param type The type of the annotation being bound.
* @param parameterDescription The parameter for which to bind an argument.
* @param <T> The annotation type.
* @return A new builder for an advice that considers the supplied annotation type during binding.
* @see DynamicValue.ForFixedValue
*/
public <T extends Annotation> WithCustomMapping bind(Class<? extends T> type, ParameterDescription parameterDescription) {
return bind(type, new DynamicValue.ForParameterValue(parameterDescription));
}
/**
* Binds the supplied annotation to the supplied fixed value.
*
* @param type The type of the annotation being bound.
* @param value The value to bind to this annotation.
* @param <T> The annotation type.
* @return A new builder for an advice that considers the supplied annotation type during binding.
* @see DynamicValue.ForFixedValue
*/
public <T extends Annotation> WithCustomMapping bindSerialized(Class<? extends T> type, Serializable value) {
return bind(type, DynamicValue.ForSerializedValue.of(value));
}
/**
* Binds the supplied annotation to the annotation's property of the specified name.
*
* @param type The type of the annotation being bound.
* @param property The name of the annotation property to be bound.
* @param <T> The annotation type.
* @return A new builder for an advice that considers the supplied annotation during binding.
*/
public <T extends Annotation> WithCustomMapping bindProperty(Class<? extends T> type, String property) {
return bind(type, DynamicValue.ForFixedValue.OfAnnotationProperty.<T>of(type, property));
}
/**
* Binds an annotation type to dynamically computed value. Whenever the {@link Advice} component discovers the given annotation on
* a parameter of an advice method, the dynamic value is asked to provide a value that is then assigned to the parameter in question.
*
* @param type The annotation type that triggers the mapping.
* @param dynamicValue The dynamic value that is computed for binding the parameter to a value.
* @param <T> The annotation type.
* @return A new builder for an advice that considers the supplied annotation type during binding.
*/
public <T extends Annotation> WithCustomMapping bind(Class<? extends T> type, DynamicValue<T> dynamicValue) {
Map<Class<? extends Annotation>, DynamicValue<?>> dynamicValues = new HashMap<Class<? extends Annotation>, Advice.DynamicValue<?>>(this.dynamicValues);
if (!type.isAnnotation()) {
throw new IllegalArgumentException("Not an annotation type: " + type);
} else if (dynamicValues.put(type, dynamicValue) != null) {
throw new IllegalArgumentException("Annotation type already mapped: " + type);
}
return new WithCustomMapping(dynamicValues);
}
/**
* Implements advice where every matched method is advised by the given type's advisory methods. The advices binary representation is
* accessed by querying the class loader of the supplied class for a class file.
*
* @param advice The type declaring the advice.
* @return A method visitor wrapper representing the supplied advice.
*/
public Advice to(Class<?> advice) {
return to(advice, ClassFileLocator.ForClassLoader.of(advice.getClassLoader()));
}
/**
* Implements advice where every matched method is advised by the given type's advisory methods.
*
* @param advice The type declaring the advice.
* @param classFileLocator The class file locator for locating the advisory class's class file.
* @return A method visitor wrapper representing the supplied advice.
*/
public Advice to(Class<?> advice, ClassFileLocator classFileLocator) {
return to(new TypeDescription.ForLoadedType(advice), classFileLocator);
}
/**
* Implements advice where every matched method is advised by the given type's advisory methods.
*
* @param advice A description of the type declaring the advice.
* @param classFileLocator The class file locator for locating the advisory class's class file.
* @return A method visitor wrapper representing the supplied advice.
*/
public Advice to(TypeDescription advice, ClassFileLocator classFileLocator) {
List<Dispatcher.OffsetMapping.Factory> userFactories = new ArrayList<Dispatcher.OffsetMapping.Factory>(dynamicValues.size());
for (Map.Entry<Class<? extends Annotation>, DynamicValue<?>> entry : dynamicValues.entrySet()) {
userFactories.add(Dispatcher.OffsetMapping.ForUserValue.Factory.of(entry.getKey(), entry.getValue()));
}
return Advice.to(advice, classFileLocator, userFactories);
}
/**
* Implements advice where every matched method is advised by the given type's advisory methods. The advices binary representation is
* accessed by querying the class loader of the supplied class for a class file.
*
* @param enterAdvice The type declaring the enter advice.
* @param exitAdvice The type declaring the exit advice.
* @return A method visitor wrapper representing the supplied advice.
*/
public Advice to(Class<?> enterAdvice, Class<?> exitAdvice) {
ClassLoader enterLoader = enterAdvice.getClassLoader(), exitLoader = exitAdvice.getClassLoader();
return to(enterAdvice, exitAdvice, enterLoader == exitLoader
? ClassFileLocator.ForClassLoader.of(enterLoader)
: new ClassFileLocator.Compound(ClassFileLocator.ForClassLoader.of(enterLoader), ClassFileLocator.ForClassLoader.of(exitLoader)));
}
/**
* Implements advice where every matched method is advised by the given type's advisory methods.
*
* @param enterAdvice The type declaring the enter advice.
* @param exitAdvice The type declaring the exit advice.
* @param classFileLocator The class file locator for locating the advisory class's class file.
* @return A method visitor wrapper representing the supplied advice.
*/
public Advice to(Class<?> enterAdvice, Class<?> exitAdvice, ClassFileLocator classFileLocator) {
return to(new TypeDescription.ForLoadedType(enterAdvice), new TypeDescription.ForLoadedType(exitAdvice), classFileLocator);
}
/**
* Implements advice where every matched method is advised by the given type's advisory methods. Using this method, a non-operational
* class file locator is specified for the advice target. This implies that only advice targets with the <i>inline</i> target set
* to {@code false} are resolvable by the returned instance.
*
* @param enterAdvice The type declaring the enter advice.
* @param exitAdvice The type declaring the exit advice.
* @return A method visitor wrapper representing the supplied advice.
*/
public Advice to(TypeDescription enterAdvice, TypeDescription exitAdvice) {
return to(enterAdvice, exitAdvice, ClassFileLocator.NoOp.INSTANCE);
}
/**
* Implements advice where every matched method is advised by the given type's advisory methods.
*
* @param enterAdvice The type declaring the enter advice.
* @param exitAdvice The type declaring the exit advice.
* @param classFileLocator The class file locator for locating the advisory class's class file.
* @return A method visitor wrapper representing the supplied advice.
*/
public Advice to(TypeDescription enterAdvice, TypeDescription exitAdvice, ClassFileLocator classFileLocator) {
List<Dispatcher.OffsetMapping.Factory> userFactories = new ArrayList<Dispatcher.OffsetMapping.Factory>(dynamicValues.size());
for (Map.Entry<Class<? extends Annotation>, DynamicValue<?>> entry : dynamicValues.entrySet()) {
userFactories.add(Dispatcher.OffsetMapping.ForUserValue.Factory.of(entry.getKey(), entry.getValue()));
}
return Advice.to(enterAdvice, exitAdvice, classFileLocator, userFactories);
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null || getClass() != other.getClass()) return false;
WithCustomMapping that = (WithCustomMapping) other;
return dynamicValues.equals(that.dynamicValues);
}
@Override
public int hashCode() {
return dynamicValues.hashCode();
}
@Override
public String toString() {
return "Advice.WithCustomMapping{" +
"dynamicValues=" + dynamicValues +
'}';
}
}
/**
* A marker class that indicates that an advice method does not suppress any {@link Throwable}.
*/
private static class NoExceptionHandler extends Throwable {
/**
* A description of the {@link NoExceptionHandler} type.
*/
private static final TypeDescription DESCRIPTION = new TypeDescription.ForLoadedType(NoExceptionHandler.class);
/**
* A private constructor as this class is not supposed to be invoked.
*/
private NoExceptionHandler() {
throw new UnsupportedOperationException("This marker class is not supposed to be instantiated");
}
}
public static final class OnDefaultValue {
/**
* A private constructor as this class is not supposed to be invoked.
*/
private OnDefaultValue() {
throw new UnsupportedOperationException("This marker class is not supposed to be instantiated");
}
}
public static final class OnNonDefaultValue {
/**
* A private constructor as this class is not supposed to be invoked.
*/
private OnNonDefaultValue() {
throw new UnsupportedOperationException("This marker class is not supposed to be instantiated");
}
}
}
|
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.BitSet;
import java.util.Scanner;
public class PoetryBot
{
public static int POETRYBOTVERSION = 1;
private void run()
{
Scanner listener = new Scanner(System.in);
System.out.println("Hello! I am Poetry Bot.");
System.out.println("I am poetry bot #" + POETRYBOTVERSION);
System.out.println();
System.out.print("What would you like me to write about? ");
String input = listener.nextLine();
System.out.println();
System.out.println("I will write about " + '"' + input + '"' + ".");
byte[] hash = getSHA512(input);
BitSet foo = getBits(hash);
printBitSet(foo);
listener.close();
}
private static void printBitSet(BitSet b)
{
for(int i = 0; i < 512; ++ i)
{
if(b.get(i))
{
System.out.print("1");
}
else
{
System.out.print("0");
}
}
}
private static byte[] getSHA512(String input)
{
MessageDigest sHAer = null;
byte[] hash = null;
try
{
sHAer = MessageDigest.getInstance("SHA-512");
}
catch (NoSuchAlgorithmException e1) { e1.printStackTrace(); }
try
{
hash = sHAer.digest(input.getBytes("UTF-8"));
}
catch (UnsupportedEncodingException e) { e.printStackTrace(); }
return hash;
}
private static BitSet getBits(byte[] bytes)
{
BitSet returnVal = BitSet.valueOf(bytes);
return returnVal;
}
public static void main(String[] args)
{
PoetryBot pb = new PoetryBot();
pb.run();
}
}
|
package com.infield.googlesearch;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import javax.servlet.ServletException;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.apache.sling.commons.json.JSONObject;
import org.apache.sling.commons.osgi.PropertiesUtil;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.customsearch.Customsearch;
import com.google.api.services.customsearch.CustomsearchRequestInitializer;
import com.google.api.services.customsearch.model.Search;
import com.google.api.services.customsearch.model.Search.SearchInformation;
@Component(
metatype = true,
label = "Google Custom Search Servlet",
description = "Servlet used to call Google Custom Services."
)
@Service
@Properties(
{
@Property(
name = "service.pid",
value = "com.infield.googlesearch.GoogleSearchServlet"
),
@Property(
name = "service.vendor",
value = "Infield"
),
@Property(
name = "sling.servlet.paths",
value = {GoogleSearchServlet.searchServletPath, GoogleSearchServlet.KBSearchServletPath},
propertyPrivate = true
),
@Property(
name = "sling.servlet.methods",
value = "GET",
propertyPrivate = true
)
}
)
public class GoogleSearchServlet extends SlingAllMethodsServlet {
private final Logger log = LoggerFactory.getLogger(getClass());
public static final String searchServletPath = "/services/SearchServlet";
public static final String KBSearchServletPath = "/services/KBSearchServlet";
@Property(label = "Application Name", description = "Be sure to specify the name of your application. "
+ "If the application name is null or blank, the application will log a warning. "
+ "Suggested format is 'MyCompany-ProductName/1.0'.")
private static final String APPLICATION_NAME = "cse.application.name";
@Property(label = "API Key", description = "API Key for the registered developer project for your application.")
private static final String API_KEY = "cse.api.key";
@Property(label = "Context", description = "The main search engine ID to scope the search query")
private static final String CX = "cse.cx";
@Property(label = "KB Context", description = "The KB (knowledge base) search engine ID to scope the search query")
private static final String KB_CX = "cse.kb_cx";
@Property(label = "Number", description = "Number of search results to return (integer)")
private static final String NUM = "cse.num";
@Property(label = "Pages", description = "Number of pages to show (integer)")
private static final String PAGES = "cse.pages";
private String api_key;
private String application_name;
private String cx;
private String kb_cx;
private Long num;
private Long pagesToShow;
private Long pagesRight;
private Long pagesLeft;
private Customsearch customsearch;
static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
private static final long serialVersionUID = 1L;
@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
throws ServletException, IOException {
String requestedPath = request.getRequestURI();
String q = request.getParameter("q");
String currentTab = request.getParameter("currentTab") != null ? request.getParameter("currentTab") : "1";
JSONObject jsonObject = new JSONObject();
try {
Long actualPage = Long.valueOf(currentTab);
com.google.api.services.customsearch.Customsearch.Cse.List list = customsearch.cse().list(q);
list.setNum(num);
list.setStart((num * (actualPage - 1)) + 1);
list.setCx(requestedPath.equals(searchServletPath) ? cx : kb_cx);
Search results = list.execute();
SearchInformation searchInformation = results.getSearchInformation();
Long totalResults = searchInformation.getTotalResults();
Long totalPages = new BigDecimal(totalResults).divide(new BigDecimal(num), RoundingMode.UP).longValue();
jsonObject.put("startPage", getStartPage(actualPage));
jsonObject.put("endPage", getEndPage(actualPage,totalPages));
jsonObject.put("totalPages", totalPages);
jsonObject.put("currentTab", actualPage);
jsonObject.put("results", results.getItems());
} catch (Exception e) {
log.error(e.getMessage(), e);
}
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
response.getWriter().print(jsonObject.toString());
}
private Long getEndPage(Long actualPage, Long totalPages) {
if (totalPages <= pagesToShow || (actualPage + (pagesRight - 1)) > totalPages) {
return totalPages;
}
if (actualPage + (pagesRight - 1) <= pagesToShow) {
return pagesToShow;
}
return actualPage + (pagesRight - 1);
}
private Long getStartPage(Long actualPage) {
if ((actualPage - pagesLeft) <= 0l) return 1l;
return actualPage-pagesLeft;
}
protected void activate(ComponentContext ctx) {
try {
api_key = PropertiesUtil.toString(ctx.getProperties().get(API_KEY), "");
application_name = PropertiesUtil.toString(ctx.getProperties().get(APPLICATION_NAME), "");
cx = PropertiesUtil.toString(ctx.getProperties().get(CX), "");
kb_cx = PropertiesUtil.toString(ctx.getProperties().get(KB_CX), "");
num = PropertiesUtil.toLong(ctx.getProperties().get(NUM), 7l);
pagesToShow = PropertiesUtil.toLong(ctx.getProperties().get(PAGES), 10l);
pagesLeft = new BigDecimal(pagesToShow).divide(new BigDecimal(2), RoundingMode.UP).longValue();
pagesRight = new BigDecimal(pagesToShow).divide(new BigDecimal(2), RoundingMode.DOWN).longValue();
customsearch = new Customsearch.Builder(GoogleNetHttpTransport.newTrustedTransport(), JSON_FACTORY, null)
.setApplicationName(application_name)
.setGoogleClientRequestInitializer(new CustomsearchRequestInitializer(api_key))
.build();
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
}
|
/**
*
* @author Tom Naessens Tom.Naessens@UGent.be 3de Bachelor Informatica Universiteit Gent
*
*/
package be.ugent.zeus.hydra.ui;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import be.ugent.zeus.hydra.Hydra;
import be.ugent.zeus.hydra.R;
import be.ugent.zeus.hydra.data.Activity;
import com.emilsjolander.components.stickylistheaders.StickyListHeadersAdapter;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class ActivityListAdapter extends BaseAdapter implements StickyListHeadersAdapter {
private Activity[] activities;
private LayoutInflater inflater;
private Context context;
public ActivityListAdapter(Context context, List<Activity> items) {
this.context = context;
inflater = LayoutInflater.from(context);
this.activities = new Activity[items.size()];
activities = items.toArray(activities);
Arrays.sort(activities, new ActivityComparator());
}
@Override
public int getCount() {
return activities.length;
}
@Override
public Object getItem(int position) {
return activities[position];
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.activity_list_item, parent, false);
holder.title = (TextView) convertView.findViewById(R.id.activity_item_title);
holder.assocation = (TextView) convertView.findViewById(R.id.activity_item_association);
holder.time = (TextView) convertView.findViewById(R.id.activity_item_time_location);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Activity activity = activities[position];
holder.title.setText(activity.title);
holder.assocation.setText(activity.association.display_name);
holder.time.setText(activity.start.substring(11, 16));
if (activity.highlighted == 1) {
int higlightedid = context.getResources().getIdentifier("drawable/icon_star", null, "be.ugent.zeus.hydra");
holder.title.setCompoundDrawablesWithIntrinsicBounds(higlightedid, 0, 0, 0);
holder.title.setCompoundDrawablePadding(10);
} else {
holder.title.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
holder.title.setCompoundDrawablePadding(0);
}
return convertView;
}
@Override
public View getHeaderView(int position, View convertView, ViewGroup parent) {
HeaderViewHolder holder;
if (convertView == null) {
holder = new HeaderViewHolder();
convertView = inflater.inflate(R.layout.activity_list_header, parent, false);
holder.header_text = (TextView) convertView.findViewById(R.id.header_text);
convertView.setTag(holder);
} else {
holder = (HeaderViewHolder) convertView.getTag();
}
String headerChar = new SimpleDateFormat("dd MMMM", Hydra.LOCALE).format(activities[position].startDate);
holder.header_text.setText(headerChar);
return convertView;
}
//remember that these have to be static, postion=1 should walys return the same Id that is.
@Override
public long getHeaderId(int position) {
return new SimpleDateFormat("dd MMMM").format(activities[position].startDate).hashCode();
}
class HeaderViewHolder {
TextView header_text;
}
class ViewHolder {
TextView title;
TextView assocation;
TextView time;
}
private class ActivityComparator implements Comparator<Activity> {
public int compare(Activity item1, Activity item2) {
return item1.start.compareTo(item2.start);
}
}
}
|
package opendap.bes.caching;
import opendap.bes.BES;
import opendap.bes.BESError;
import opendap.bes.BadConfigurationException;
import opendap.bes.dap2Responders.BesApi;
import opendap.ppt.PPTException;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* An in-memory cache for BES showNode responses. This class is a singleton.
*/
public class BesNodeCache {
public static final String NODE_CACHE_ELEMENT_NAME = "NodeCache";
private static final String MAX_ENTRIES_ATTRIBUTE_NAME = "maxEntries";
private static final String REFRESH_INTERVAL_ATTRIBUTE_NAME = "refreshInterval";
private static final long NODE_CACHE_MAX_ENTRIES_DEFAULT = 2000;
private static final long NODE_CACHE_REFRESH_INTERVAL_DEFAULT = 600;
private static final ReentrantReadWriteLock RWLOCK = new ReentrantReadWriteLock();
private static final ReentrantLock LOCK = new ReentrantLock();
private static final Logger LOG = LoggerFactory.getLogger(NODE_CACHE_ELEMENT_NAME);
private static final ConcurrentHashMap<String,NodeTransaction> NODE_CACHE = new ConcurrentHashMap<>();
private static final ConcurrentSkipListSet<NodeTransaction> MOST_RECENTLY_ACCESSED = new ConcurrentSkipListSet<>();
private static final AtomicLong MAX_CACHE_ENTRIES = new AtomicLong(50); // # of entries in cache
private static final AtomicLong UPDATE_INTERVAL = new AtomicLong(10); // Update interval in seconds
private static final double CACHE_REDUCTION_FACTOR = 0.2; // Amount to reduce cache when purging
private static final AtomicBoolean ENABLED = new AtomicBoolean(false);
private static final long nanoInSeconds = 1000000000;
/**
* This is a singleton class and as such all methods are static and the constructor is private because an
* instance should never be created.
*/
private BesNodeCache(){}
/**
* Initialize the Node Cache using an XML Element.
* @param config The "NodeCache" configuration element
* @throws BadConfigurationException When the configuration is broken.
*/
public static void init(Element config) throws BadConfigurationException {
if (config == null || !config.getName().equals(NODE_CACHE_ELEMENT_NAME))
throw new BadConfigurationException("BesNodeCache must be passed a non-null configuration " +
"element named " + NODE_CACHE_ELEMENT_NAME);
long maxEntries = NODE_CACHE_MAX_ENTRIES_DEFAULT;
String maxEntriesString = config.getAttributeValue(MAX_ENTRIES_ATTRIBUTE_NAME);
if(maxEntriesString!=null) {
try {
maxEntries = Long.parseLong(maxEntriesString);
if (maxEntries <= 0) {
maxEntries = NODE_CACHE_MAX_ENTRIES_DEFAULT;
String msg = "Failed to parse value of " +
NODE_CACHE_ELEMENT_NAME + "@" + MAX_ENTRIES_ATTRIBUTE_NAME + "! " +
"Value must be an integer > 0. Using default value: " + maxEntries;
LOG.error(msg);
}
} catch (NumberFormatException nfe) {
LOG.error("Failed to parse value of NodeCache@maxEntries! Value must" +
" be an integer. Using default value: {}", maxEntries);
}
}
long refreshInterval = NODE_CACHE_REFRESH_INTERVAL_DEFAULT;
String refreshIntervalString = config.getAttributeValue(REFRESH_INTERVAL_ATTRIBUTE_NAME);
if(refreshIntervalString != null) {
try {
refreshInterval = Long.parseLong(refreshIntervalString);
if (refreshInterval <= 0) {
refreshInterval = NODE_CACHE_REFRESH_INTERVAL_DEFAULT;
String msg = "Failed to parse value of " +
NODE_CACHE_ELEMENT_NAME + "@" +
REFRESH_INTERVAL_ATTRIBUTE_NAME + "! " +
"Value must be an integer > 0. Using default value: " +
refreshInterval;
LOG.error(msg);
}
} catch (NumberFormatException nfe) {
LOG.error("Failed to parse value of NodeCache@refreshInterval! Value" +
" must be an integer. Using default value: {}", refreshInterval);
}
}
init(maxEntries, refreshInterval);
}
/**
* The _actual_ init method that sets up the cache. This must be called
* prior to using the cache.
* @param maxEntries The maximum number of entries in the cache
* @param updateIntervalSeconds The time any object may reside in the cache before it is removed.
*/
public static void init(long maxEntries, long updateIntervalSeconds) {
RWLOCK.writeLock().lock();
try {
if (ENABLED.get()) {
LOG.error("BesNodeCache has already been initialized! " +
"MAX_CACHE_ENTRIES: {} UPDATE_INTERVAL: {} s",
MAX_CACHE_ENTRIES.get(),
UPDATE_INTERVAL.get()/(nanoInSeconds*1.0));
return;
}
MAX_CACHE_ENTRIES.set(maxEntries);
UPDATE_INTERVAL.set(updateIntervalSeconds * nanoInSeconds);
ENABLED.set(true);
LOG.debug("INITIALIZED MAX_CACHE_ENTRIES: {} UPDATE_INTERVAL: {} s",
MAX_CACHE_ENTRIES.get(),
UPDATE_INTERVAL.get()/(nanoInSeconds*1.0));
}
finally {
RWLOCK.writeLock().unlock();
}
}
/**
* The primary public method used to retrieve BES showNode command responses. Caching happens within this call.
* @param key The name of the BES node to retrieve.
* @return The BES showNode response for "key"
*/
public static Element getNode(String key)
throws JDOMException,
BadConfigurationException,
PPTException,
IOException,
BESError {
if(!ENABLED.get()) {
init(NODE_CACHE_MAX_ENTRIES_DEFAULT,NODE_CACHE_REFRESH_INTERVAL_DEFAULT);
}
if(key==null)
throw new IOException("The BesApi.getNode() method was passed a key value of null. That's bad.");
RWLOCK.readLock().lock();
try {
LOG.debug("BEGIN NODE_CACHE.size(): {} MOST_RECENTLY_ACCESSED.size(): {}", NODE_CACHE.size(), MOST_RECENTLY_ACCESSED.size());
NodeTransaction nodeTransaction = NODE_CACHE.get(key);
if(isStaleNodeTransaction(nodeTransaction)){
RWLOCK.readLock().unlock();
RWLOCK.writeLock().lock();
try {
if (isStaleNodeTransaction(nodeTransaction)) {
dropStaleNodeTransaction(nodeTransaction);
LOG.debug("Dropping stale NodeTransaction[{}] from cache!",key);
nodeTransaction = getAndCacheNodeTransaction(key);
}
RWLOCK.readLock().lock();
}
finally {
RWLOCK.writeLock().unlock();
}
}
updateMostRecentlyAccessed(nodeTransaction);
// Now we need to sort out the response - Document or Error?
Object responseObject = nodeTransaction.getResponse();
if(responseObject instanceof Document){
Document cachedNodeDoc = (Document)responseObject;
Element root = cachedNodeDoc.getRootElement();
Element newRoot = (Element) root.clone();
newRoot.detach();
return newRoot;
}
if (responseObject instanceof BESError) {
LOG.info("Cache contains BESError object. dataSource=\"" +
key + "\"");
throw (BESError) responseObject;
}
// The responseObject should only ever be a Document or a BESError
throw new IOException("Cached object is of unexpected type! " +
"This is a bad thing! Object: "+responseObject.getClass().getCanonicalName());
}
finally {
LOG.debug("END NODE_CACHE.size(): {} MOST_RECENTLY_ACCESSED.size(): {}", NODE_CACHE.size(), MOST_RECENTLY_ACCESSED.size());
RWLOCK.readLock().unlock();
}
}
/**
* Solicits a showNode response from the BES for the passed parameter key. Once the response is received the response
* is used to make a new NodeTransaction which is then placed in the cache associated with the value of key.
* If the BES returns an error that is handled the same way, the error object is used to make a new NodeTransaction
* which is placed in the cache associated with the value of key.
* @param key The name of the node to retrieve from the BES using the showNode command.
* @return The NodeTransaction built from the BES response.
* @throws BadConfigurationException When a BES cannot be located.
* @throws PPTException When the PPT exchange between the BES process and the OLFS fails.
* @throws JDOMException When the documents cannot be parsed.
* @throws IOException When theings cannot be read or written.
*/
private static NodeTransaction getAndCacheNodeTransaction(String key) throws BadConfigurationException, PPTException, JDOMException, IOException {
BES bes = BesApi.getBES(key);
Document showNodeRequestDoc = BesApi.getShowNodeRequestDocument(key);
Document response = new Document();
NodeTransaction result;
try {
bes.besTransaction(showNodeRequestDoc, response);
// Get the root element.
Element root = response.getRootElement();
if (root == null)
throw new IOException("BES showNode response for " + key + " was empty! No root element");
Element showNode = root.getChild("showNode", opendap.namespaces.BES.BES_NS);
if (showNode == null)
throw new IOException("BES showNode response for " + key + " was malformed! No showNode element");
showNode.setAttribute("prefix", bes.getPrefix());
LOG.info("Caching copy of BES showNode response for key: \"{}\"",key);
result = putNodeTransaction(key, showNodeRequestDoc, response.clone());
} catch (BESError be) {
LOG.info("The BES returned a BESError for key: \"{} \" CACHING BESError",key);
result = putNodeTransaction(key, showNodeRequestDoc, be);
}
return result;
}
/**
* Check to see if the passed NodeTransaction is stale. This is based
* comparing its time in the cache with the UPDATE_INTERVAL.
*
* @param nodeTransaction The NodeTransaction to test.
* @return Returns true is the NodeTransaction has been in the cache longer
* the UPDATE_INTERVAL.
*/
private static boolean isStaleNodeTransaction(NodeTransaction nodeTransaction){
boolean isStale = true; // if it's null it's stale...
if(nodeTransaction!=null) {
long timeInCache = System.nanoTime() - nodeTransaction.getLastUpdateTime();
LOG.debug("nodeTransaction[{}] has been in cache {} s", nodeTransaction.getKey(), timeInCache / (nanoInSeconds * 1.0));
// Is it stale?
isStale = timeInCache > UPDATE_INTERVAL.get();
}
return isStale;
}
/**
* Removes the passed NodeTransaction from both the cache (NODE_CACHE) and
* from the most recently accessed list (MOST_RECENTLY_ACCESSED). If a null
* value is passed, nothing is done and the method returns.
*
* @param nodeTransaction The NodeTransaction to drop from the cache.
*/
private static void dropStaleNodeTransaction(NodeTransaction nodeTransaction){
if(nodeTransaction==null){
// a null value is a noop, but not an error
return;
}
NodeTransaction nt = NODE_CACHE.remove(nodeTransaction.getKey());
LOG.debug("Remove NodeTransaction[{}] from NODE_CACHE returned: {}",
nodeTransaction.getKey(), (nt == null) ? "NULL" : nt);
LOG.debug("NODE_CACHE.size(): {}", NODE_CACHE.size());
if (MOST_RECENTLY_ACCESSED.remove(nodeTransaction)) {
LOG.debug("Successfully dropped NodeTransaction[{}] from MOST_RECENTLY_ACCESSED (size: {})", nodeTransaction.getKey(), MOST_RECENTLY_ACCESSED.size());
} else {
LOG.error("FAILED to drop NodeTransaction[{}] from MOST_RECENTLY_ACCESSED (size: {})", nodeTransaction.getKey(), MOST_RECENTLY_ACCESSED.size());
}
}
/**
* Updates the MOST_RECENTLY_ACCESSED list by dropping the passed
* CatalogTransaction from the MOST_RECENTLY_ACCESSED list, updating
* the CatalogTransaction's access time and then adding the updated
* CatalogTransaction back to the MOST_RECENTLY_ACCESSED list.
* @param nodeTransaction The CatalogTransaction whose access time needs
* updating.
*/
private static void updateMostRecentlyAccessed(NodeTransaction nodeTransaction){
boolean status;
LOCK.lock();
try {
LOG.debug("Updating MOST_RECENTLY_ACCESSED list. MOST_RECENTLY_ACCESSED.size(): {}", MOST_RECENTLY_ACCESSED.size());
status = MOST_RECENTLY_ACCESSED.remove(nodeTransaction);
if(status) {
LOG.debug("Removed NodeTransaction[{},{}] from MOST_RECENTLY_ACCESSED", nodeTransaction.getKey(),nodeTransaction);
}
else {
LOG.debug("The NodeTransaction[{},{}] was not found in MOST_RECENTLY_ACCESSED", nodeTransaction.getKey(),nodeTransaction);
}
LOG.debug("MOST_RECENTLY_ACCESSED list updated. MOST_RECENTLY_ACCESSED.size(): {}", MOST_RECENTLY_ACCESSED.size());
nodeTransaction.updateAccessedTime();
status = MOST_RECENTLY_ACCESSED.add(nodeTransaction);
LOG.debug("{} NodeTransaction[{}] to MOST_RECENTLY_ACCESSED",status?"Added":"FAILED to add",nodeTransaction.getKey());
LOG.debug("MOST_RECENTLY_ACCESSED list updated. MOST_RECENTLY_ACCESSED.size(): {}", MOST_RECENTLY_ACCESSED.size());
}
finally {
LOCK.unlock();
}
}
/**
* Takes a node response (Document or BESError) and tucks it into the NodeCache
* @param key The name of the node that was retrieved.
* @param request The BES showNode request document used to elicit the response.
* @param response The object (either a Document or a BESError) returned by the BES transaction.
*/
private static NodeTransaction putNodeTransaction(String key, Document request, Object response) {
LOG.debug("BEGIN NODE_CACHE.size(): {} ", NODE_CACHE.size());
// Make sure the cache has not grown too large.
purgeLeastRecentlyAccessed();
NodeTransaction nodeTransaction = new NodeTransaction(key, request, response);
LOG.debug("Created nodeTransaction[{}] @ {}", key, nodeTransaction.getLastUpdateTime());
NodeTransaction previous = NODE_CACHE.put(key, nodeTransaction);
if (nodeTransaction == previous) {
LOG.warn("NodeTransaction cache updated with new (replacement) object for key: \"{}\"",key);
} else {
LOG.debug("NodeTransaction cache updated by adding new object to cache using key \"{}\"",key);
}
LOG.debug("END NODE_CACHE.size(): {}", NODE_CACHE.size());
return nodeTransaction;
}
/**
* If the cache is smaller than MAX_CACHE_ENTRIES then this is a no-op.
* If the cache has grown larger than MAX_CACHE_ENTRIES then it will be reduced by
* rsize = (CACHE_REDUCTION_FACTOR * MAX_CACHE_ENTRIES) entries. The reduction is done by iterating over the
* MOST_RECENTLY_ACCESSED list, from oldest (longest since accessed) to newest (least time since access) and
* collecting "rsize" NodeTransactions and removing them from both the NODE_CACHE and the MOST_RECENTLY_ACCESSED
* list.
*/
private static void purgeLeastRecentlyAccessed(){
// Cache not full? Then return...
if (NODE_CACHE.size() < MAX_CACHE_ENTRIES.get())
return;
int dropNum = (int) (MAX_CACHE_ENTRIES.get() * CACHE_REDUCTION_FACTOR);
if(dropNum==0) {
dropNum = 1;
}
LOG.debug("BEGIN NODE_CACHE.size(): {} MOST_RECENTLY_ACCESSED.size(): {}", NODE_CACHE.size(), MOST_RECENTLY_ACCESSED.size());
LOG.debug("dropNum: {}",dropNum);
LOG.debug("Before purge NODE_CACHE.size(): {}", NODE_CACHE.size());
LOG.debug("Before purge MOST_RECENTLY_ACCESSED.size(): {}", MOST_RECENTLY_ACCESSED.size());
List<NodeTransaction> purgeList = new ArrayList<>(dropNum);
Iterator<NodeTransaction> oldestToNewest = MOST_RECENTLY_ACCESSED.iterator();
for(int i=0; i<dropNum && oldestToNewest.hasNext(); i++ ){
NodeTransaction nodeTransaction = oldestToNewest.next();
purgeList.add(nodeTransaction);
LOG.debug("Purging CatalogTransaction for key {}",nodeTransaction.getKey());
NODE_CACHE.remove(nodeTransaction.getKey());
}
MOST_RECENTLY_ACCESSED.removeAll(purgeList);
LOG.debug("After purge NODE_CACHE.size(): {}", NODE_CACHE.size());
LOG.debug("After purge MOST_RECENTLY_ACCESSED.size(): {}", MOST_RECENTLY_ACCESSED.size());
LOG.debug("END");
}
/**
* Drops all references from the cache.
*/
public void destroy(){
RWLOCK.writeLock().lock();
try {
NODE_CACHE.clear();
MOST_RECENTLY_ACCESSED.clear();
}
finally {
RWLOCK.writeLock().unlock();
}
}
/**
* This is a test method used to make a NodeTransaction without requiring a
* running BES to receive a request and generate a response. THe point is
* to provide a test fixture to allow the evaluation of the
* NodeTransaction.comparable() interface for the purposes of sorting.
*
* @param id
* @return
*/
private static NodeTransaction getDummyCachedNodeTransaction(String id){
Document request;
Document response;
Element e;
request = new Document();
e=new Element("request");
e.setAttribute("id",id);
request.setRootElement(e);
response = new Document();
e= new Element("response");
e.setAttribute("id",id);
response.setRootElement(e);
return new NodeTransaction(id,request,response);
}
public static void main(String[] args) {
Logger log = LoggerFactory.getLogger(BesNodeCache.class);
TreeSet<NodeTransaction> set = new TreeSet<>();
String[] testKeys = {"foo", "bar", "moo", "soo", "bar", "baz"};
NodeTransaction nodeTransaction;
NodeTransaction first = null;
String msgFormat = "nodeTransaction - key: %s getLastAccessedTime(): %d set.size(): %d";
String msg;
for(String key: testKeys){
nodeTransaction = getDummyCachedNodeTransaction(key);
set.add(nodeTransaction);
msg = String.format(msgFormat,nodeTransaction.getKey(),nodeTransaction.getLastAccessedTime(),set.size());
log.info(msg);
if(first==null)
first = nodeTransaction;
}
log.info("Original List: ");
for(NodeTransaction nodeT: set){
log.info(" node[{}]: {}",nodeT.getKey(),nodeT.getLastAccessedTime());
}
set.remove(first);
first.updateAccessedTime();
set.add(first);
log.info("List after remove and replace: ");
for(NodeTransaction nodeT: set){
log.info(" node[{}]: {}",nodeT.getKey(),nodeT.getLastAccessedTime());
}
}
//
//
//
//
//
//
//
//
//
}
|
package ubic.basecode.dataStructure.params;
import java.util.List;
import java.util.Map;
import org.apache.poi.ss.formula.FormulaParser;
import ubic.basecode.io.excel.CreateSpreadSheet;
import ubic.basecode.io.excel.ExcelUtil;
import ubic.basecode.io.excel.SpreadSheetSchema;
/**
* A class to convert parametergrabber information/instances into excel speadsheet lines
*
* @author leon
*/
public class ParamSpreadSheet extends CreateSpreadSheet {
public ParamSpreadSheet( String filename, SpreadSheetSchema schema ) throws Exception {
super( filename, schema );
}
public void populate( List<Map<String, String>> paramLines ) {
int row = 0;
for ( Map<String, String> paramLine : paramLines ) {
row++;
for ( String key : paramLine.keySet() ) {
String value = paramLine.get( key );
int pos = schema.getPosition( key );
try {
double dValue = Double.parseDouble( value );
if ( Double.isNaN( dValue ) ) throw new NumberFormatException();
ExcelUtil.setValue( spreadsheet, row, pos, dValue );
} catch ( NumberFormatException e ) {
try {
ExcelUtil.setFormula( spreadsheet, row, pos, value );
// having trouble finding the exception to catch
} catch ( Exception xe ) {
ExcelUtil.setValue( spreadsheet, row, pos, value );
}
}
}
}
}
}
|
package com.dianping.cat;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.codehaus.plexus.logging.LogEnabled;
import org.codehaus.plexus.logging.Logger;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.Initializable;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.InitializationException;
import org.unidal.dal.jdbc.DalException;
import org.unidal.helper.Files;
import org.unidal.helper.Threads;
import org.unidal.helper.Threads.Task;
import org.unidal.lookup.annotation.Inject;
import org.unidal.webres.json.JsonArray;
import org.unidal.webres.json.JsonObject;
import com.dianping.cat.core.dal.Hostinfo;
import com.dianping.cat.core.dal.HostinfoDao;
import com.dianping.cat.core.dal.HostinfoEntity;
import com.dianping.cat.core.dal.Project;
import com.dianping.cat.core.dal.ProjectDao;
import com.dianping.cat.core.dal.ProjectEntity;
public class DomainManager implements Initializable, LogEnabled {
@Inject
private HostinfoDao m_hostInfoDao;
@Inject
private ProjectDao m_projectDao;
@Inject
private ServerConfigManager m_manager;
private Map<String, String> m_ipDomains = new ConcurrentHashMap<String, String>();
private Map<String, String> m_unknownIps = new ConcurrentHashMap<String, String>();
private Map<String, String> m_cmdbs = new ConcurrentHashMap<String, String>();
private Set<String> m_domainsInCat = new HashSet<String>();
private Map<String, Hostinfo> m_ipsInCat = new ConcurrentHashMap<String, Hostinfo>();
private Logger m_logger;
private static final String UNKNOWN_IP = "UnknownIp";
private static final String UNKNOWN_PROJECT = "UnknownProject";
private static final String CMDB_URL = "http://cmdb.dp/cmdb/device/s?q=%s&fl=app&tidy=true";
private static final long DURATION = 60 * 60 * 1000L;
public boolean containsDomainInCat(String domain) {
return m_domainsInCat.contains(domain);
}
@Override
public void enableLogging(Logger logger) {
m_logger = logger;
}
@Override
public void initialize() throws InitializationException {
if (!m_manager.isLocalMode()) {
try {
m_ipDomains.put(UNKNOWN_IP, UNKNOWN_PROJECT);
List<Hostinfo> infos = m_hostInfoDao.findAllIp(HostinfoEntity.READSET_FULL);
for (Hostinfo info : infos) {
m_ipDomains.put(info.getIp(), info.getDomain());
m_ipsInCat.put(info.getIp(), info);
}
List<Project> projects = m_projectDao.findAll(ProjectEntity.READSET_FULL);
for (Project project : projects) {
m_domainsInCat.add(project.getDomain());
}
} catch (DalException e) {
Cat.logError(e);
}
Threads.forGroup("Cat").start(new ReloadDomainTask());
Threads.forGroup("Cat").start(new UploadHostinfoDBTask());
}
}
public boolean insert(String domain, String ip) {
try {
Hostinfo info = m_hostInfoDao.createLocal();
info.setDomain(domain);
info.setIp(ip);
m_hostInfoDao.insert(info);
m_domainsInCat.add(domain);
m_ipsInCat.put(ip, info);
return true;
} catch (DalException e) {
Cat.logError(e);
}
return false;
}
public boolean insertDomain(String domain) {
Project project = m_projectDao.createLocal();
project.setDomain(domain);
project.setProjectLine("Default");
project.setDepartment("Default");
try {
m_projectDao.insert(project);
m_domainsInCat.add(domain);
return true;
} catch (Exception ex) {
Cat.logError(ex);
}
return false;
}
public String queryDomainByIp(String ip) {
String project = m_ipDomains.get(ip);
if (project == null) {
project = m_cmdbs.get(ip);
if (project == null) {
if (!m_unknownIps.containsKey(ip)) {
m_unknownIps.put(ip, ip);
}
return UNKNOWN_PROJECT;
}
}
return project;
}
public Hostinfo queryHostInfoByIp(String ip) {
return m_ipsInCat.get(ip);
}
public String queryHostnameByIp(String ip) {
String hostname = null;
try {
hostname = m_hostInfoDao.findByIp(ip, HostinfoEntity.READSET_FULL).getHostname();
} catch (DalException e) {
Cat.logError(e);
}
return hostname;
}
public boolean update(int id, String domain, String ip) {
try {
Hostinfo info = m_hostInfoDao.createLocal();
info.setId(id);
info.setDomain(domain);
info.setIp(ip);
info.setLastModifiedDate(new Date());
m_hostInfoDao.updateByPK(info, HostinfoEntity.UPDATESET_FULL);
m_domainsInCat.add(domain);
m_ipsInCat.put(ip, info);
return true;
} catch (DalException e) {
Cat.logError(e);
}
return false;
}
public class ReloadDomainTask implements Task {
private int m_count;
@Override
public String getName() {
return "Reload-CMDB-Ip-Domain-Info";
}
public String parseIp(String content) throws Exception {
JsonObject object = new JsonObject(content);
JsonArray array = object.getJSONArray("app");
if (array.length() > 0) {
return array.getString(0);
}
return null;
}
private void queryFromCMDB() {
Set<String> addedIps = new HashSet<String>();
for (String ip : m_unknownIps.keySet()) {
try {
String cmdb = String.format(CMDB_URL, ip);
URL url = new URL(cmdb);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
int nRc = conn.getResponseCode();
if (nRc == HttpURLConnection.HTTP_OK) {
InputStream input = conn.getInputStream();
String content = Files.forIO().readFrom(input, "utf-8");
String domain = parseIp(content.trim());
if (domain != null) {
m_cmdbs.put(ip, domain);
addedIps.add(ip);
}
}
} catch (Exception e) {
Cat.logError(e);
}
for (String temp : addedIps) {
m_unknownIps.remove(temp);
}
}
}
private void queryFromDatabase() {
Set<String> addIps = new HashSet<String>();
for (String ip : m_unknownIps.keySet()) {
try {
Hostinfo hostinfo = m_hostInfoDao.findByIp(ip, HostinfoEntity.READSET_FULL);
addIps.add(hostinfo.getIp());
m_ipDomains.put(hostinfo.getIp(), hostinfo.getDomain());
m_domainsInCat.add(hostinfo.getDomain());
} catch (Exception e) {
// ignore
}
}
for (String ip : addIps) {
m_unknownIps.remove(ip);
}
}
@Override
public void run() {
boolean active = true;
while (active) {
try {
m_count++;
queryFromDatabase();
queryFromCMDB();
if (m_count % 1000 == 0 && m_unknownIps.size() > 0) {
m_logger.error(String.format("can't get domain info from cmdb, ip: %s", m_unknownIps.keySet()
.toString()));
}
} catch (Throwable e) {
Cat.logError(e);
}
try {
Thread.sleep(2 * 60 * 1000);
} catch (InterruptedException e) {
active = false;
}
}
}
@Override
public void shutdown() {
}
}
public class UploadHostinfoDBTask implements Task {
private static final String CMDB_HOSTNAME_URL = "http://cmdb.dp/cmdb/device/s?q=%s&fl=hostname&tidy=true";
@Override
public String getName() {
return "update_hostinfo_db";
}
public String parseHostname(String content) throws Exception {
JsonObject object = new JsonObject(content);
JsonArray array = object.getJSONArray("hostname");
if (array.length() > 0) {
return array.getString(0);
}
return null;
}
private String queryHostnameFromCMDB(String ip) {
String hostname = null;
try {
String cmdb = String.format(CMDB_HOSTNAME_URL, ip);
URL url = new URL(cmdb);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
int nRc = conn.getResponseCode();
if (nRc == HttpURLConnection.HTTP_OK) {
InputStream input = conn.getInputStream();
String content = Files.forIO().readFrom(input, "utf-8");
hostname = parseHostname(content.trim());
}
} catch (Exception e) {
Cat.logError(e);
}
return hostname;
}
@Override
public void run() {
boolean active = true;
while (active) {
long startMill = System.currentTimeMillis();
try {
List<Hostinfo> infos = m_hostInfoDao.findAllIp(HostinfoEntity.READSET_FULL);
for(Hostinfo info : infos){
String hostname = info.getHostname();
if(info.getHostname() == null || "".equals(hostname)){
String ip = info.getIp();
String cmdbHostname = queryHostnameFromCMDB(ip);
if(cmdbHostname != null){
info.setHostname(cmdbHostname);
m_hostInfoDao.updateByPK(info, HostinfoEntity.UPDATESET_FULL);
}else{
m_logger.error("cant find hostname for ip: " + ip);
}
}
}
} catch (Throwable e) {
Cat.logError(e);
}
try {
long executeMills = System.currentTimeMillis() - startMill;
if(executeMills < DURATION){
Thread.sleep(DURATION - executeMills);
}
} catch (InterruptedException e) {
active = false;
}
}
}
@Override
public void shutdown() {
}
}
}
|
package ucar.nc2.iosp.hdf5;
import com.google.common.primitives.Ints;
import com.google.common.primitives.Longs;
import ucar.ma2.DataType;
import ucar.ma2.InvalidRangeException;
import ucar.ma2.Section;
import ucar.nc2.Variable;
import ucar.nc2.iosp.LayoutBB;
import ucar.nc2.iosp.LayoutBBTiled;
import ucar.nc2.util.IO;
import ucar.unidata.io.RandomAccessFile;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
/**
* Iterator to read/write subsets of an array.
* This calculates byte offsets for HD5 chunked datasets.
* Assumes that the data is stored in chunks, indexed by a Btree.
* for filtered data
*
* @author caron
*/
class H5tiledLayoutBB implements LayoutBB {
static final int DEFAULTZIPBUFFERSIZE = 512;
// System property name for -D flag
static final String INFLATEBUFFERSIZE = "unidata.h5iosp.inflate.buffersize";
static public boolean debugFilter = false;
private LayoutBBTiled delegate;
private RandomAccessFile raf;
private H5header.Filter[] filters;
private ByteOrder byteOrder;
private Section want;
private int[] chunkSize; // from the StorageLayout message (exclude the elemSize)
private int elemSize; // last dimension of the StorageLayout message
private int nChunkDims;
private boolean debug = false;
private int inflatebuffersize = DEFAULTZIPBUFFERSIZE;
/**
* Constructor.
* This is for HDF5 chunked data storage. The data is read by chunk, for efficency.
*
* @param v2 Variable to index over; assumes that vinfo is the data object
* @param wantSection the wanted section of data, contains a List of Range objects. must be complete
* @param raf the RandomAccessFile
* @param filters set of filters that have been applied to the data
* @throws InvalidRangeException if section invalid for this variable
* @throws java.io.IOException on io error
*/
H5tiledLayoutBB(Variable v2, Section wantSection, RandomAccessFile raf, H5header.Filter[] filters, ByteOrder byteOrder) throws InvalidRangeException, IOException
{
wantSection = Section.fill(wantSection, v2.getShape());
H5header.Vinfo vinfo = (H5header.Vinfo) v2.getSPobject();
assert vinfo.isChunked;
assert vinfo.btree != null;
this.raf = raf;
this.filters = filters;
this.byteOrder = byteOrder;
// we have to translate the want section into the same rank as the storageSize, in order to be able to call
// Section.intersect(). It appears that storageSize (actually msl.chunkSize) may have an extra dimension, reletive
// to the Variable.
DataType dtype = v2.getDataType();
if((dtype == DataType.CHAR) && (wantSection.getRank() < vinfo.storageSize.length))
this.want = new Section(wantSection).appendRange(1);
else
this.want = wantSection;
// one less chunk dimension, except in the case of char
nChunkDims = (dtype == DataType.CHAR) ? vinfo.storageSize.length : vinfo.storageSize.length - 1;
this.chunkSize = new int[nChunkDims];
System.arraycopy(vinfo.storageSize, 0, chunkSize, 0, nChunkDims);
this.elemSize = vinfo.storageSize[vinfo.storageSize.length - 1]; // last one is always the elements size
// create the data chunk iterator
DataBTree.DataChunkIterator iter = vinfo.btree.getDataChunkIteratorFilter(this.want);
DataChunkIterator dcIter = new DataChunkIterator(iter);
delegate = new LayoutBBTiled(dcIter, chunkSize, elemSize, this.want);
if(System.getProperty(INFLATEBUFFERSIZE) != null) {
try {
int size = Integer.parseInt(System.getProperty(INFLATEBUFFERSIZE));
if(size <= 0)
H5iosp.log.warn(String.format("-D%s must be > 0",INFLATEBUFFERSIZE));
else
this.inflatebuffersize = size;
} catch (NumberFormatException nfe) {
H5iosp.log.warn(String.format("-D%s is not an integer",INFLATEBUFFERSIZE));
}
}
if(debugFilter)
System.out.printf("inflate buffer size -D%s = %d%n",INFLATEBUFFERSIZE,this.inflatebuffersize);
if (debug) System.out.println(" H5tiledLayout: " + this);
}
public long getTotalNelems() {
return delegate.getTotalNelems();
}
public int getElemSize() {
return delegate.getElemSize();
}
public boolean hasNext() {
return delegate.hasNext();
}
public Chunk next() throws IOException {
return delegate.next();
}
public String toString() {
StringBuilder sbuff = new StringBuilder();
sbuff.append("want=").append(want).append("; ");
sbuff.append("chunkSize=[");
for (int i = 0; i < chunkSize.length; i++) {
if (i > 0) sbuff.append(",");
sbuff.append(chunkSize[i]);
}
sbuff.append("] totalNelems=").append(getTotalNelems());
sbuff.append(" elemSize=").append(elemSize);
return sbuff.toString();
}
private class DataChunkIterator implements LayoutBBTiled.DataChunkIterator {
DataBTree.DataChunkIterator delegate;
DataChunkIterator(DataBTree.DataChunkIterator delegate) {
this.delegate = delegate;
}
public boolean hasNext() {
return delegate.hasNext();
}
public LayoutBBTiled.DataChunk next() throws IOException {
return new DataChunk(delegate.next());
}
}
private class DataChunk implements ucar.nc2.iosp.LayoutBBTiled.DataChunk {
// Copied from ArrayList.
private static final int MAX_ARRAY_LEN = Integer.MAX_VALUE - 8;
DataBTree.DataChunk delegate;
DataChunk(DataBTree.DataChunk delegate) {
this.delegate = delegate;
// Check that the chunk length (delegate.size) isn't greater than the maximum array length that we can
// allocate (MAX_ARRAY_LEN). This condition manifests in two ways.
// max chunk length is 4GB (i.e. representable in an unsigned int). Java, however, only has signed ints.
// So, if we try to store a large unsigned int in a singed int, it'll overflow, and the signed int will come
// out negative. We're trusting here that the chunk size read from the HDF file is never negative.
// 2) In most JVM implementations MAX_ARRAY_LEN is actually less than Integer.MAX_VALUE (see note in ArrayList).
// So, we could have: "MAX_ARRAY_LEN < chunkSize <= Integer.MAX_VALUE".
if (delegate.size < 0 || delegate.size > MAX_ARRAY_LEN) {
// We want to report the size of the chunk, but we may be in an arithmetic overflow situation. So to get the
// correct value, we're going to reinterpet the integer's bytes as long bytes.
byte[] intBytes = Ints.toByteArray(delegate.size);
byte[] longBytes = new byte[8];
System.arraycopy(intBytes, 0, longBytes, 4, 4); // Copy int bytes to the lowest 4 positions.
long chunkSize = Longs.fromByteArray(longBytes); // Method requires an array of length 8.
throw new IllegalArgumentException(String.format("Filtered data chunk is %s bytes and we must load it all " +
"into memory. However the maximum length of a byte array in Java is %s.", chunkSize, MAX_ARRAY_LEN));
}
}
public int[] getOffset() {
int[] offset = delegate.offset;
if (offset.length > nChunkDims) { // may have to eliminate last offset
offset = new int[nChunkDims];
System.arraycopy(delegate.offset, 0, offset, 0, nChunkDims);
}
return offset;
}
public ByteBuffer getByteBuffer() throws IOException {
try {
// read the data
byte[] data = new byte[delegate.size];
raf.seek(delegate.filePos);
raf.readFully(data);
// apply filters backwards
for (int i = filters.length - 1; i >= 0; i
H5header.Filter f = filters[i];
if (isBitSet(delegate.filterMask, i)) {
if (debug) System.out.println("skip for chunk " + delegate);
continue;
}
if (f.id == 1) {
data = inflate(data);
} else if (f.id == 2) {
data = shuffle(data, f.data[0]);
} else if (f.id == 3) {
data = checkfletcher32(data);
} else
throw new RuntimeException("Unknown filter type="+f.id);
}
ByteBuffer result = ByteBuffer.wrap(data);
result.order(byteOrder);
return result;
} catch (OutOfMemoryError e) {
Error oom = new OutOfMemoryError("Ran out of memory trying to read HDF5 filtered chunk. Either increase the " +
"JVM's heap size (use the -Xmx switch) or reduce the size of the dataset's chunks (use nccopy -c).");
oom.initCause(e); // OutOfMemoryError lacks a constructor with a cause parameter.
throw oom;
}
}
/**
* inflate data
*
* @param compressed compressed data
* @return uncompressed data
* @throws IOException on I/O error
*/
private byte[] inflate(byte[] compressed) throws IOException {
// run it through the Inflator
ByteArrayInputStream in = new ByteArrayInputStream(compressed);
java.util.zip.Inflater inflater = new java.util.zip.Inflater();
java.util.zip.InflaterInputStream inflatestream
= new java.util.zip.InflaterInputStream(in, inflater, inflatebuffersize);
int len = Math.min(8 * compressed.length, MAX_ARRAY_LEN);
ByteArrayOutputStream out = new ByteArrayOutputStream(len); // Fixes KXL-349288
IO.copyB(inflatestream, out, len);
byte[] uncomp = out.toByteArray();
if (debug || debugFilter)
System.out.println(" inflate bytes in= " + compressed.length + " bytes out= " + uncomp.length);
return uncomp;
}
// just strip off the 4-byte fletcher32 checksum at the end
private byte[] checkfletcher32(byte[] org) throws IOException {
byte[] result = new byte[org.length-4];
System.arraycopy(org, 0, result, 0, result.length);
if (debug) System.out.println(" checkfletcher32 bytes in= " + org.length + " bytes out= " + result.length);
return result;
}
private byte[] shuffle(byte[] data, int n) throws IOException {
if (debug) System.out.println(" shuffle bytes in= " + data.length + " n= " + n);
assert data.length % n == 0;
if (n <= 1) return data;
int m = data.length / n;
int[] count = new int[n];
for (int k = 0; k < n; k++) count[k] = k * m;
byte[] result = new byte[data.length];
/* for (int i = 0; i < data.length; i += n) {
for (int k = 0; k < n; k++) {
result[count[k]++] = data[i + k];
}
} */
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
result[i*n+j] = data[i + count[j]];
}
}
return result;
}
boolean isBitSet(int val, int bitno) {
return ((val >>> bitno) & 1) != 0;
}
}
}
|
package com.thaiopensource.xml.out;
import java.io.UnsupportedEncodingException;
public class CharRepertoire {
private final byte[] allUnknown = new byte[256];
private final byte[][] charTable = new byte[256][];
private static final byte UNKNOWN = 0;
private static final byte IN = 1;
private static final byte OUT = -1;
private final String enc;
CharRepertoire(String enc) {
this.enc = enc;
for (int i = 0; i < charTable.length; i++)
charTable[i] = allUnknown;
}
public static CharRepertoire getInstance(String enc)
throws UnsupportedEncodingException {
"x".getBytes(enc); // check whether encoding supported
return new CharRepertoire(enc);
}
public final boolean contains(char c) {
byte b = charTable[c >> 8][c & 0xFF];
return b == 0 ? contains1(c) : b > 0;
}
private boolean contains1(char c) {
int i = c >> 8;
if (charTable[i] == allUnknown)
charTable[i] = new byte[256];
if (contains2(c)) {
charTable[i][c & 0xFF] = IN;
return true;
}
else {
charTable[i][c & 0xFF] = OUT;
return false;
}
}
private boolean contains2(char c) {
try {
String s = new String(new String(new char[]{ c }).getBytes(enc), enc);
return s.length() == 1 && s.charAt(0) == c;
}
catch (UnsupportedEncodingException e) {
return false;
}
}
/* For surrogates. */
public final boolean contains(char c1, char c2) {
try {
String s = new String(new String(new char[]{c1, c2}).getBytes(enc), enc);
return s.length() == 2 && s.charAt(0) == c1 && s.charAt(1) == c2;
}
catch (UnsupportedEncodingException e) {
return false;
}
// work around gcj bug (libgcj/9802)
catch (RuntimeException e) {
return false;
}
}
}
|
package ucar.nc2.ft.point.writer;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import ucar.ma2.DataType;
import ucar.nc2.Attribute;
import ucar.nc2.Dimension;
import ucar.nc2.VariableSimpleIF;
import ucar.nc2.constants.CDM;
import ucar.nc2.constants.FeatureType;
import ucar.nc2.ft.*;
import ucar.nc2.ncml.NcMLReader;
import ucar.nc2.ncml.NcMLWriter;
import ucar.nc2.time.CalendarDate;
import ucar.nc2.time.CalendarDateFormatter;
import ucar.nc2.time.CalendarDateRange;
import ucar.nc2.units.DateUnit;
import ucar.unidata.geoloc.LatLonPointImpl;
import ucar.unidata.geoloc.LatLonRect;
import ucar.unidata.geoloc.Station;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;
/**
* generate capabilities XML for a FeatureDatasetPoint / StationTimeSeriesFeatureCollection
*
* @author caron
* @since Aug 19, 2009
*/
public class FeatureDatasetPointXML {
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(FeatureDatasetPointXML.class);
private FeatureDatasetPoint fdp;
private String path;
//private PointFeatureCollection pfc;
//private NestedPointFeatureCollection pfc;
public FeatureDatasetPointXML(FeatureDatasetPoint fdp, String path) {
this.fdp = fdp;
this.path = path;
}
public String getCapabilities() {
XMLOutputter fmt = new XMLOutputter(Format.getPrettyFormat());
return fmt.outputString(getCapabilitiesDocument());
}
public void getCapabilities(OutputStream os) throws IOException {
XMLOutputter fmt = new XMLOutputter(Format.getPrettyFormat());
fmt.output(getCapabilitiesDocument(), os);
}
/*
* Write stationCollection XML document
*
public String writeStationCollectionXML(LatLonRect bb, String[] names) throws IOException {
XMLOutputter fmt = new XMLOutputter(Format.getPrettyFormat());
return fmt.outputString(makeStationCollectionDocument(bb, names));
}
public void writeStationCollectionXML(OutputStream os) throws IOException {
XMLOutputter fmt = new XMLOutputter(Format.getPrettyFormat());
fmt.output(makeStationCollectionDocument(), os);
} */
/**
* Create an XML document for the stations in this dataset.
*
* @param bb restrict stations to this bounding box, may be null
* @param names restrict stations to these names, may be null
* @return XML document for the stations
* @throws IOException on read error
*/
public Document makeStationCollectionDocument(LatLonRect bb, String[] names) throws IOException {
List<FeatureCollection> list = fdp.getPointFeatureCollectionList();
FeatureCollection fc = list.get(0);
if (!(fc instanceof StationTimeSeriesFeatureCollection)) {
throw new UnsupportedOperationException(fc.getClass().getName() + " not a StationTimeSeriesFeatureCollection");
}
StationTimeSeriesFeatureCollection sobs = (StationTimeSeriesFeatureCollection) fc;
Element rootElem = new Element("stationCollection");
Document doc = new Document(rootElem);
List<Station> stations;
if (bb != null)
stations = sobs.getStations(bb);
else if (names != null)
stations = sobs.getStations(Arrays.asList(names));
else
stations = sobs.getStations();
for (Station s : stations) {
Element sElem = new Element("station");
sElem.setAttribute("name", s.getName());
if (s.getWmoId() != null)
sElem.setAttribute("wmo_id", s.getWmoId());
if ((s.getDescription() != null) && (s.getDescription().length() > 0))
sElem.addContent(new Element("description").addContent(s.getDescription()));
sElem.addContent(new Element("longitude").addContent(Double.toString(s.getLongitude())));
sElem.addContent(new Element("latitide").addContent(Double.toString(s.getLatitude())));
if (!Double.isNaN(s.getAltitude()))
sElem.addContent(new Element("altitude").addContent(Double.toString(s.getAltitude())));
rootElem.addContent(sElem);
}
return doc;
}
/**
* Create the capabilities XML document for this datasets
*
* @return capabilities XML document
*/
public Document getCapabilitiesDocument() {
Element rootElem = new Element("capabilities");
Document doc = new Document(rootElem);
if (null != path) {
rootElem.setAttribute("location", path);
Element elem = new Element("featureDataset");
FeatureType ft = fdp.getFeatureType();
elem.setAttribute("type", ft.toString().toLowerCase());
String url = path.replace("dataset.xml", ft.toString().toLowerCase() + ".xml");
elem.setAttribute("url", url);
rootElem.addContent(elem);
}
//rootElem.addContent(new Element("TimeUnit").addContent(fdp.getTimeUnit()));
//rootElem.addContent(new Element("AltitudeUnits").addContent(fdp.getAltUnits()));
// data variables
List<? extends VariableSimpleIF> vars = fdp.getDataVariables();
Collections.sort(vars);
for (VariableSimpleIF v : vars) {
rootElem.addContent(writeVariable(v));
}
// add lat/lon bounding box
try {
fdp.calcBounds();
} catch (IOException e) {
//e.printStackTrace();
log.warn("Unable to compute bounds for dataset " + fdp.getTitle(), e);
}
LatLonRect bb = fdp.getBoundingBox();
if (bb != null)
rootElem.addContent(writeBoundingBox(bb));
// add date range
CalendarDateRange dateRange = fdp.getCalendarDateRange();
if (dateRange != null) {
Element drElem = new Element("TimeSpan"); // from KML
drElem.addContent(new Element("begin").addContent(dateRange.getStart().toString()));
drElem.addContent(new Element("end").addContent(dateRange.getEnd().toString()));
if (dateRange.getResolution() != null)
drElem.addContent(new Element("resolution").addContent(dateRange.getResolution().toString()));
rootElem.addContent(drElem);
}
// add accept list
Element elem = new Element("AcceptList");
//elem.addContent(new Element("accept").addContent("raw"));
elem.addContent(new Element("accept").addContent("csv").setAttribute("displayName", "csv"));
elem.addContent(new Element("accept").addContent("text/csv").setAttribute("displayName", "csv (file)"));
elem.addContent(new Element("accept").addContent("xml").setAttribute("displayName", "xml"));
elem.addContent(new Element("accept").addContent("text/xml").setAttribute("displayName", "xml (file)"));
elem.addContent(new Element("accept").addContent("waterml2").setAttribute("displayName", "WaterML 2.0"));
elem.addContent(new Element("accept").addContent("netcdf").setAttribute("displayName", "CF/NetCDF-3"));
//elem.addContent(new Element("accept").addContent("ncstream"));
rootElem.addContent(elem);
return doc;
}
private Element writeBoundingBox(LatLonRect bb) {
int decToKeep = 6;
double bbExpand = Math.pow(10, -decToKeep);
// extend the bbox to make sure the implicit rounding does not result in a bbox that does not contain
// any points (can happen when you have a single station with very precise lat/lon values)
// This accounts for the implicit rounding errors that result from the use of
// ucar.unidata.util.Format.dfrac when writing out the lat/lon box on the NCSS for Points dataset.html
// page
LatLonPointImpl extendNorthEast = new LatLonPointImpl(bb.getLatMax() + bbExpand, bb.getLonMax() + bbExpand);
LatLonPointImpl extendSouthWest = new LatLonPointImpl(bb.getLatMin() - bbExpand, bb.getLonMin() - bbExpand);
bb.extend(extendNorthEast);
bb.extend(extendSouthWest);
Element bbElem = new Element("LatLonBox"); // from KML
bbElem.addContent(new Element("west").addContent(ucar.unidata.util.Format.dfrac(bb.getLonMin(), decToKeep)));
bbElem.addContent(new Element("east").addContent(ucar.unidata.util.Format.dfrac(bb.getLonMax(), decToKeep)));
bbElem.addContent(new Element("south").addContent(ucar.unidata.util.Format.dfrac(bb.getLatMin(), decToKeep)));
bbElem.addContent(new Element("north").addContent(ucar.unidata.util.Format.dfrac(bb.getLatMax(), decToKeep)));
return bbElem;
}
private Element writeVariable(VariableSimpleIF v) {
Element varElem = new Element("variable");
varElem.setAttribute("name", v.getShortName());
ucar.ma2.DataType dt = v.getDataType();
if (dt != null)
varElem.setAttribute("type", dt.toString());
// attributes
for (Attribute att : v.getAttributes()) {
varElem.addContent(NcMLWriter.writeAttribute(att, "attribute", null));
}
return varElem;
}
public static LatLonRect getSpatialExtent(Document doc) throws IOException {
Element root = doc.getRootElement();
Element latlonBox = root.getChild("LatLonBox");
if (latlonBox == null) return null;
String westS = latlonBox.getChildText("west");
String eastS = latlonBox.getChildText("east");
String northS = latlonBox.getChildText("north");
String southS = latlonBox.getChildText("south");
if ((westS == null) || (eastS == null) || (northS == null) || (southS == null)) return null;
try {
double west = Double.parseDouble(westS);
double east = Double.parseDouble(eastS);
double south = Double.parseDouble(southS);
double north = Double.parseDouble(northS);
return new LatLonRect(new LatLonPointImpl(south, east), new LatLonPointImpl(north, west));
} catch (Exception e) {
return null;
}
}
public static CalendarDateRange getTimeSpan(Document doc) throws IOException {
Element root = doc.getRootElement();
Element timeSpan = root.getChild("TimeSpan");
if (timeSpan == null) return null;
String beginS = timeSpan.getChildText("begin");
String endS = timeSpan.getChildText("end");
// String resS = timeSpan.getChildText("resolution");
if ((beginS == null) || (endS == null)) return null;
try {
CalendarDate start = CalendarDateFormatter.isoStringToCalendarDate(null, beginS);
CalendarDate end = CalendarDateFormatter.isoStringToCalendarDate(null, endS);
if ((start == null) || (end == null)) {
return null;
}
CalendarDateRange dr = CalendarDateRange.of(start, end);
// LOOK if (resS != null)
// dr.setResolution(new TimeDuration(resS));
return dr;
} catch (Exception e) {
return null;
}
}
public static DateUnit getTimeUnit(Document doc) throws IOException {
Element root = doc.getRootElement();
String timeUnitS = root.getChildText("TimeUnit");
if (timeUnitS == null) return null;
try {
return new DateUnit(timeUnitS);
} catch (Exception e) {
log.error("Illegal date unit {}", timeUnitS);
return null;
}
}
public static String getAltUnits(Document doc) throws IOException {
Element root = doc.getRootElement();
return root.getChildText("AltitudeUnits");
}
public static List<VariableSimpleIF> getDataVariables(Document doc) throws IOException {
Element root = doc.getRootElement();
List<VariableSimpleIF> dataVars = new ArrayList<>();
List<Element> varElems = root.getChildren("variable");
for (Element varElem : varElems) {
dataVars.add(new VariableSimple(varElem));
}
return dataVars;
}
private static class VariableSimple implements VariableSimpleIF {
String name, desc, units;
DataType dt;
List<Attribute> atts;
VariableSimple(Element velem) {
name = velem.getAttributeValue("name");
String type = velem.getAttributeValue("type");
dt = DataType.getType(type);
atts = new ArrayList<>();
List<Element> attElems = velem.getChildren("attribute");
for (Element attElem : attElems) {
String attName = attElem.getAttributeValue("name");
ucar.ma2.Array values = NcMLReader.readAttributeValues(attElem);
atts.add(new Attribute(attName, values));
}
for (Attribute att : atts) {
if (att.getShortName().equals(CDM.UNITS))
units = att.getStringValue();
if (att.getShortName().equals(CDM.LONG_NAME))
desc = att.getStringValue();
if ((desc == null) && att.getShortName().equals("description"))
desc = att.getStringValue();
if ((desc == null) && att.getShortName().equals("standard_name"))
desc = att.getStringValue();
}
}
@Override
public String getName() {
return name;
}
@Override
public String getFullName() {
return name;
}
@Override
public String getShortName() {
return name;
}
@Override
public String getDescription() {
return desc;
}
@Override
public String getUnitsString() {
return units;
}
@Override
public int getRank() {
return 0;
}
@Override
public int[] getShape() {
return new int[0];
}
@Override
public List<Dimension> getDimensions() {
return null;
}
@Override
public DataType getDataType() {
return dt;
}
@Override
public List<Attribute> getAttributes() {
return atts;
}
@Override
public Attribute findAttributeIgnoreCase(String name) {
for (Attribute att : atts) {
if (att.getShortName().equalsIgnoreCase(name))
return att;
}
return null;
}
@Override
public int compareTo(VariableSimpleIF o) {
return name.compareTo(o.getShortName());
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
VariableSimple that = (VariableSimple) o;
return name.equals(that.name);
}
@Override
public int hashCode() {
return name.hashCode();
}
}
public static void doOne(String location, String path, String result) throws IOException {
FeatureDataset fd = FeatureDatasetFactoryManager.open(FeatureType.ANY_POINT, location, null, new Formatter(System.out));
FeatureDatasetPointXML xml = new FeatureDatasetPointXML((FeatureDatasetPoint) fd, path);
xml.getCapabilities(System.out);
File f = new File(result);
FileOutputStream fos = new FileOutputStream(f);
xml.getCapabilities(fos);
fos.close();
System.out.printf("%s written%n", f.getPath());
}
// debug
public static void main(String args[]) throws IOException {
doOne("Q:/cdmUnitTest/ft/point/ship/nc/Surface_Buoy_20090920_0000.nc",
"http://thredds.ucar.edu/thredds/cdmremote/idd/buoy/collection",
"C:/tmp/pointCapabilities.xml"
);
/*
File f = new File("C:/TEMP/stationCollection.xml");
FileOutputStream fos = new FileOutputStream(f);
xml.writeStationCollectionXML(fos);
fos.close();
System.out.println(" size xml=" + f.length());
long s1 = f.length();
f = new File("C:/TEMP/stationCollection.xml.gzip");
fos = new FileOutputStream(f);
GZIPOutputStream zout = new GZIPOutputStream(fos);
xml.writeStationCollectionXML(zout);
zout.close();
double s2 = (double) f.length();
System.out.printf(" size xml zipped=%d ratio=%f%n", f.length(), s1/s2); */
}
}
|
package net.signalr.client;
/**
* Defines a connection handler.
*/
public interface ConnectionHandler {
/**
* Called when the connection is going to be connected.
*/
void onConnecting();
/**
* Called when the connection has been connected.
*/
void onConnected();
/**
* Called when the connection is going to be reconnected.
*/
void onReconnecting();
/**
* Called when the connection has been reconnected.
*/
void onReconnected();
/**
* Called when the connection is going to be disconnected.
*/
void onDisconnecting();
/**
* Called when the connection has been disconnected.
*/
void onDisconnected();
/**
* Called when the connection is slow.
*/
void onConnectionSlow();
/**
* Called when a message is going to be sent.
*
* @param message The message.
*/
void onSending(String message);
/**
* Called when a message has been received.
*
* @param message The message.
*/
void onReceived(String message);
/**
* Called when an error occurred.
*
* @param throwable The error.
*/
void onError(Throwable throwable);
}
|
package ch.elexis.core.data.lock;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import org.eclipse.core.runtime.IProgressMonitor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.eclipsesource.jaxrs.consumer.ConsumerFactory;
import ch.elexis.core.common.InstanceStatus;
import ch.elexis.core.common.InstanceStatus.STATE;
import ch.elexis.core.constants.Preferences;
import ch.elexis.core.data.activator.CoreHub;
import ch.elexis.core.data.constants.ElexisSystemPropertyConstants;
import ch.elexis.core.data.events.ElexisEvent;
import ch.elexis.core.data.events.ElexisEventDispatcher;
import ch.elexis.core.data.status.ElexisStatus;
import ch.elexis.core.lock.ILocalLockService;
import ch.elexis.core.lock.types.LockInfo;
import ch.elexis.core.lock.types.LockRequest;
import ch.elexis.core.lock.types.LockRequest.Type;
import ch.elexis.core.lock.types.LockResponse;
import ch.elexis.core.model.IPersistentObject;
import ch.elexis.core.server.IInstanceService;
import ch.elexis.core.server.ILockService;
import ch.elexis.data.PersistentObject;
import ch.elexis.data.User;
/**
* ILocalLockService implementation. Managing locks of PersistentObjects.</br>
* If the environment variable <b>ELEXIS_SERVER_REST_INTERFACE_URL</b> is set a connection to a
* remote LockService will used internal.
*
* @author marco
*
*/
public class LocalLockService implements ILocalLockService {
private ILockService ils;
private IInstanceService iis;
private InstanceStatus inst;
private final HashMap<String, Integer> lockCount = new HashMap<String, Integer>();
private final HashMap<String, LockInfo> locks = new HashMap<String, LockInfo>();
private boolean standalone = false;
private Logger logger = LoggerFactory.getLogger(LocalLockService.class);
/**
* A unique id for this instance of Elexis. Changes on every restart
*/
private static final UUID systemUuid = UUID.randomUUID();
private Timer timer;
/**
* Construct a new LocalLockService. Application code should access via
* {@link CoreHub#getLocalLockService()} and <b>NOT</b> create its own instance.
*
*/
public LocalLockService(){
ils = new DenyAllLockService();
timer = new Timer();
timer.schedule(new LockRefreshTask(), 10000, 10000);
inst = new InstanceStatus();
inst.setState(InstanceStatus.STATE.ACTIVE);
inst.setUuid(getSystemUuid());
inst.setVersion(CoreHub.readElexisBuildVersion());
inst.setOperatingSystem(
System.getProperty("os.name") + "/" + System.getProperty("os.version") + "/"
+ System.getProperty("os.arch") + "/J" + System.getProperty("java.version"));
}
public void reconfigure(){
final String restUrl =
System.getProperty(ElexisSystemPropertyConstants.ELEXIS_SERVER_REST_INTERFACE_URL);
if (restUrl != null && restUrl.length() > 0) {
standalone = false;
logger.info("Operating against elexis-server instance on " + restUrl);
ils = ConsumerFactory.createConsumer(restUrl, ILockService.class);
iis = ConsumerFactory.createConsumer(restUrl, IInstanceService.class);
String identId = CoreHub.localCfg.get(Preferences.STATION_IDENT_ID, "");
String identTxt = CoreHub.localCfg.get(Preferences.STATION_IDENT_TEXT, "");
inst.setIdentifier(identTxt + " [" + identId + "]");
} else {
standalone = true;
logger.info("Operating in stand-alone mode.");
}
}
@Override
public LockResponse releaseAllLocks(){
if (standalone) {
return LockResponse.OK;
}
List<LockInfo> lockList = new ArrayList<LockInfo>(locks.values());
for (LockInfo lockInfo : lockList) {
LockRequest lockRequest = new LockRequest(LockRequest.Type.RELEASE, lockInfo);
LockResponse lr = acquireOrReleaseLocks(lockRequest);
if (!lr.isOk()) {
return lr;
}
}
return LockResponse.OK;
}
@Override
public LockResponse releaseLock(IPersistentObject po){
if (po == null) {
return LockResponse.DENIED(null);
}
logger.debug("Releasing lock on [" + po + "]");
return releaseLock(po.storeToString());
}
@Override
public LockResponse releaseLock(LockInfo lockInfo){
if (lockInfo.getElementStoreToString() == null) {
return LockResponse.DENIED(null);
}
logger.debug("Releasing lock on [" + lockInfo.getElementStoreToString() + "]");
return releaseLock(lockInfo.getElementStoreToString());
}
private LockResponse releaseLock(String storeToString){
User user = (User) ElexisEventDispatcher.getSelected(User.class);
LockInfo lil = new LockInfo(storeToString, user.getId(), systemUuid.toString());
LockRequest lockRequest = new LockRequest(LockRequest.Type.RELEASE, lil);
return acquireOrReleaseLocks(lockRequest);
}
@Override
public LockResponse acquireLockBlocking(IPersistentObject po, int secTimeout,
IProgressMonitor monitor){
if (po == null) {
return LockResponse.DENIED(null);
}
if (monitor != null) {
monitor.beginTask("Acquiring Lock for [" + po.getLabel() + "]", (secTimeout * 10) + 1);
}
logger.debug("Acquiring lock blocking on [" + po + "]");
String storeToString = po.storeToString();
LockResponse response = acquireLock(storeToString);
int sleptMilli = 0;
while (!response.isOk()) {
if (response.getStatus() == LockResponse.Status.DENIED_PERMANENT) {
return response;
}
try {
Thread.sleep(100);
sleptMilli += 100;
response = acquireLock(storeToString);
if (sleptMilli > (secTimeout * 1000)) {
return response;
}
// update monitor
if (monitor != null) {
monitor.worked(1);
if (monitor.isCanceled()) {
return LockResponse.DENIED(response.getLockInfo());
}
}
} catch (InterruptedException e) {
// ignore and keep trying
}
}
return response;
}
@Override
public LockResponse acquireLock(IPersistentObject po){
if (po == null) {
return LockResponse.DENIED(null);
}
logger.debug("Acquiring lock on [" + po + "]");
LockResponse lr = acquireLock(po.storeToString());
if (lr.getStatus() == LockResponse.Status.ERROR) {
logger.warn("LockResponse ERROR");
}
return lr;
}
private LockResponse acquireLock(String storeToString){
if (storeToString == null) {
return LockResponse.DENIED(null);
}
User user = (User) ElexisEventDispatcher.getSelected(User.class);
LockInfo lockInfo = new LockInfo(storeToString, user.getId(), systemUuid.toString());
LockRequest lockRequest = new LockRequest(LockRequest.Type.ACQUIRE, lockInfo);
return acquireOrReleaseLocks(lockRequest);
}
@Override
public LockResponse acquireOrReleaseLocks(LockRequest lockRequest){
if (standalone) {
return LockResponse.OK(lockRequest.getLockInfo());
}
if (ils == null) {
String message =
"System not configured for standalone mode, and elexis-server not available!";
logger.error(message);
ElexisEventDispatcher
.fireElexisStatusEvent(new ElexisStatus(org.eclipse.core.runtime.Status.ERROR,
CoreHub.PLUGIN_ID, ElexisStatus.CODE_NONE, message, null));
return new LockResponse(LockResponse.Status.ERROR, lockRequest.getLockInfo());
}
LockInfo lockInfo = lockRequest.getLockInfo();
synchronized (locks) {
// does the requested lock match the cache on our side?
if (LockRequest.Type.ACQUIRE == lockRequest.getRequestType()
&& locks.keySet().contains(lockInfo.getElementId())) {
incrementLockCount(lockInfo);
return LockResponse.OK(lockRequest.getLockInfo());
}
// do not release lock if it was locked multiple times
if (LockRequest.Type.RELEASE == lockRequest.getRequestType()
&& getCurrentLockCount(lockInfo) > 1) {
decrementLockCount(lockInfo);
return LockResponse.OK(lockRequest.getLockInfo());
}
// TODO should we release all locks on acquiring a new one?
// if yes, this has to be dependent upon the strategy
try {
if (LockRequest.Type.RELEASE == lockRequest.getRequestType()) {
PersistentObject po =
CoreHub.poFactory.createFromString(lockInfo.getElementStoreToString());
if (po != null) {
ElexisEventDispatcher.getInstance().fire(new ElexisEvent(po, po.getClass(),
ElexisEvent.EVENT_LOCK_PRERELEASE, ElexisEvent.PRIORITY_SYNC));
}
}
LockResponse lr = ils.acquireOrReleaseLocks(lockRequest);
if (!lr.isOk()) {
return lr;
}
if (LockRequest.Type.ACQUIRE == lockRequest.getRequestType()) {
// ACQUIRE ACTIONS
// lock is granted only if we have non-exception on acquire
locks.put(lockInfo.getElementId(), lockInfo);
incrementLockCount(lockInfo);
PersistentObject po =
CoreHub.poFactory.createFromString(lockInfo.getElementStoreToString());
if (po != null) {
ElexisEventDispatcher.getInstance().fire(
new ElexisEvent(po, po.getClass(), ElexisEvent.EVENT_LOCK_AQUIRED));
}
}
return lr;
} catch (Exception e) {
// if we have an exception here, our lock copies never get
// deleted!!!
String message = "Error trying to acquireOrReleaseLocks.";
logger.error(message);
ElexisEventDispatcher
.fireElexisStatusEvent(new ElexisStatus(org.eclipse.core.runtime.Status.ERROR,
CoreHub.PLUGIN_ID, ElexisStatus.CODE_NONE, message, e));
return new LockResponse(LockResponse.Status.ERROR, lockRequest.getLockInfo());
} finally {
if (LockRequest.Type.RELEASE.equals(lockRequest.getRequestType())) {
// RELEASE ACTIONS
// releases are also to be performed on occurence of an
// exception
decrementLockCount(lockInfo);
locks.remove(lockInfo.getElementId());
PersistentObject po =
CoreHub.poFactory.createFromString(lockInfo.getElementStoreToString());
if (po != null) {
ElexisEventDispatcher.getInstance().fire(
new ElexisEvent(po, po.getClass(), ElexisEvent.EVENT_LOCK_RELEASED));
}
}
}
}
}
private void incrementLockCount(LockInfo lockInfo){
Integer count = lockCount.get(lockInfo.getElementId());
if (count == null) {
count = new Integer(0);
}
lockCount.put(lockInfo.getElementId(), ++count);
logger.debug("Increment to " + count + " locks on " + lockInfo.getElementId());
}
private void decrementLockCount(LockInfo lockInfo){
Integer count = lockCount.get(lockInfo.getElementId());
if (count != null) {
lockCount.put(lockInfo.getElementId(), --count);
logger.debug("Decrement to " + count + " locks on " + lockInfo.getElementId());
if (count < 1) {
lockCount.remove(lockInfo.getElementId());
}
}
}
private Integer getCurrentLockCount(LockInfo lockInfo){
Integer count = lockCount.get(lockInfo.getElementId());
if (count == null) {
count = new Integer(0);
}
logger.debug("Got currently " + count + " locks on " + lockInfo.getElementId());
return count;
}
@Override
public boolean isLockedLocal(IPersistentObject po){
if (po == null) {
return false;
}
if (standalone) {
return true;
}
// check local locks first
if (locks.containsKey(po.getId())) {
return true;
}
return false;
}
@Override
public boolean isLocked(IPersistentObject po){
if (po == null) {
return false;
}
logger.debug("Checking lock on [" + po + "]");
User user = (User) ElexisEventDispatcher.getSelected(User.class);
LockInfo lockInfo = new LockInfo(po.storeToString(), user.getId(), systemUuid.toString());
LockRequest lockRequest = new LockRequest(LockRequest.Type.INFO, lockInfo);
return isLocked(lockRequest);
}
@Override
public boolean isLocked(LockRequest lockRequest){
if (lockRequest == null || lockRequest.getLockInfo().getElementId() == null) {
return false;
}
if (standalone) {
return true;
}
// check local locks first
if (locks.containsKey(lockRequest.getLockInfo().getElementId())) {
return true;
}
try {
return ils.isLocked(lockRequest);
} catch (Exception e) {
logger.error("Catched exception in isLocked: ", e);
return false;
}
}
@Override
public List<LockInfo> getCopyOfAllHeldLocks(){
Collection<LockInfo> values = locks.values();
if (values.size() == 0) {
return Collections.emptyList();
}
return new ArrayList<LockInfo>(values);
}
@Override
public String getSystemUuid(){
return systemUuid.toString();
}
@Override
public LockInfo getLockInfo(String storeToString){
String elementId = LockInfo.getElementId(storeToString);
LockInfo lockInfo = locks.get(elementId);
return lockInfo;
}
private class LockRefreshTask extends TimerTask {
private ILockService restService;
@Override
public void run(){
try {
final String restUrl = System
.getProperty(ElexisSystemPropertyConstants.ELEXIS_SERVER_REST_INTERFACE_URL);
if (restUrl != null && !restUrl.isEmpty()) {
// if service is available but we are not using it -> use it
// if service not available but we are using it -> dont use it
if (testRestUrl(restUrl) && ils instanceof DenyAllLockService
&& restService != null) {
ils = restService;
iis = ConsumerFactory.createConsumer(restUrl, IInstanceService.class);
// publish change
ElexisEventDispatcher.getInstance().fire(new ElexisEvent(null,
ILocalLockService.class, ElexisEvent.EVENT_RELOAD));
} else if (!testRestUrl(restUrl) && !(ils instanceof DenyAllLockService)) {
restService = ils;
iis = null;
ils = new DenyAllLockService();
// publish change
ElexisEventDispatcher.getInstance().fire(new ElexisEvent(null,
ILocalLockService.class, ElexisEvent.EVENT_RELOAD));
}
}
if (standalone) {
return;
}
if (iis != null) {
User u = (User) ElexisEventDispatcher.getSelected(User.class);
inst.setActiveUser((u != null) ? u.getId() : "NO USER ACTIVE");
iis.updateStatus(inst);
}
// verify and update the locks
boolean publishUpdate = false;
synchronized (locks) {
List<String> lockKeys = new ArrayList<String>();
lockKeys.addAll(locks.keySet());
for (String key : lockKeys) {
boolean success = ils.isLocked(new LockRequest(Type.INFO, locks.get(key)));
if (!success) {
publishUpdate = true;
releaseLock(locks.get(key).getElementStoreToString());
}
}
}
if (publishUpdate) {
ElexisEventDispatcher.getInstance()
.fire(new ElexisEvent(null, LockInfo.class, ElexisEvent.EVENT_RELOAD));
}
} catch (Exception e) {
LoggerFactory.getLogger(LockRefreshTask.class).error("Execution error", e);
}
}
private boolean testRestUrl(String restUrl){
try {
URL url = new URL(restUrl);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.connect();
return HttpURLConnection.HTTP_OK == urlConn.getResponseCode();
} catch (IOException e) {
return false;
}
}
}
private class DenyAllLockService implements ILockService {
@Override
public LockResponse acquireOrReleaseLocks(LockRequest request){
return LockResponse
.DENIED(getLockInfo(request.getLockInfo().getElementStoreToString()));
}
@Override
public boolean isLocked(LockRequest request){
return false;
}
@Override
public LockInfo getLockInfo(String storeToString){
return new LockInfo(storeToString, "LockService", "DenyAllLockService");
}
}
@Override
public Status getStatus(){
if (standalone) {
return Status.STANDALONE;
} else if (ils == null || ils instanceof DenyAllLockService) {
return Status.LOCAL;
}
return Status.REMOTE;
}
@Override
public void shutdown(){
timer.cancel();
if (iis != null) {
inst.setState(STATE.SHUTTING_DOWN);
iis.updateStatus(inst);
}
}
}
|
package org.appwork.utils.os;
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.util.logging.Level;
import org.appwork.utils.logging.Log;
import org.appwork.utils.os.mime.Mime;
import org.appwork.utils.os.mime.MimeDefault;
import org.appwork.utils.os.mime.MimeLinux;
import org.appwork.utils.os.mime.MimeWindows;
public class CrossSystem {
public static final byte OS_LINUX_OTHER = 6;
public static final byte OS_MAC_OTHER = 5;
public static final byte OS_WINDOWS_OTHER = 4;
public static final byte OS_WINDOWS_NT = 3;
public static final byte OS_WINDOWS_2000 = 2;
public static final byte OS_WINDOWS_XP = 0;
public static final byte OS_WINDOWS_2003 = 7;
public static final byte OS_WINDOWS_VISTA = 1;
public static final byte OS_WINDOWS_7 = 8;
/**
* Cache to store the OS string in
*/
private final static String OS_STRING;
/**
* Cache to store the OS ID in
*/
private final static byte OS_ID;
/**
* Cache to store the Mime Class in
*/
private static final Mime MIME;
static {
OS_STRING = System.getProperty("os.name");
final String OS = CrossSystem.OS_STRING.toLowerCase();
if (OS.contains("windows 7")) {
OS_ID = CrossSystem.OS_WINDOWS_7;
} else if (OS.contains("windows xp")) {
OS_ID = CrossSystem.OS_WINDOWS_XP;
} else if (OS.contains("windows vista")) {
OS_ID = CrossSystem.OS_WINDOWS_VISTA;
} else if (OS.contains("windows 2000")) {
OS_ID = CrossSystem.OS_WINDOWS_2000;
} else if (OS.contains("windows 2003")) {
OS_ID = CrossSystem.OS_WINDOWS_2003;
} else if (OS.contains("nt")) {
OS_ID = CrossSystem.OS_WINDOWS_NT;
} else if (OS.contains("windows")) {
OS_ID = CrossSystem.OS_WINDOWS_OTHER;
} else if (OS.contains("mac")) {
OS_ID = CrossSystem.OS_MAC_OTHER;
} else {
OS_ID = CrossSystem.OS_LINUX_OTHER;
}
if (CrossSystem.isWindows()) {
MIME = new MimeWindows();
} else if (CrossSystem.isLinux()) {
MIME = new MimeLinux();
} else {
MIME = new MimeDefault();
}
}
public static byte getID() {
return CrossSystem.OS_ID;
}
/**
* Returns the Mime Class for the current OS
*
* @return
* @see Mime
*/
public static Mime getMime() {
return CrossSystem.MIME;
}
public static String getOSString() {
return CrossSystem.OS_STRING;
}
/**
* Returns true if the OS is a linux system
*
* @return
*/
public static boolean isLinux() {
return CrossSystem.OS_ID == CrossSystem.OS_LINUX_OTHER;
}
/**
* Returns true if the OS is a MAC System
*
* @return
*/
public static boolean isMac() {
return CrossSystem.OS_ID == CrossSystem.OS_MAC_OTHER;
}
/**
* @return
*/
public static boolean isOpenBrowserSupported() {
if (CrossSystem.isWindows()) { return true; }
final Desktop desktop = Desktop.getDesktop();
if (!desktop.isSupported(Desktop.Action.BROWSE)) { return false; }
return true;
}
public static boolean isOpenFileSupported() {
if (CrossSystem.isWindows()) { return true; }
final Desktop desktop = Desktop.getDesktop();
if (!desktop.isSupported(Desktop.Action.OPEN)) { return false; }
return true;
}
/**
* Returns true if the OS is a Windows System
*
* @return
*/
public static boolean isWindows() {
switch (CrossSystem.OS_ID) {
case OS_WINDOWS_XP:
case OS_WINDOWS_VISTA:
case OS_WINDOWS_2000:
case OS_WINDOWS_2003:
case OS_WINDOWS_NT:
case OS_WINDOWS_OTHER:
case OS_WINDOWS_7:
return true;
}
return false;
}
/**
* Opens a file or directory
*
* @see java.awt.Desktop#open(File)
* @param file
*/
public static void openFile(final File file) {
if (file == null || !file.exists()) { return; }
if (CrossSystem.isWindows()) {
// workaround for windows
try {
Runtime.getRuntime().exec(new String[] { "rundll32.exe", "url.dll,FileProtocolHandler", file.getAbsolutePath() });
return;
} catch (final IOException e) {
Log.exception(Level.WARNING, e);
}
}
if (!Desktop.isDesktopSupported()) {
Log.L.warning("Desktop is not supported (fatal)");
return;
}
final Desktop desktop = Desktop.getDesktop();
if (!desktop.isSupported(Desktop.Action.OPEN)) {
Log.L.severe("Desktop doesn't support the OPEN action (fatal)");
return;
}
try {
final URI uri = file.getCanonicalFile().toURI();
desktop.open(new File(uri));
} catch (final Exception e) {
try {
Log.L.warning(file.getCanonicalFile().toURI().toString());
} catch (final Exception e1) {
}
Log.exception(Level.WARNING, e);
}
}
/**
* Open an url in the systems default browser
*
* @param url
*/
public static void openURL(final URL url) {
if (url == null) { return; }
if (CrossSystem.isWindows()) {
try {
Runtime.getRuntime().exec(new String[] { "rundll32.exe", "url.dll,FileProtocolHandler", url.toString() });
return;
} catch (final IOException e) {
Log.exception(Level.WARNING, e);
}
}
if (!Desktop.isDesktopSupported()) {
Log.L.severe("Desktop is not supported (fatal)");
return;
}
final Desktop desktop = Desktop.getDesktop();
if (!desktop.isSupported(Desktop.Action.BROWSE)) {
Log.L.warning("Desktop doesn't support the browse action (fatal)");
return;
}
try {
desktop.browse(url.toURI());
} catch (final Exception e) {
try {
Log.L.warning(url.toURI().toString());
} catch (final Exception e1) {
}
Log.exception(Level.WARNING, e);
}
}
}
|
package com.jetbrains.python.psi.impl;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.ResolveState;
import com.intellij.psi.scope.PsiScopeProcessor;
import com.intellij.psi.search.LocalSearchScope;
import com.intellij.psi.search.SearchScope;
import com.intellij.psi.stubs.IStubElementType;
import com.intellij.psi.stubs.StubElement;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.PlatformIcons;
import com.jetbrains.python.PyElementTypes;
import com.jetbrains.python.PyNames;
import com.jetbrains.python.PyTokenTypes;
import com.jetbrains.python.PythonDocStringFinder;
import com.jetbrains.python.codeInsight.controlflow.ControlFlowCache;
import com.jetbrains.python.codeInsight.controlflow.ScopeOwner;
import com.jetbrains.python.documentation.StructuredDocString;
import com.jetbrains.python.psi.*;
import com.jetbrains.python.psi.stubs.PyClassStub;
import com.jetbrains.python.psi.stubs.PyFunctionStub;
import com.jetbrains.python.psi.types.*;
import com.jetbrains.python.sdk.PythonSdkType;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.util.*;
/**
* Implements PyFunction.
*/
public class PyFunctionImpl extends PyPresentableElementImpl<PyFunctionStub> implements PyFunction {
public PyFunctionImpl(ASTNode astNode) {
super(astNode);
}
public PyFunctionImpl(final PyFunctionStub stub) {
this(stub, PyElementTypes.FUNCTION_DECLARATION);
}
public PyFunctionImpl(PyFunctionStub stub, IStubElementType nodeType) {
super(stub, nodeType);
}
@Nullable
@Override
public String getName() {
final PyFunctionStub stub = getStub();
if (stub != null) {
return stub.getName();
}
ASTNode node = getNameNode();
return node != null ? node.getText() : null;
}
public PsiElement getNameIdentifier() {
final ASTNode nameNode = getNameNode();
return nameNode != null ? nameNode.getPsi() : null;
}
public PsiElement setName(@NotNull String name) throws IncorrectOperationException {
final ASTNode nameElement = PyElementGenerator.getInstance(getProject()).createNameIdentifier(name);
getNode().replaceChild(getNameNode(), nameElement);
return this;
}
@Override
public Icon getIcon(int flags) {
return getProperty() != null ? PlatformIcons.PROPERTY_ICON : PlatformIcons.METHOD_ICON;
}
@Nullable
public ASTNode getNameNode() {
return getNode().findChildByType(PyTokenTypes.IDENTIFIER);
}
@NotNull
public PyParameterList getParameterList() {
return getRequiredStubOrPsiChild(PyElementTypes.PARAMETER_LIST);
}
@Nullable
public PyStatementList getStatementList() {
return childToPsi(PyElementTypes.STATEMENT_LIST);
}
public PyClass getContainingClass() {
final PyFunctionStub stub = getStub();
if (stub != null) {
final StubElement parentStub = stub.getParentStub();
if (parentStub instanceof PyClassStub) {
return ((PyClassStub)parentStub).getPsi();
}
return null;
}
final PsiElement parent = getParent();
if (parent instanceof PyStatementList) {
PsiElement pparent = parent.getParent();
if (pparent instanceof PyClass) {
return (PyClass)pparent;
}
}
return null;
}
@Nullable
public PyDecoratorList getDecoratorList() {
return getStubOrPsiChild(PyElementTypes.DECORATOR_LIST); // PsiTreeUtil.getChildOfType(this, PyDecoratorList.class);
}
public boolean isTopLevel() {
return getParentByStub() instanceof PsiFile;
}
@Nullable
public PyType getReturnType(TypeEvalContext typeEvalContext, @Nullable PyReferenceExpression callSite) {
PyAnnotation anno = getAnnotation();
if (anno != null) {
PyClass pyClass = anno.resolveToClass();
if (pyClass != null) {
return new PyClassType(pyClass, false);
}
}
for(PyTypeProvider typeProvider: Extensions.getExtensions(PyTypeProvider.EP_NAME)) {
final PyType returnType = typeProvider.getReturnType(this, callSite, typeEvalContext);
if (returnType != null) {
return returnType;
}
}
final PyType docStringType = getReturnTypeFromDocString();
if (docStringType != null) {
return docStringType;
}
if (typeEvalContext.allowReturnTypes(getContainingFile())) {
final PyType yieldType = getYieldStatementType(typeEvalContext);
if (yieldType != null) {
return yieldType;
}
return getReturnStatementType(typeEvalContext);
}
return null;
}
@Nullable
private PyType getYieldStatementType(@NotNull final TypeEvalContext context) {
PyType elementType = null;
final PyBuiltinCache cache = PyBuiltinCache.getInstance(this);
final PyClass listClass = cache.getClass("list");
final PyStatementList statements = getStatementList();
final Set<PyType> types = new HashSet<PyType>();
if (statements != null && listClass != null) {
statements.accept(new PyRecursiveElementVisitor() {
@Override
public void visitPyYieldExpression(PyYieldExpression node) {
types.add(node.getType(context));
}
});
final int n = types.size();
if (n == 1) {
elementType = types.iterator().next();
}
else if (n > 0) {
elementType = PyUnionType.union(types);
}
}
if (elementType != null) {
final PyType it = PyTypeParser.getTypeByName(this, "Iterator");
if (it instanceof PyClassType) {
return new PyCollectionTypeImpl(((PyClassType)it).getPyClass(), false, elementType);
}
}
return null;
}
@Nullable
public PyType getReturnStatementType(TypeEvalContext typeEvalContext) {
ReturnVisitor visitor = new ReturnVisitor(this, typeEvalContext);
final PyStatementList statements = getStatementList();
if (statements != null) {
statements.accept(visitor);
if (isGeneratedStub() && !visitor.myHasReturns) {
if (PyNames.INIT.equals(getName())) {
return PyNoneType.INSTANCE;
}
return null;
}
}
return visitor.result();
}
public PyFunction asMethod() {
if (getContainingClass() != null) {
return this;
}
else {
return null;
}
}
public PyType getReturnTypeFromDocString() {
String typeName;
final PyFunctionStub stub = getStub();
if (stub != null) {
typeName = stub.getReturnTypeFromDocString();
}
else {
typeName = extractDocStringReturnType();
}
return PyTypeParser.getTypeByName(this, typeName);
}
@Override
public String getDeprecationMessage() {
PyFunctionStub stub = getStub();
if (stub != null) {
return stub.getDeprecationMessage();
}
return extractDeprecationMessage();
}
public String extractDeprecationMessage() {
PyStatementList statementList = getStatementList();
if (statementList == null) {
return null;
}
return extractDeprecationMessage(Arrays.asList(statementList.getStatements()));
}
public static String extractDeprecationMessage(List<PyStatement> statements) {
for (PyStatement statement : statements) {
if (statement instanceof PyExpressionStatement) {
PyExpressionStatement expressionStatement = (PyExpressionStatement)statement;
if (expressionStatement.getExpression() instanceof PyCallExpression) {
PyCallExpression callExpression = (PyCallExpression)expressionStatement.getExpression();
if (callExpression.isCalleeText(PyNames.WARN)) {
PyReferenceExpression warningClass = callExpression.getArgument(1, PyReferenceExpression.class);
if (warningClass != null && (PyNames.DEPRECATION_WARNING.equals(warningClass.getReferencedName()) ||
PyNames.PENDING_DEPRECATION_WARNING.equals(warningClass.getReferencedName()))) {
return PyUtil.strValue(callExpression.getArguments() [0]);
}
}
}
}
}
return null;
}
@Nullable
public String extractDocStringReturnType() {
final PyStringLiteralExpression docString = getDocStringExpression();
if (docString != null) {
return extractReturnType(docString.getStringValue());
}
return null;
}
private boolean isGeneratedStub() {
VirtualFile vFile = getContainingFile().getVirtualFile();
if (vFile != null) {
vFile = vFile.getParent();
if (vFile != null) {
vFile = vFile.getParent();
if (vFile != null && vFile.getName().equals(PythonSdkType.SKELETON_DIR_NAME)) {
return true;
}
}
}
return false;
}
@Nullable
private static String extractReturnType(String docString) {
final List<String> lines = StringUtil.split(docString, "\n");
while (lines.size() > 0 && lines.get(0).trim().length() == 0) {
lines.remove(0);
}
if (lines.size() > 1 && lines.get(1).trim().length() == 0) {
String firstLine = lines.get(0);
int pos = firstLine.lastIndexOf("->");
if (pos >= 0) {
return firstLine.substring(pos + 2).trim();
}
}
StructuredDocString epydocString = StructuredDocString.parse(docString);
return epydocString.getReturnType();
}
private static class ReturnVisitor extends PyRecursiveElementVisitor {
private final PyFunction myFunction;
private final TypeEvalContext myContext;
private PyType myResult = null;
private boolean myHasReturns = false;
public ReturnVisitor(PyFunction function, final TypeEvalContext context) {
myFunction = function;
myContext = context;
}
@Override
public void visitPyReturnStatement(PyReturnStatement node) {
if (PsiTreeUtil.getParentOfType(node, ScopeOwner.class, true) == myFunction) {
final PyExpression expr = node.getExpression();
PyType returnType;
returnType = expr == null ? PyNoneType.INSTANCE : myContext.getType(expr);
if (!myHasReturns) {
myResult = returnType;
myHasReturns = true;
}
else {
myResult = PyUnionType.union(myResult, returnType);
}
}
}
PyType result() {
return myHasReturns ? myResult : PyNoneType.INSTANCE;
}
}
@Override
protected void acceptPyVisitor(PyElementVisitor pyVisitor) {
pyVisitor.visitPyFunction(this);
}
@Override
public boolean processDeclarations(@NotNull PsiScopeProcessor processor,
@NotNull ResolveState substitutor,
PsiElement lastParent,
@NotNull PsiElement place) {
/*
if (lastParent != null && lastParent.getParent() == this) {
final PyNamedParameter[] params = getParameterList().getParameters();
for (PyNamedParameter param : params) {
if (!processor.execute(param, substitutor)) return false;
}
}
*/
return processor.execute(this, substitutor);
}
public int getTextOffset() {
final ASTNode name = getNameNode();
return name != null ? name.getStartOffset() : super.getTextOffset();
}
public void delete() throws IncorrectOperationException {
ASTNode node = getNode();
node.getTreeParent().removeChild(node);
}
public PyStringLiteralExpression getDocStringExpression() {
final PyStatementList stmtList = getStatementList();
return stmtList != null ? PythonDocStringFinder.find(stmtList) : null;
}
protected String getElementLocation() {
final PyClass containingClass = getContainingClass();
if (containingClass != null) {
return "(" + containingClass.getName() + " in " + getPackageForFile(getContainingFile()) + ")";
}
return super.getElementLocation();
}
@NotNull
public Iterable<PyElement> iterateNames() {
return Collections.<PyElement>singleton(this);
}
public PyElement getElementNamed(final String the_name) {
return the_name.equals(getName()) ? this : null;
}
public boolean mustResolveOutside() {
return false;
}
@Override
public String toString() {
return super.toString() + "('" + getName() + "')";
}
public void subtreeChanged() {
super.subtreeChanged();
ControlFlowCache.clear(this);
}
public Property getProperty() {
final PyClass containingClass = getContainingClass();
final String name = getName();
if (containingClass != null && name != null) {
// TODO find property which uses property call, rather than annotation (function name will be different in that case)
return containingClass.findProperty(name);
}
return null;
}
@Override
public PyAnnotation getAnnotation() {
return findChildByClass(PyAnnotation.class);
}
@NotNull
@Override
public SearchScope getUseScope() {
final ScopeOwner scopeOwner = PsiTreeUtil.getParentOfType(this, ScopeOwner.class);
if (scopeOwner instanceof PyFunction) {
return new LocalSearchScope(scopeOwner);
}
return super.getUseScope();
}
}
|
package org.appwork.utils.os;
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.logging.Level;
import javax.swing.filechooser.FileFilter;
import net.miginfocom.swing.MigLayout;
import org.appwork.exceptions.WTFException;
import org.appwork.shutdown.ShutdownController;
import org.appwork.shutdown.ShutdownEvent;
import org.appwork.storage.JSonStorage;
import org.appwork.storage.StorageException;
import org.appwork.utils.Application;
import org.appwork.utils.Regex;
import org.appwork.utils.StringUtils;
import org.appwork.utils.locale._AWU;
import org.appwork.utils.logging.Log;
import org.appwork.utils.os.mime.Mime;
import org.appwork.utils.os.mime.MimeDefault;
import org.appwork.utils.os.mime.MimeLinux;
import org.appwork.utils.os.mime.MimeWindows;
import org.appwork.utils.swing.dialog.Dialog;
import org.appwork.utils.swing.dialog.DialogCanceledException;
import org.appwork.utils.swing.dialog.DialogClosedException;
import org.appwork.utils.swing.dialog.DialogNoAnswerException;
public class CrossSystem {
public static final byte OS_LINUX_OTHER = 6;
public static final byte OS_MAC_OTHER = 5;
public static final byte OS_WINDOWS_OTHER = 4;
public static final byte OS_WINDOWS_NT = 3;
public static final byte OS_WINDOWS_2000 = 2;
public static final byte OS_WINDOWS_XP = 0;
public static final byte OS_WINDOWS_2003 = 7;
public static final byte OS_WINDOWS_VISTA = 1;
public static final byte OS_WINDOWS_7 = 8;
public static final byte OS_WINDOWS_SERVER_2008 = 9;
private static Boolean openURLSupport = null;
private static Boolean openFILESupport = null;
private static String JAVAINT = null;
/**
* Cache to store the OS string in
*/
private final static String OS_STRING;
/**
* Cache to store the OS ID in
*/
private final static byte OS_ID;
/**
* Cache to store the Mime Class in
*/
private static final Mime MIME;
private static String[] BROWSER_COMMANDLINE = null;
static {
}
static {
OS_STRING = System.getProperty("os.name");
final String OS = CrossSystem.OS_STRING.toLowerCase();
if (OS.contains("windows 7")) {
OS_ID = CrossSystem.OS_WINDOWS_7;
} else if (OS.contains("windows xp")) {
OS_ID = CrossSystem.OS_WINDOWS_XP;
} else if (OS.contains("windows vista")) {
OS_ID = CrossSystem.OS_WINDOWS_VISTA;
} else if (OS.contains("windows 2000")) {
OS_ID = CrossSystem.OS_WINDOWS_2000;
} else if (OS.contains("windows 2003")) {
OS_ID = CrossSystem.OS_WINDOWS_2003;
} else if (OS.contains("windows server 2008")) {
OS_ID = CrossSystem.OS_WINDOWS_SERVER_2008;
} else if (OS.contains("nt")) {
OS_ID = CrossSystem.OS_WINDOWS_NT;
} else if (OS.contains("windows")) {
OS_ID = CrossSystem.OS_WINDOWS_OTHER;
} else if (OS.contains("mac")) {
OS_ID = CrossSystem.OS_MAC_OTHER;
} else {
OS_ID = CrossSystem.OS_LINUX_OTHER;
}
if (CrossSystem.isWindows()) {
MIME = new MimeWindows();
} else if (CrossSystem.isLinux()) {
MIME = new MimeLinux();
} else {
MIME = new MimeDefault();
}
if (CrossSystem.isWindows()) {
CrossSystem.BROWSER_COMMANDLINE = new String[] { "rundll32.exe", "url.dll,FileProtocolHandler", "%s" };
}
}
private static boolean _isOpenBrowserSupported() {
if (CrossSystem.isWindows()) { return true; }
try {
if (!Desktop.isDesktopSupported()) { return false; }
final Desktop desktop = Desktop.getDesktop();
if (!desktop.isSupported(Desktop.Action.BROWSE)) { return false; }
return true;
} catch (final Throwable e) {
Log.exception(Level.WARNING, e);
}
return false;
}
private static boolean _isOpenFileSupported() {
if (CrossSystem.isWindows()) { return true; }
try {
if (!Desktop.isDesktopSupported()) { return false; }
final Desktop desktop = Desktop.getDesktop();
if (!desktop.isSupported(Desktop.Action.OPEN)) { return false; }
return true;
} catch (final Throwable e) {
Log.exception(Level.WARNING, e);
}
return false;
}
/**
* internal function to open a file/folder
*
* @param file
* @throws IOException
*/
private static void _openFILE(final File file) throws IOException {
if (CrossSystem.isWindows()) {
// workaround for windows
Runtime.getRuntime().exec(new String[] { "rundll32.exe", "url.dll,FileProtocolHandler", file.getAbsolutePath() });
} else {
final Desktop desktop = Desktop.getDesktop();
final URI uri = file.getCanonicalFile().toURI();
desktop.open(new File(uri));
}
}
/**
* internal function to open an URL in a browser
*
* @param _url
* @throws IOException
* @throws URISyntaxException
*/
private static void _openURL(final String _url) throws IOException, URISyntaxException {
final URL url = new URL(_url);
final String custom[] = CrossSystem.BROWSER_COMMANDLINE;
if (custom != null && custom.length > 0) {
final ArrayList<String> commands = new ArrayList<String>();
for (final String s : custom) {
commands.add(s.replace("%s", _url));
}
Runtime.getRuntime().exec(commands.toArray(new String[] {}));
} else {
final Desktop desktop = Desktop.getDesktop();
desktop.browse(url.toURI());
}
}
/**
* use this method to make pathPart safe to use in a full absoluePath.
*
* it will remove driveletters/path seperators and all known chars that are
* forbidden in a path
*
* @param pathPart
* @return
*/
public static String alleviatePathParts(String pathPart) {
if (StringUtils.isEmpty(pathPart)) { return null; }
/* remove invalid chars */
pathPart = pathPart.replaceAll("([\\\\|<|>|\\||\"|:|\\*|\\?|/|\\x00])+", "_");
/*
* remove ending points, not allowed under windows and others os maybe
* too
*/
pathPart = pathPart.replaceFirst("\\.+$", "");
return pathPart;
}
public static String[] getEditor(final String extension) throws DialogCanceledException, DialogClosedException, StorageException {
final File[] ret = Dialog.getInstance().showFileChooser("FILE_EDIT_CONTROLLER_" + extension, _AWU.T.fileditcontroller_geteditor_for(extension), Dialog.FileChooserSelectionMode.FILES_ONLY, new FileFilter() {
@Override
public boolean accept(final File f) {
if (f.isDirectory()) { return true; }
if (CrossSystem.isWindows()) {
return f.getName().endsWith(".exe");
} else {
return f.canExecute();
}
}
@Override
public String getDescription() {
return _AWU.T.fileeditcontroller_exechooser_description(extension);
}
}, false, Dialog.FileChooserType.OPEN_DIALOG_WITH_PRESELECTION, new File(JSonStorage.getPlainStorage("EDITORS").get(extension, "")));
if (ret != null && ret.length > 0) {
JSonStorage.getPlainStorage("EDITORS").put(extension, ret[0].toString());
return new String[] { ret[0].toString() };
} else {
return null;
}
}
public static String getFileExtension(final String str) {
if (StringUtils.isEmpty(str)) { return null; }
final int lastPoint = str.lastIndexOf(".");
if (lastPoint > 0 && lastPoint != str.length()) { return str.substring(lastPoint + 1); }
return null;
}
public static byte getID() {
return CrossSystem.OS_ID;
}
public static String getJavaBinary() {
if (CrossSystem.JAVAINT != null) { return CrossSystem.JAVAINT; }
String javaBinary = "java";
if (CrossSystem.isWindows()) {
javaBinary = "javaw.exe";
}
final String javaHome = System.getProperty("java.home");
if (javaHome != null) {
/* get path from system property */
final File java = new File(new File(javaHome), "/bin/" + javaBinary);
if (java.exists() && java.isFile()) {
CrossSystem.JAVAINT = java.getAbsolutePath();
}
} else {
CrossSystem.JAVAINT = javaBinary;
}
return CrossSystem.JAVAINT;
}
/**
* Returns the Mime Class for the current OS
*
* @return
* @see Mime
*/
public static Mime getMime() {
return CrossSystem.MIME;
}
public static String getOSString() {
return CrossSystem.OS_STRING;
}
/**
* checks if given path is absolute or relative
*
* @param path
* @return
*/
public static boolean isAbsolutePath(final String path) {
if (StringUtils.isEmpty(path)) { return false; }
if (CrossSystem.isWindows() && path.matches(".:/.*")) { return true; }
if (CrossSystem.isWindows() && path.matches(".:\\\\.*")) { return true; }
if (path.startsWith("/")) { return true; }
return false;
}
/**
* Returns true if the OS is a linux system
*
* @return
*/
public static boolean isLinux() {
return CrossSystem.OS_ID == CrossSystem.OS_LINUX_OTHER;
}
/**
* Returns true if the OS is a MAC System
*
* @return
*/
public static boolean isMac() {
return CrossSystem.OS_ID == CrossSystem.OS_MAC_OTHER;
}
/**
* returns true in case of "open an URL in a browser" is supported
*
* @return
*/
public static boolean isOpenBrowserSupported() {
if (CrossSystem.openURLSupport != null) { return CrossSystem.openURLSupport; }
CrossSystem.openURLSupport = CrossSystem._isOpenBrowserSupported();
return CrossSystem.openURLSupport;
}
/**
* returns true in case of "open a File" is supported
*
* @return
*/
public static boolean isOpenFileSupported() {
if (CrossSystem.openFILESupport != null) { return CrossSystem.openFILESupport; }
CrossSystem.openFILESupport = CrossSystem._isOpenFileSupported();
return CrossSystem.openFILESupport;
}
/**
* Returns true if the OS is a Windows System
*
* @return
*/
public static boolean isWindows() {
switch (CrossSystem.OS_ID) {
case OS_WINDOWS_XP:
case OS_WINDOWS_VISTA:
case OS_WINDOWS_2000:
case OS_WINDOWS_2003:
case OS_WINDOWS_NT:
case OS_WINDOWS_OTHER:
case OS_WINDOWS_7:
case OS_WINDOWS_SERVER_2008:
return true;
}
return false;
}
public static void main(final String[] args) {
CrossSystem.restartApplication(MigLayout.class);
}
/**
* Opens a file or directory
*
* @see java.awt.Desktop#open(File)
* @param file
*/
public static void openFile(final File file) {
try {
CrossSystem._openFILE(file);
} catch (final Throwable e) {
Log.exception(Level.WARNING, e);
}
}
/**
* Open an url in the systems default browser
*
* @param url
*/
public static void openURL(final String url) {
try {
CrossSystem._openURL(url);
} catch (final Throwable e) {
Log.exception(Level.WARNING, e);
}
}
public static void openURL(final URL url) {
CrossSystem.openURL(url.toString());
}
/**
* @param update_dialog_news_button_url
*/
public static void openURLOrShowMessage(final String urlString) {
try {
CrossSystem._openURL(urlString);
} catch (final Throwable e) {
Log.exception(Level.WARNING, e);
try {
Dialog.getInstance().showInputDialog(Dialog.BUTTONS_HIDE_CANCEL, _AWU.T.crossSystem_open_url_failed_msg(), urlString);
} catch (final DialogNoAnswerException donothing) {
}
}
}
/**
* @param class1
*/
public static void restartApplication(final Class<?> class1, final String... parameters) {
try {
final ArrayList<String> nativeParameters = new ArrayList<String>();
File runin = null;
if (CrossSystem.isMac()) {
// find .app
File rootpath = Application.getRootByClass(class1, null);
final HashSet<File> loopMap = new HashSet<File>();
while (rootpath != null && loopMap.add(rootpath)) {
if (rootpath.getName().endsWith(".app")) {
break;
}
rootpath = rootpath.getParentFile();
}
if (rootpath.getName().endsWith(".app")) {
// found app.- restart it.
nativeParameters.add("open");
nativeParameters.add("-n");
nativeParameters.add(rootpath.getAbsolutePath());
runin = rootpath.getParentFile();
}
}
if (nativeParameters.isEmpty()) {
final URL root = class1.getClassLoader().getResource(class1.getName().replace(".", "/") + ".class");
// Filenames may contain ! !!
final int index = root.getPath().indexOf("!");
if (index <= 0 || !"jar".equalsIgnoreCase(root.getProtocol())) {
throw new WTFException("REstart works only in Jared mode");
} else {
final File jarFile = new File(new URI(root.getPath().substring(0, index)));
runin = jarFile.getParentFile();
if (CrossSystem.isWindows()) {
final File exeFile = new File(jarFile.getParentFile(), jarFile.getName().substring(0, jarFile.getName().length() - 4) + ".exe");
if (exeFile.exists()) {
nativeParameters.add(exeFile.getAbsolutePath());
} else {
nativeParameters.add(CrossSystem.getJavaBinary());
nativeParameters.add("-jar");
nativeParameters.add(jarFile.getAbsolutePath());
}
} else {
nativeParameters.add(CrossSystem.getJavaBinary());
nativeParameters.add("-jar");
nativeParameters.add(jarFile.getAbsolutePath());
}
}
}
if (parameters != null) {
for (final String s : parameters) {
nativeParameters.add(s);
}
}
final ProcessBuilder pb = new ProcessBuilder(nativeParameters.toArray(new String[] {}));
/*
* needed because the root is different for jre/class version
*/
System.out.println("Root: " + runin);
if (runin != null) {
pb.directory(runin);
}
ShutdownController.getInstance().addShutdownEvent(new ShutdownEvent() {
{
this.setHookPriority(Integer.MIN_VALUE);
}
@Override
public void run() {
try {
pb.start();
} catch (final IOException e) {
Log.exception(e);
}
}
});
ShutdownController.getInstance().requestShutdown();
} catch (final Throwable e) {
throw new WTFException(e);
}
}
/**
* Set commandline to open the browser use %s as wildcard for the url
*
* @param commands
*/
public static void setBrowserCommandLine(final String[] commands) {
CrossSystem.BROWSER_COMMANDLINE = commands;
}
/**
* splits filename into name,extension
*
* @param filename
* @return
*/
public static String[] splitFileName(final String filename) {
final String extension = new Regex(filename, "\\.+([^\\.]*$)").getMatch(0);
final String name = new Regex(filename, "(.*?)(\\.+[^\\.]*$|$)").getMatch(0);
return new String[] { name, extension };
}
}
|
//FILE: MMStudioMainFrame.java
//PROJECT: Micro-Manager
//SUBSYSTEM: mmstudio
// Modifications by Arthur Edelstein, Nico Stuurman
// This file is distributed in the hope that it will be useful,
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.
//CVS: $Id$
package org.micromanager;
import ij.IJ;
import ij.ImageJ;
import ij.ImagePlus;
import ij.WindowManager;
import ij.gui.Line;
import ij.gui.Roi;
import ij.process.ImageProcessor;
import ij.process.ShortProcessor;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.Point2D;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.prefs.Preferences;
import java.util.Timer;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JToggleButton;
import javax.swing.SpringLayout;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.ToolTipManager;
import javax.swing.UIManager;
import javax.swing.event.AncestorEvent;
import mmcorej.CMMCore;
import mmcorej.DeviceType;
import mmcorej.MMCoreJ;
import mmcorej.MMEventCallback;
import mmcorej.Metadata;
import mmcorej.StrVector;
import org.json.JSONObject;
import org.micromanager.acquisition.AcquisitionManager;
import org.micromanager.api.ImageCache;
import org.micromanager.api.ImageCacheListener;
import org.micromanager.acquisition.MMImageCache;
import org.micromanager.api.AcquisitionEngine;
import org.micromanager.api.Autofocus;
import org.micromanager.api.DeviceControlGUI;
import org.micromanager.api.MMPlugin;
import org.micromanager.api.ScriptInterface;
import org.micromanager.api.MMListenerInterface;
import org.micromanager.conf2.ConfiguratorDlg2;
import org.micromanager.conf.ConfiguratorDlg;
import org.micromanager.conf.MMConfigFileException;
import org.micromanager.conf.MicroscopeModel;
import org.micromanager.graph.SingleChannelContrastPanel;
import org.micromanager.graph.GraphData;
import org.micromanager.graph.GraphFrame;
import org.micromanager.navigation.CenterAndDragListener;
import org.micromanager.navigation.PositionList;
import org.micromanager.navigation.XYZKeyListener;
import org.micromanager.navigation.ZWheelListener;
import org.micromanager.utils.AutofocusManager;
import org.micromanager.utils.ContrastSettings;
import org.micromanager.utils.GUIColors;
import org.micromanager.utils.GUIUtils;
import org.micromanager.utils.JavaUtils;
import org.micromanager.utils.MMException;
import org.micromanager.utils.MMScriptException;
import org.micromanager.utils.NumberUtils;
import org.micromanager.utils.TextUtils;
import org.micromanager.utils.TooltipTextMaker;
import org.micromanager.utils.WaitDialog;
import bsh.EvalError;
import bsh.Interpreter;
import com.swtdesigner.SwingResourceManager;
import ij.gui.ImageCanvas;
import ij.gui.ImageWindow;
import ij.process.FloatProcessor;
import java.awt.Cursor;
import java.awt.Graphics;
import java.awt.KeyboardFocusManager;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Collections;
import java.util.HashMap;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.event.AncestorListener;
import mmcorej.TaggedImage;
import org.json.JSONException;
import org.micromanager.acquisition.AcquisitionVirtualStack;
import org.micromanager.acquisition.AcquisitionWrapperEngine;
import org.micromanager.acquisition.LiveModeTimer;
import org.micromanager.acquisition.MMAcquisition;
import org.micromanager.acquisition.MetadataPanel;
import org.micromanager.acquisition.TaggedImageStorageDiskDefault;
import org.micromanager.acquisition.VirtualAcquisitionDisplay;
import org.micromanager.utils.ImageFocusListener;
import org.micromanager.api.Pipeline;
import org.micromanager.api.TaggedImageStorage;
import org.micromanager.utils.FileDialogs;
import org.micromanager.utils.FileDialogs.FileType;
import org.micromanager.utils.HotKeysDialog;
import org.micromanager.utils.ImageUtils;
import org.micromanager.utils.MDUtils;
import org.micromanager.utils.MMKeyDispatcher;
import org.micromanager.utils.ReportingUtils;
/*
* Main panel and application class for the MMStudio.
*/
public class MMStudioMainFrame extends JFrame implements DeviceControlGUI, ScriptInterface {
private static final String MICRO_MANAGER_TITLE = "Micro-Manager 1.4";
private static final String VERSION = "1.4.7 20111110";
private static final long serialVersionUID = 3556500289598574541L;
private static final String MAIN_FRAME_X = "x";
private static final String MAIN_FRAME_Y = "y";
private static final String MAIN_FRAME_WIDTH = "width";
private static final String MAIN_FRAME_HEIGHT = "height";
private static final String MAIN_FRAME_DIVIDER_POS = "divider_pos";
private static final String MAIN_EXPOSURE = "exposure";
private static final String SYSTEM_CONFIG_FILE = "sysconfig_file";
private static final String CONTRAST_SETTINGS_8_MIN = "contrast8_MIN";
private static final String CONTRAST_SETTINGS_8_MAX = "contrast8_MAX";
private static final String CONTRAST_SETTINGS_16_MIN = "contrast16_MIN";
private static final String CONTRAST_SETTINGS_16_MAX = "contrast16_MAX";
private static final String OPEN_ACQ_DIR = "openDataDir";
private static final String SCRIPT_CORE_OBJECT = "mmc";
private static final String SCRIPT_ACQENG_OBJECT = "acq";
private static final String SCRIPT_GUI_OBJECT = "gui";
private static final String AUTOFOCUS_DEVICE = "autofocus_device";
private static final String MOUSE_MOVES_STAGE = "mouse_moves_stage";
private static final int TOOLTIP_DISPLAY_DURATION_MILLISECONDS = 15000;
private static final int TOOLTIP_DISPLAY_INITIAL_DELAY_MILLISECONDS = 2000;
// cfg file saving
private static final String CFGFILE_ENTRY_BASE = "CFGFileEntry"; // + {0, 1, 2, 3, 4}
// GUI components
private JComboBox comboBinning_;
private JComboBox shutterComboBox_;
private JTextField textFieldExp_;
private JLabel labelImageDimensions_;
private JToggleButton toggleButtonLive_;
private JCheckBox autoShutterCheckBox_;
private boolean shutterOriginalState_;
private boolean autoShutterOriginalState_;
private MMOptions options_;
private boolean runsAsPlugin_;
private JCheckBoxMenuItem centerAndDragMenuItem_;
private JButton buttonSnap_;
private JButton buttonAutofocus_;
private JButton buttonAutofocusTools_;
private JToggleButton toggleButtonShutter_;
private GUIColors guiColors_;
private GraphFrame profileWin_;
private PropertyEditor propertyBrowser_;
private CalibrationListDlg calibrationListDlg_;
private AcqControlDlg acqControlWin_;
private ReportProblemDialog reportProblemDialog_;
private JMenu pluginMenu_;
private ArrayList<PluginItem> plugins_;
private List<MMListenerInterface> MMListeners_
= (List<MMListenerInterface>)
Collections.synchronizedList(new ArrayList<MMListenerInterface>());
private List<Component> MMFrames_
= (List<Component>)
Collections.synchronizedList(new ArrayList<Component>());
private AutofocusManager afMgr_;
private final static String DEFAULT_CONFIG_FILE_NAME = "MMConfig_demo.cfg";
private ArrayList<String> MRUConfigFiles_;
private static final int maxMRUCfgs_ = 5;
private String sysConfigFile_;
private String startupScriptFile_;
private String sysStateFile_ = "MMSystemState.cfg";
private ConfigGroupPad configPad_;
private LiveModeTimer liveModeTimer_;
private GraphData lineProfileData_;
// labels for standard devices
private String cameraLabel_;
private String zStageLabel_;
private String shutterLabel_;
private String xyStageLabel_;
// applications settings
private Preferences mainPrefs_;
private Preferences systemPrefs_;
private Preferences colorPrefs_;
// MMcore
private CMMCore core_;
private AcquisitionEngine engine_;
private PositionList posList_;
private PositionListDlg posListDlg_;
private String openAcqDirectory_ = "";
private boolean running_;
private boolean configChanged_ = false;
private StrVector shutters_ = null;
private JButton saveConfigButton_;
private ScriptPanel scriptPanel_;
private org.micromanager.utils.HotKeys hotKeys_;
private CenterAndDragListener centerAndDragListener_;
private ZWheelListener zWheelListener_;
private XYZKeyListener xyzKeyListener_;
private AcquisitionManager acqMgr_;
private static VirtualAcquisitionDisplay simpleDisplay_;
private Color[] multiCameraColors_ = {Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW, Color.CYAN};
private int snapCount_ = -1;
private boolean liveModeSuspended_;
public Font defaultScriptFont_ = null;
public static final String SIMPLE_ACQ = "Snap/Live Window";
public static FileType MM_CONFIG_FILE
= new FileType("MM_CONFIG_FILE",
"Micro-Manager Config File",
"./MyScope.cfg",
true, "cfg");
// Our instance
private static MMStudioMainFrame gui_;
// Callback
private CoreEventCallback cb_;
// Lock invoked while shutting down
private final Object shutdownLock_ = new Object();
private JMenuBar menuBar_;
private ConfigPadButtonPanel configPadButtonPanel_;
private final JMenu switchConfigurationMenu_;
private final MetadataPanel metadataPanel_;
public static FileType MM_DATA_SET
= new FileType("MM_DATA_SET",
"Micro-Manager Image Location",
System.getProperty("user.home") + "/Untitled",
false, (String[]) null);
private Thread pipelineClassLoadingThread_ = null;
private Class pipelineClass_ = null;
private Pipeline acquirePipeline_ = null;
private final JSplitPane splitPane_;
private volatile boolean ignorePropertyChanges_;
public ImageWindow getImageWin() {
return simpleDisplay_.getHyperImage().getWindow();
}
public static VirtualAcquisitionDisplay getSimpleDisplay() {
return simpleDisplay_;
}
public static void createSimpleDisplay(String name, ImageCache cache) throws MMScriptException {
simpleDisplay_ = new VirtualAcquisitionDisplay(cache, name);
}
private void checkSimpleAcquisition() {
int width = (int) core_.getImageWidth();
int height = (int) core_.getImageHeight();
int depth = (int) core_.getBytesPerPixel();
int bitDepth = (int) core_.getImageBitDepth();
int numCamChannels = (int) core_.getNumberOfCameraChannels();
try {
if (acquisitionExists(SIMPLE_ACQ)) {
if ((getAcquisitionImageWidth(SIMPLE_ACQ) != width)
|| (getAcquisitionImageHeight(SIMPLE_ACQ) != height)
|| (getAcquisitionImageByteDepth(SIMPLE_ACQ) != depth)
|| (getAcquisitionImageBitDepth(SIMPLE_ACQ) != bitDepth)
|| (getAcquisitionMultiCamNumChannels(SIMPLE_ACQ) != numCamChannels)) { //Need to close and reopen simple window
closeAcquisitionImage5D(SIMPLE_ACQ);
closeAcquisition(SIMPLE_ACQ);
}
}
if (!acquisitionExists(SIMPLE_ACQ)) {
openAcquisition(SIMPLE_ACQ, "", 1, numCamChannels, 1, true);
if (numCamChannels > 1) {
for (long i = 0; i < numCamChannels; i++) {
String chName = core_.getCameraChannelName(i);
int defaultColor = multiCameraColors_[(int) i % multiCameraColors_.length].getRGB();
setChannelColor(SIMPLE_ACQ, (int) i,
getChannelColor(chName, defaultColor));
setChannelName(SIMPLE_ACQ, (int) i, chName);
}
}
initializeSimpleAcquisition(SIMPLE_ACQ, width, height, depth, bitDepth, numCamChannels);
getAcquisition(SIMPLE_ACQ).promptToSave(false);
getAcquisition(SIMPLE_ACQ).toFront();
}
} catch (Exception ex) {
ReportingUtils.showError(ex);
}
}
public void saveChannelColor(String chName, int rgb)
{
if (colorPrefs_ != null) {
colorPrefs_.putInt("Color_" + chName, rgb);
}
}
public Color getChannelColor(String chName, int defaultColor)
{
if (colorPrefs_ != null) {
defaultColor = colorPrefs_.getInt("Color_" + chName, defaultColor);
}
return new Color(defaultColor);
}
private void initializeHelpMenu() {
// add help menu item
final JMenu helpMenu = new JMenu();
helpMenu.setText("Help");
menuBar_.add(helpMenu);
final JMenuItem usersGuideMenuItem = new JMenuItem();
usersGuideMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
ij.plugin.BrowserLauncher.openURL("http://valelab.ucsf.edu/~MM/MMwiki/index.php/Micro-Manager_User%27s_Guide");
} catch (IOException e1) {
ReportingUtils.showError(e1);
}
}
});
usersGuideMenuItem.setText("User's Guide...");
helpMenu.add(usersGuideMenuItem);
final JMenuItem configGuideMenuItem = new JMenuItem();
configGuideMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
ij.plugin.BrowserLauncher.openURL("http://valelab.ucsf.edu/~MM/MMwiki/index.php/Micro-Manager_Configuration_Guide");
} catch (IOException e1) {
ReportingUtils.showError(e1);
}
}
});
configGuideMenuItem.setText("Configuration Guide...");
helpMenu.add(configGuideMenuItem);
if (!systemPrefs_.getBoolean(RegistrationDlg.REGISTRATION, false)) {
final JMenuItem registerMenuItem = new JMenuItem();
registerMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
RegistrationDlg regDlg = new RegistrationDlg(systemPrefs_);
regDlg.setVisible(true);
} catch (Exception e1) {
ReportingUtils.showError(e1);
}
}
});
registerMenuItem.setText("Register your copy of Micro-Manager...");
helpMenu.add(registerMenuItem);
}
final MMStudioMainFrame thisFrame = this;
final JMenuItem reportProblemMenuItem = new JMenuItem();
reportProblemMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (null == reportProblemDialog_) {
reportProblemDialog_ = new ReportProblemDialog(core_, thisFrame, sysConfigFile_, options_);
thisFrame.addMMBackgroundListener(reportProblemDialog_);
reportProblemDialog_.setBackground(guiColors_.background.get(options_.displayBackground_));
}
reportProblemDialog_.setVisible(true);
}
});
reportProblemMenuItem.setText("Report Problem");
helpMenu.add(reportProblemMenuItem);
final JMenuItem aboutMenuItem = new JMenuItem();
aboutMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
MMAboutDlg dlg = new MMAboutDlg();
String versionInfo = "MM Studio version: " + VERSION;
versionInfo += "\n" + core_.getVersionInfo();
versionInfo += "\n" + core_.getAPIVersionInfo();
versionInfo += "\nUser: " + core_.getUserId();
versionInfo += "\nHost: " + core_.getHostName();
dlg.setVersionInfo(versionInfo);
dlg.setVisible(true);
}
});
aboutMenuItem.setText("About Micromanager...");
helpMenu.add(aboutMenuItem);
menuBar_.validate();
}
private void updateSwitchConfigurationMenu() {
switchConfigurationMenu_.removeAll();
for (final String configFile : MRUConfigFiles_) {
if (! configFile.equals(sysConfigFile_)) {
JMenuItem configMenuItem = new JMenuItem();
configMenuItem.setText(configFile);
configMenuItem.addActionListener(new ActionListener() {
String theConfigFile = configFile;
public void actionPerformed(ActionEvent e) {
sysConfigFile_ = theConfigFile;
loadSystemConfiguration();
mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_);
}
});
switchConfigurationMenu_.add(configMenuItem);
}
}
}
/**
* Allows MMListeners to register themselves
*/
public void addMMListener(MMListenerInterface newL) {
if (MMListeners_.contains(newL))
return;
MMListeners_.add(newL);
}
/**
* Allows MMListeners to remove themselves
*/
public void removeMMListener(MMListenerInterface oldL) {
if (!MMListeners_.contains(oldL))
return;
MMListeners_.remove(oldL);
}
/**
* Lets JComponents register themselves so that their background can be
* manipulated
*/
public void addMMBackgroundListener(Component comp) {
if (MMFrames_.contains(comp))
return;
MMFrames_.add(comp);
}
/**
* Lets JComponents remove themselves from the list whose background gets
* changes
*/
public void removeMMBackgroundListener(Component comp) {
if (!MMFrames_.contains(comp))
return;
MMFrames_.remove(comp);
}
public void updateContrast(ImagePlus iplus) {
// contrastPanel_.updateContrast(iplus);
// metadataPanel_.updateContrast(iplus);
}
/**
* Part of ScriptInterface
* Manipulate acquisition so that it looks like a burst
*/
public void runBurstAcquisition() throws MMScriptException {
double interval = engine_.getFrameIntervalMs();
int nr = engine_.getNumFrames();
boolean doZStack = engine_.isZSliceSettingEnabled();
boolean doChannels = engine_.isChannelsSettingEnabled();
engine_.enableZSliceSetting(false);
engine_.setFrames(nr, 0);
engine_.enableChannelsSetting(false);
try {
engine_.acquire();
} catch (MMException e) {
throw new MMScriptException(e);
}
engine_.setFrames(nr, interval);
engine_.enableZSliceSetting(doZStack);
engine_.enableChannelsSetting(doChannels);
}
public void runBurstAcquisition(int nr) throws MMScriptException {
int originalNr = engine_.getNumFrames();
double interval = engine_.getFrameIntervalMs();
engine_.setFrames(nr, 0);
this.runBurstAcquisition();
engine_.setFrames(originalNr, interval);
}
public void runBurstAcquisition(int nr, String name, String root) throws MMScriptException {
//String originalName = engine_.getDirName();
String originalRoot = engine_.getRootName();
engine_.setDirName(name);
engine_.setRootName(root);
this.runBurstAcquisition(nr);
engine_.setRootName(originalRoot);
//engine_.setDirName(originalDirName);
}
/**
* @deprecated
* @throws MMScriptException
*/
public void startBurstAcquisition() throws MMScriptException {
runAcquisition();
}
public boolean isBurstAcquisitionRunning() throws MMScriptException {
if (engine_ == null)
return false;
return engine_.isAcquisitionRunning();
}
private void startLoadingPipelineClass() {
Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
pipelineClassLoadingThread_ = new Thread("Pipeline Class loading thread") {
@Override
public void run() {
try {
pipelineClass_ = Class.forName("org.micromanager.AcqEngine");
} catch (Exception ex) {
ReportingUtils.logError(ex);
pipelineClass_ = null;
}
}
};
pipelineClassLoadingThread_.start();
}
public void addImageStorageListener(ImageCacheListener listener) {
throw new UnsupportedOperationException("Not supported yet.");
}
public ImageCache getAcquisitionImageCache(String acquisitionName) {
throw new UnsupportedOperationException("Not supported yet.");
}
/**
* Callback to update GUI when a change happens in the MMCore.
*/
public class CoreEventCallback extends MMEventCallback {
public CoreEventCallback() {
super();
}
@Override
public void onPropertiesChanged() {
// TODO: remove test once acquisition engine is fully multithreaded
if (engine_ != null && engine_.isAcquisitionRunning()) {
core_.logMessage("Notification from MMCore ignored because acquistion is running!");
} else {
if (ignorePropertyChanges_) {
core_.logMessage("Notification from MMCore ignored since the system is still loading");
} else {
core_.updateSystemStateCache();
updateGUI(true);
// update all registered listeners
for (MMListenerInterface mmIntf : MMListeners_) {
mmIntf.propertiesChangedAlert();
}
core_.logMessage("Notification from MMCore!");
}
}
}
@Override
public void onPropertyChanged(String deviceName, String propName, String propValue) {
core_.logMessage("Notification for Device: " + deviceName + " Property: " +
propName + " changed to value: " + propValue);
// update all registered listeners
for (MMListenerInterface mmIntf:MMListeners_) {
mmIntf.propertyChangedAlert(deviceName, propName, propValue);
}
}
@Override
public void onConfigGroupChanged(String groupName, String newConfig) {
try {
configPad_.refreshGroup(groupName, newConfig);
for (MMListenerInterface mmIntf:MMListeners_) {
mmIntf.configGroupChangedAlert(groupName, newConfig);
}
} catch (Exception e) {
}
}
@Override
public void onPixelSizeChanged(double newPixelSizeUm) {
updatePixSizeUm (newPixelSizeUm);
for (MMListenerInterface mmIntf:MMListeners_) {
mmIntf.pixelSizeChangedAlert(newPixelSizeUm);
}
}
@Override
public void onStagePositionChanged(String deviceName, double pos) {
if (deviceName.equals(zStageLabel_)) {
updateZPos(pos);
for (MMListenerInterface mmIntf:MMListeners_) {
mmIntf.stagePositionChangedAlert(deviceName, pos);
}
}
}
@Override
public void onStagePositionChangedRelative(String deviceName, double pos) {
if (deviceName.equals(zStageLabel_))
updateZPosRelative(pos);
}
@Override
public void onXYStagePositionChanged(String deviceName, double xPos, double yPos) {
if (deviceName.equals(xyStageLabel_)) {
updateXYPos(xPos, yPos);
for (MMListenerInterface mmIntf:MMListeners_) {
mmIntf.xyStagePositionChanged(deviceName, xPos, yPos);
}
}
}
@Override
public void onXYStagePositionChangedRelative(String deviceName, double xPos, double yPos) {
if (deviceName.equals(xyStageLabel_))
updateXYPosRelative(xPos, yPos);
}
}
private class PluginItem {
public Class<?> pluginClass = null;
public String menuItem = "undefined";
public MMPlugin plugin = null;
public String className = "";
public void instantiate() {
try {
if (plugin == null) {
plugin = (MMPlugin) pluginClass.newInstance();
}
} catch (InstantiationException e) {
ReportingUtils.logError(e);
} catch (IllegalAccessException e) {
ReportingUtils.logError(e);
}
plugin.setApp(MMStudioMainFrame.this);
}
}
/*
* Simple class used to cache static info
*/
private class StaticInfo {
public long width_;
public long height_;
public long bytesPerPixel_;
public long imageBitDepth_;
public double pixSizeUm_;
public double zPos_;
public double x_;
public double y_;
}
private StaticInfo staticInfo_ = new StaticInfo();
/**
* Main procedure for stand alone operation.
*/
public static void main(String args[]) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
MMStudioMainFrame frame = new MMStudioMainFrame(false);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
} catch (Throwable e) {
ReportingUtils.showError(e, "A java error has caused Micro-Manager to exit.");
System.exit(1);
}
}
public MMStudioMainFrame(boolean pluginStatus) {
super();
startLoadingPipelineClass();
options_ = new MMOptions();
try {
options_.loadSettings();
} catch (NullPointerException ex) {
ReportingUtils.logError(ex);
}
guiColors_ = new GUIColors();
plugins_ = new ArrayList<PluginItem>();
gui_ = this;
runsAsPlugin_ = pluginStatus;
setIconImage(SwingResourceManager.getImage(MMStudioMainFrame.class,
"icons/microscope.gif"));
running_ = true;
acqMgr_ = new AcquisitionManager();
sysConfigFile_ = System.getProperty("user.dir") + "/"
+ DEFAULT_CONFIG_FILE_NAME;
if (options_.startupScript_.length() > 0) {
startupScriptFile_ = System.getProperty("user.dir") + "/"
+ options_.startupScript_;
} else {
startupScriptFile_ = "";
}
ReportingUtils.SetContainingFrame(gui_);
// set the location for app preferences
try {
mainPrefs_ = Preferences.userNodeForPackage(this.getClass());
} catch (Exception e) {
ReportingUtils.logError(e);
}
systemPrefs_ = mainPrefs_;
colorPrefs_ = mainPrefs_.node(mainPrefs_.absolutePath() + "/" +
AcqControlDlg.COLOR_SETTINGS_NODE);
// check system preferences
try {
Preferences p = Preferences.systemNodeForPackage(this.getClass());
if (null != p) {
// if we can not write to the systemPrefs, use AppPrefs instead
if (JavaUtils.backingStoreAvailable(p)) {
systemPrefs_ = p;
}
}
} catch (Exception e) {
ReportingUtils.logError(e);
}
// show registration dialog if not already registered
// first check user preferences (for legacy compatibility reasons)
boolean userReg = mainPrefs_.getBoolean(RegistrationDlg.REGISTRATION,
false) || mainPrefs_.getBoolean(RegistrationDlg.REGISTRATION_NEVER, false);
if (!userReg) {
boolean systemReg = systemPrefs_.getBoolean(
RegistrationDlg.REGISTRATION, false) || systemPrefs_.getBoolean(RegistrationDlg.REGISTRATION_NEVER, false);
if (!systemReg) {
// prompt for registration info
RegistrationDlg dlg = new RegistrationDlg(systemPrefs_);
dlg.setVisible(true);
}
}
// load application preferences
// NOTE: only window size and position preferences are loaded,
// not the settings for the camera and live imaging -
// attempting to set those automatically on startup may cause problems
// with the hardware
int x = mainPrefs_.getInt(MAIN_FRAME_X, 100);
int y = mainPrefs_.getInt(MAIN_FRAME_Y, 100);
int width = mainPrefs_.getInt(MAIN_FRAME_WIDTH, 580);
int height = mainPrefs_.getInt(MAIN_FRAME_HEIGHT, 482);
int dividerPos = mainPrefs_.getInt(MAIN_FRAME_DIVIDER_POS, 178);
openAcqDirectory_ = mainPrefs_.get(OPEN_ACQ_DIR, "");
ToolTipManager ttManager = ToolTipManager.sharedInstance();
ttManager.setDismissDelay(TOOLTIP_DISPLAY_DURATION_MILLISECONDS);
ttManager.setInitialDelay(TOOLTIP_DISPLAY_INITIAL_DELAY_MILLISECONDS);
setBounds(x, y, width, height);
setExitStrategy(options_.closeOnExit_);
setTitle(MICRO_MANAGER_TITLE);
setBackground(guiColors_.background.get((options_.displayBackground_)));
SpringLayout topLayout = new SpringLayout();
this.setMinimumSize(new Dimension(580,480));
JPanel topPanel = new JPanel();
topPanel.setLayout(topLayout);
topPanel.setMinimumSize(new Dimension(580, 175));
class ListeningJPanel extends JPanel implements AncestorListener {
public void ancestorMoved(AncestorEvent event) {
//System.out.println("moved!");
}
public void ancestorRemoved(AncestorEvent event) {}
public void ancestorAdded(AncestorEvent event) {}
}
ListeningJPanel bottomPanel = new ListeningJPanel();
bottomPanel.setLayout(topLayout);
splitPane_ = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true,
topPanel, bottomPanel);
splitPane_.setBorder(BorderFactory.createEmptyBorder());
splitPane_.setDividerLocation(dividerPos);
splitPane_.setResizeWeight(0.0);
splitPane_.addAncestorListener(bottomPanel);
getContentPane().add(splitPane_);
// Snap button
buttonSnap_ = new JButton();
buttonSnap_.setIconTextGap(6);
buttonSnap_.setText("Snap");
buttonSnap_.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class, "/org/micromanager/icons/camera.png"));
buttonSnap_.setFont(new Font("Arial", Font.PLAIN, 10));
buttonSnap_.setToolTipText("Snap single image");
buttonSnap_.setMaximumSize(new Dimension(0, 0));
buttonSnap_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
doSnap();
}
});
topPanel.add(buttonSnap_);
topLayout.putConstraint(SpringLayout.SOUTH, buttonSnap_, 25,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, buttonSnap_, 4,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, buttonSnap_, 95,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, buttonSnap_, 7,
SpringLayout.WEST, topPanel);
// Initialize
// Exposure field
final JLabel label_1 = new JLabel();
label_1.setFont(new Font("Arial", Font.PLAIN, 10));
label_1.setText("Exposure [ms]");
topPanel.add(label_1);
topLayout.putConstraint(SpringLayout.EAST, label_1, 198,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, label_1, 111,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.SOUTH, label_1, 39,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, label_1, 23,
SpringLayout.NORTH, topPanel);
textFieldExp_ = new JTextField();
textFieldExp_.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent fe) {
synchronized(shutdownLock_) {
if (core_ != null)
setExposure();
}
}
});
textFieldExp_.setFont(new Font("Arial", Font.PLAIN, 10));
textFieldExp_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setExposure();
}
});
topPanel.add(textFieldExp_);
topLayout.putConstraint(SpringLayout.SOUTH, textFieldExp_, 40,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, textFieldExp_, 21,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, textFieldExp_, 276,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, textFieldExp_, 203,
SpringLayout.WEST, topPanel);
// Live button
toggleButtonLive_ = new JToggleButton();
toggleButtonLive_.setMargin(new Insets(2, 2, 2, 2));
toggleButtonLive_.setIconTextGap(1);
toggleButtonLive_.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class,
"/org/micromanager/icons/camera_go.png"));
toggleButtonLive_.setIconTextGap(6);
toggleButtonLive_.setToolTipText("Continuous live view");
toggleButtonLive_.setFont(new Font("Arial", Font.PLAIN, 10));
toggleButtonLive_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
enableLiveMode(!isLiveModeOn());
}
});
toggleButtonLive_.setText("Live");
topPanel.add(toggleButtonLive_);
topLayout.putConstraint(SpringLayout.SOUTH, toggleButtonLive_, 47,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, toggleButtonLive_, 26,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, toggleButtonLive_, 95,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, toggleButtonLive_, 7,
SpringLayout.WEST, topPanel);
// Acquire button
JButton acquireButton = new JButton();
acquireButton.setMargin(new Insets(2, 2, 2, 2));
acquireButton.setIconTextGap(1);
acquireButton.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class,
"/org/micromanager/icons/snapAppend.png"));
acquireButton.setIconTextGap(6);
acquireButton.setToolTipText("Acquire single frame and add to an album");
acquireButton.setFont(new Font("Arial", Font.PLAIN, 10));
acquireButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
snapAndAddToImage5D();
}
});
acquireButton.setText("Acquire");
topPanel.add(acquireButton);
topLayout.putConstraint(SpringLayout.SOUTH, acquireButton, 69,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, acquireButton, 48,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, acquireButton, 95,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, acquireButton, 7,
SpringLayout.WEST, topPanel);
// Shutter button
toggleButtonShutter_ = new JToggleButton();
toggleButtonShutter_.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
toggleShutter();
}
});
toggleButtonShutter_.setToolTipText("Open/close the shutter");
toggleButtonShutter_.setIconTextGap(6);
toggleButtonShutter_.setFont(new Font("Arial", Font.BOLD, 10));
toggleButtonShutter_.setText("Open");
topPanel.add(toggleButtonShutter_);
topLayout.putConstraint(SpringLayout.EAST, toggleButtonShutter_,
275, SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, toggleButtonShutter_,
203, SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.SOUTH, toggleButtonShutter_,
138 - 21, SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, toggleButtonShutter_,
117 - 21, SpringLayout.NORTH, topPanel);
// Active shutter label
final JLabel activeShutterLabel = new JLabel();
activeShutterLabel.setFont(new Font("Arial", Font.PLAIN, 10));
activeShutterLabel.setText("Shutter");
topPanel.add(activeShutterLabel);
topLayout.putConstraint(SpringLayout.SOUTH, activeShutterLabel,
108 - 22, SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, activeShutterLabel,
95 - 22, SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, activeShutterLabel,
160 - 2, SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, activeShutterLabel,
113 - 2, SpringLayout.WEST, topPanel);
// Active shutter Combo Box
shutterComboBox_ = new JComboBox();
shutterComboBox_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
if (shutterComboBox_.getSelectedItem() != null) {
core_.setShutterDevice((String) shutterComboBox_.getSelectedItem());
}
} catch (Exception e) {
ReportingUtils.showError(e);
}
return;
}
});
topPanel.add(shutterComboBox_);
topLayout.putConstraint(SpringLayout.SOUTH, shutterComboBox_,
114 - 22, SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, shutterComboBox_,
92 - 22, SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, shutterComboBox_, 275,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, shutterComboBox_, 170,
SpringLayout.WEST, topPanel);
menuBar_ = new JMenuBar();
setJMenuBar(menuBar_);
final JMenu fileMenu = new JMenu();
fileMenu.setText("File");
menuBar_.add(fileMenu);
final JMenuItem openMenuItem = new JMenuItem();
openMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
new Thread() {
@Override
public void run() {
openAcquisitionData();
}
}.start();
}
});
openMenuItem.setText("Open Acquisition Data...");
fileMenu.add(openMenuItem);
fileMenu.addSeparator();
final JMenuItem loadState = new JMenuItem();
loadState.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
loadSystemState();
}
});
loadState.setText("Load System State...");
fileMenu.add(loadState);
final JMenuItem saveStateAs = new JMenuItem();
fileMenu.add(saveStateAs);
saveStateAs.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
saveSystemState();
}
});
saveStateAs.setText("Save System State As...");
fileMenu.addSeparator();
final JMenuItem exitMenuItem = new JMenuItem();
exitMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
closeSequence();
}
});
fileMenu.add(exitMenuItem);
exitMenuItem.setText("Exit");
/*
final JMenu image5dMenu = new JMenu();
image5dMenu.setText("Image5D");
menuBar_.add(image5dMenu);
final JMenuItem closeAllMenuItem = new JMenuItem();
closeAllMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
WindowManager.closeAllWindows();
}
});
closeAllMenuItem.setText("Close All");
image5dMenu.add(closeAllMenuItem);
final JMenuItem duplicateMenuItem = new JMenuItem();
duplicateMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Duplicate_Image5D duplicate = new Duplicate_Image5D();
duplicate.run("");
}
});
duplicateMenuItem.setText("Duplicate");
image5dMenu.add(duplicateMenuItem);
final JMenuItem cropMenuItem = new JMenuItem();
cropMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Crop_Image5D crop = new Crop_Image5D();
crop.run("");
}
});
cropMenuItem.setText("Crop");
image5dMenu.add(cropMenuItem);
final JMenuItem makeMontageMenuItem = new JMenuItem();
makeMontageMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Make_Montage makeMontage = new Make_Montage();
makeMontage.run("");
}
});
makeMontageMenuItem.setText("Make Montage");
image5dMenu.add(makeMontageMenuItem);
final JMenuItem zProjectMenuItem = new JMenuItem();
zProjectMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Z_Project projection = new Z_Project();
projection.run("");
}
});
zProjectMenuItem.setText("Z Project");
image5dMenu.add(zProjectMenuItem);
final JMenuItem convertToRgbMenuItem = new JMenuItem();
convertToRgbMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Image5D_Stack_to_RGB stackToRGB = new Image5D_Stack_to_RGB();
stackToRGB.run("");
}
});
convertToRgbMenuItem.setText("Copy to RGB Stack(z)");
image5dMenu.add(convertToRgbMenuItem);
final JMenuItem convertToRgbtMenuItem = new JMenuItem();
convertToRgbtMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Image5D_Stack_to_RGB_t stackToRGB_t = new Image5D_Stack_to_RGB_t();
stackToRGB_t.run("");
}
});
convertToRgbtMenuItem.setText("Copy to RGB Stack(t)");
image5dMenu.add(convertToRgbtMenuItem);
final JMenuItem convertToStackMenuItem = new JMenuItem();
convertToStackMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Image5D_to_Stack image5DToStack = new Image5D_to_Stack();
image5DToStack.run("");
}
});
convertToStackMenuItem.setText("Copy to Stack");
image5dMenu.add(convertToStackMenuItem);
final JMenuItem convertToStacksMenuItem = new JMenuItem();
convertToStacksMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Image5D_Channels_to_Stacks image5DToStacks = new Image5D_Channels_to_Stacks();
image5DToStacks.run("");
}
});
convertToStacksMenuItem.setText("Copy to Stacks (channels)");
image5dMenu.add(convertToStacksMenuItem);
final JMenuItem volumeViewerMenuItem = new JMenuItem();
volumeViewerMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Image5D_to_VolumeViewer volumeViewer = new Image5D_to_VolumeViewer();
volumeViewer.run("");
}
});
volumeViewerMenuItem.setText("VolumeViewer");
image5dMenu.add(volumeViewerMenuItem);
final JMenuItem splitImageMenuItem = new JMenuItem();
splitImageMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Split_Image5D splitImage = new Split_Image5D();
splitImage.run("");
}
});
splitImageMenuItem.setText("SplitView");
image5dMenu.add(splitImageMenuItem);
*/
final JMenu toolsMenu = new JMenu();
toolsMenu.setText("Tools");
menuBar_.add(toolsMenu);
final JMenuItem refreshMenuItem = new JMenuItem();
refreshMenuItem.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class, "icons/arrow_refresh.png"));
refreshMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
core_.updateSystemStateCache();
updateGUI(true);
}
});
refreshMenuItem.setText("Refresh GUI");
refreshMenuItem.setToolTipText("Refresh all GUI controls directly from the hardware");
toolsMenu.add(refreshMenuItem);
final JMenuItem rebuildGuiMenuItem = new JMenuItem();
rebuildGuiMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
initializeGUI();
core_.updateSystemStateCache();
}
});
rebuildGuiMenuItem.setText("Rebuild GUI");
rebuildGuiMenuItem.setToolTipText("Regenerate micromanager user interface");
toolsMenu.add(rebuildGuiMenuItem);
toolsMenu.addSeparator();
final JMenuItem scriptPanelMenuItem = new JMenuItem();
toolsMenu.add(scriptPanelMenuItem);
scriptPanelMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
scriptPanel_.setVisible(true);
}
});
scriptPanelMenuItem.setText("Script Panel...");
scriptPanelMenuItem.setToolTipText("Open micromanager script editor window");
final JMenuItem hotKeysMenuItem = new JMenuItem();
toolsMenu.add(hotKeysMenuItem);
hotKeysMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
HotKeysDialog hk = new HotKeysDialog
(guiColors_.background.get((options_.displayBackground_)));
//hk.setBackground(guiColors_.background.get((options_.displayBackground_)));
}
});
hotKeysMenuItem.setText("Shortcuts...");
hotKeysMenuItem.setToolTipText("Create keyboard shortcuts to activate image acquisition, mark positions, or run custom scripts");
final JMenuItem propertyEditorMenuItem = new JMenuItem();
toolsMenu.add(propertyEditorMenuItem);
propertyEditorMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
createPropertyEditor();
}
});
propertyEditorMenuItem.setText("Device/Property Browser...");
propertyEditorMenuItem.setToolTipText("Open new window to view and edit property values in current configuration");
toolsMenu.addSeparator();
final JMenuItem xyListMenuItem = new JMenuItem();
xyListMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
showXYPositionList();
}
});
xyListMenuItem.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class, "icons/application_view_list.png"));
xyListMenuItem.setText("XY List...");
toolsMenu.add(xyListMenuItem);
xyListMenuItem.setToolTipText("Open position list manager window");
final JMenuItem acquisitionMenuItem = new JMenuItem();
acquisitionMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openAcqControlDialog();
}
});
acquisitionMenuItem.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class, "icons/film.png"));
acquisitionMenuItem.setText("Multi-Dimensional Acquisition...");
toolsMenu.add(acquisitionMenuItem);
acquisitionMenuItem.setToolTipText("Open multi-dimensional acquisition window");
/*
final JMenuItem splitViewMenuItem = new JMenuItem();
splitViewMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
splitViewDialog();
}
});
splitViewMenuItem.setText("Split View...");
toolsMenu.add(splitViewMenuItem);
*/
centerAndDragMenuItem_ = new JCheckBoxMenuItem();
centerAndDragMenuItem_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (centerAndDragListener_ == null) {
centerAndDragListener_ = new CenterAndDragListener(core_, gui_);
}
if (!centerAndDragListener_.isRunning()) {
centerAndDragListener_.start();
centerAndDragMenuItem_.setSelected(true);
} else {
centerAndDragListener_.stop();
centerAndDragMenuItem_.setSelected(false);
}
mainPrefs_.putBoolean(MOUSE_MOVES_STAGE, centerAndDragMenuItem_.isSelected());
}
});
centerAndDragMenuItem_.setText("Mouse Moves Stage");
centerAndDragMenuItem_.setSelected(mainPrefs_.getBoolean(MOUSE_MOVES_STAGE, false));
centerAndDragMenuItem_.setToolTipText("When enabled, double clicking in live window moves stage");
toolsMenu.add(centerAndDragMenuItem_);
final JMenuItem calibrationMenuItem = new JMenuItem();
toolsMenu.add(calibrationMenuItem);
calibrationMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
createCalibrationListDlg();
}
});
calibrationMenuItem.setText("Pixel Size Calibration...");
toolsMenu.add(calibrationMenuItem);
String calibrationTooltip = "Define size calibrations specific to each objective lens. " +
"When the objective in use has a calibration defined, " +
"micromanager will automatically use it when " +
"calculating metadata";
String mrjProp = System.getProperty("mrj.version");
if (mrjProp != null && !mrjProp.equals(null)) // running on a mac
calibrationMenuItem.setToolTipText(calibrationTooltip);
else
calibrationMenuItem.setToolTipText(TooltipTextMaker.addHTMLBreaksForTooltip(calibrationTooltip));
toolsMenu.addSeparator();
final JMenuItem configuratorMenuItem = new JMenuItem();
configuratorMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// true - new wizard
// false - old wizard
runHardwareWizard(true);
}
});
configuratorMenuItem.setText("Hardware Configuration Wizard...");
toolsMenu.add(configuratorMenuItem);
configuratorMenuItem.setToolTipText("Open wizard to create new hardware configuration");
final JMenuItem loadSystemConfigMenuItem = new JMenuItem();
toolsMenu.add(loadSystemConfigMenuItem);
loadSystemConfigMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
loadConfiguration();
initializeGUI();
}
});
loadSystemConfigMenuItem.setText("Load Hardware Configuration...");
loadSystemConfigMenuItem.setToolTipText("Un-initialize current configuration and initialize new one");
switchConfigurationMenu_ = new JMenu();
for (int i=0; i<5; i++)
{
JMenuItem configItem = new JMenuItem();
configItem.setText(Integer.toString(i));
switchConfigurationMenu_.add(configItem);
}
final JMenuItem reloadConfigMenuItem = new JMenuItem();
toolsMenu.add(reloadConfigMenuItem);
reloadConfigMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
loadSystemConfiguration();
initializeGUI();
}
});
reloadConfigMenuItem.setText("Reload Hardware Configuration");
reloadConfigMenuItem.setToolTipText("Un-initialize current configuration and initialize most recently loaded configuration");
switchConfigurationMenu_.setText("Switch Hardware Configuration");
toolsMenu.add(switchConfigurationMenu_);
switchConfigurationMenu_.setToolTipText("Switch between recently used configurations");
final JMenuItem saveConfigurationPresetsMenuItem = new JMenuItem();
saveConfigurationPresetsMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
saveConfigPresets();
updateChannelCombos();
}
});
saveConfigurationPresetsMenuItem.setText("Save Configuration Settings as...");
toolsMenu.add(saveConfigurationPresetsMenuItem);
saveConfigurationPresetsMenuItem.setToolTipText("Save current configuration settings as new configuration file");
/*
final JMenuItem regenerateConfiguratorDeviceListMenuItem = new JMenuItem();
regenerateConfiguratorDeviceListMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Cursor oldc = Cursor.getDefaultCursor();
Cursor waitc = new Cursor(Cursor.WAIT_CURSOR);
setCursor(waitc);
StringBuffer resultFile = new StringBuffer();
MicroscopeModel.generateDeviceListFile(options_.enableDeviceDiscovery_, resultFile,core_);
setCursor(oldc);
}
});
regenerateConfiguratorDeviceListMenuItem.setText("Regenerate Configurator Device List");
toolsMenu.add(regenerateConfiguratorDeviceListMenuItem);
*/
toolsMenu.addSeparator();
final MMStudioMainFrame thisInstance = this;
final JMenuItem optionsMenuItem = new JMenuItem();
optionsMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
int oldBufsize = options_.circularBufferSizeMB_;
OptionsDlg dlg = new OptionsDlg(options_, core_, mainPrefs_,
thisInstance, sysConfigFile_);
dlg.setVisible(true);
// adjust memory footprint if necessary
if (oldBufsize != options_.circularBufferSizeMB_) {
try {
core_.setCircularBufferMemoryFootprint(options_.circularBufferSizeMB_);
} catch (Exception exc) {
ReportingUtils.showError(exc);
}
}
}
});
optionsMenuItem.setText("Options...");
toolsMenu.add(optionsMenuItem);
final JLabel binningLabel = new JLabel();
binningLabel.setFont(new Font("Arial", Font.PLAIN, 10));
binningLabel.setText("Binning");
topPanel.add(binningLabel);
topLayout.putConstraint(SpringLayout.SOUTH, binningLabel, 64,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, binningLabel, 43,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, binningLabel, 200 - 1,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, binningLabel, 112 - 1,
SpringLayout.WEST, topPanel);
labelImageDimensions_ = new JLabel();
labelImageDimensions_.setFont(new Font("Arial", Font.PLAIN, 10));
bottomPanel.add(labelImageDimensions_);
topLayout.putConstraint(SpringLayout.SOUTH, labelImageDimensions_,
-5, SpringLayout.SOUTH, bottomPanel);
topLayout.putConstraint(SpringLayout.NORTH, labelImageDimensions_,
-25, SpringLayout.SOUTH, bottomPanel);
topLayout.putConstraint(SpringLayout.EAST, labelImageDimensions_,
-5, SpringLayout.EAST, bottomPanel);
topLayout.putConstraint(SpringLayout.WEST, labelImageDimensions_,
5, SpringLayout.WEST, bottomPanel);
comboBinning_ = new JComboBox();
comboBinning_.setFont(new Font("Arial", Font.PLAIN, 10));
comboBinning_.setMaximumRowCount(4);
comboBinning_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
changeBinning();
}
});
topPanel.add(comboBinning_);
topLayout.putConstraint(SpringLayout.EAST, comboBinning_, 275,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, comboBinning_, 200,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.SOUTH, comboBinning_, 66,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, comboBinning_, 43,
SpringLayout.NORTH, topPanel);
final JLabel cameraSettingsLabel = new JLabel();
cameraSettingsLabel.setFont(new Font("Arial", Font.BOLD, 11));
cameraSettingsLabel.setText("Camera settings");
topPanel.add(cameraSettingsLabel);
topLayout.putConstraint(SpringLayout.EAST, cameraSettingsLabel,
211, SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, cameraSettingsLabel, 6,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.WEST, cameraSettingsLabel,
109, SpringLayout.WEST, topPanel);
configPad_ = new ConfigGroupPad();
configPad_.setFont(new Font("", Font.PLAIN, 10));
topPanel.add(configPad_);
topLayout.putConstraint(SpringLayout.EAST, configPad_, -4,
SpringLayout.EAST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, configPad_, 5,
SpringLayout.EAST, comboBinning_);
topLayout.putConstraint(SpringLayout.SOUTH, configPad_, -21,
SpringLayout.SOUTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, configPad_, 21,
SpringLayout.NORTH, topPanel);
configPadButtonPanel_ = new ConfigPadButtonPanel();
configPadButtonPanel_.setConfigPad(configPad_);
configPadButtonPanel_.setGUI(MMStudioMainFrame.this);
topPanel.add(configPadButtonPanel_);
topLayout.putConstraint(SpringLayout.EAST, configPadButtonPanel_, -4,
SpringLayout.EAST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, configPadButtonPanel_, 5,
SpringLayout.EAST, comboBinning_);
topLayout.putConstraint(SpringLayout.SOUTH, configPadButtonPanel_, 0,
SpringLayout.SOUTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, configPadButtonPanel_, -18,
SpringLayout.SOUTH, topPanel);
final JLabel stateDeviceLabel = new JLabel();
stateDeviceLabel.setFont(new Font("Arial", Font.BOLD, 11));
stateDeviceLabel.setText("Configuration settings");
topPanel.add(stateDeviceLabel);
topLayout.putConstraint(SpringLayout.SOUTH, stateDeviceLabel, 0,
SpringLayout.SOUTH, cameraSettingsLabel);
topLayout.putConstraint(SpringLayout.NORTH, stateDeviceLabel, 0,
SpringLayout.NORTH, cameraSettingsLabel);
topLayout.putConstraint(SpringLayout.EAST, stateDeviceLabel, 150,
SpringLayout.WEST, configPad_);
topLayout.putConstraint(SpringLayout.WEST, stateDeviceLabel, 0,
SpringLayout.WEST, configPad_);
final JButton buttonAcqSetup = new JButton();
buttonAcqSetup.setMargin(new Insets(2, 2, 2, 2));
buttonAcqSetup.setIconTextGap(1);
buttonAcqSetup.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class, "/org/micromanager/icons/film.png"));
buttonAcqSetup.setToolTipText("Open multi-dimensional acquisition window");
buttonAcqSetup.setFont(new Font("Arial", Font.PLAIN, 10));
buttonAcqSetup.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openAcqControlDialog();
}
});
buttonAcqSetup.setText("Multi-D Acq.");
topPanel.add(buttonAcqSetup);
topLayout.putConstraint(SpringLayout.SOUTH, buttonAcqSetup, 91,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, buttonAcqSetup, 70,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, buttonAcqSetup, 95,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, buttonAcqSetup, 7,
SpringLayout.WEST, topPanel);
autoShutterCheckBox_ = new JCheckBox();
autoShutterCheckBox_.setFont(new Font("Arial", Font.PLAIN, 10));
autoShutterCheckBox_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
shutterLabel_ = core_.getShutterDevice();
if (shutterLabel_.length() == 0) {
toggleButtonShutter_.setEnabled(false);
return;
}
if (autoShutterCheckBox_.isSelected()) {
try {
core_.setAutoShutter(true);
core_.setShutterOpen(false);
toggleButtonShutter_.setSelected(false);
toggleButtonShutter_.setText("Open");
toggleButtonShutter_.setEnabled(false);
} catch (Exception e2) {
ReportingUtils.logError(e2);
}
} else {
try {
core_.setAutoShutter(false);
core_.setShutterOpen(false);
toggleButtonShutter_.setEnabled(true);
toggleButtonShutter_.setText("Open");
} catch (Exception exc) {
ReportingUtils.logError(exc);
}
}
}
});
autoShutterCheckBox_.setIconTextGap(6);
autoShutterCheckBox_.setHorizontalTextPosition(SwingConstants.LEADING);
autoShutterCheckBox_.setText("Auto shutter");
topPanel.add(autoShutterCheckBox_);
topLayout.putConstraint(SpringLayout.EAST, autoShutterCheckBox_,
202 - 3, SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, autoShutterCheckBox_,
110 - 3, SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.SOUTH, autoShutterCheckBox_,
141 - 22, SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, autoShutterCheckBox_,
118 - 22, SpringLayout.NORTH, topPanel);
final JButton refreshButton = new JButton();
refreshButton.setMargin(new Insets(2, 2, 2, 2));
refreshButton.setIconTextGap(1);
refreshButton.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class,
"/org/micromanager/icons/arrow_refresh.png"));
refreshButton.setFont(new Font("Arial", Font.PLAIN, 10));
refreshButton.setToolTipText("Refresh all GUI controls directly from the hardware");
refreshButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
core_.updateSystemStateCache();
updateGUI(true);
}
});
refreshButton.setText("Refresh");
topPanel.add(refreshButton);
topLayout.putConstraint(SpringLayout.SOUTH, refreshButton, 113,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, refreshButton, 92,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, refreshButton, 95,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, refreshButton, 7,
SpringLayout.WEST, topPanel);
JLabel citePleaLabel = new JLabel("<html>Please <a href=\"http://micro-manager.org\">cite Micro-Manager</a> so funding will continue!</html>");
topPanel.add(citePleaLabel);
citePleaLabel.setFont(new Font("Arial", Font.PLAIN, 11));
topLayout.putConstraint(SpringLayout.SOUTH, citePleaLabel, 139,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, citePleaLabel, 119,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, citePleaLabel, 270,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, citePleaLabel, 7,
SpringLayout.WEST, topPanel);
class Pleader extends Thread{
Pleader(){
super("pleader");
}
@Override
public void run(){
try {
ij.plugin.BrowserLauncher.openURL("https://valelab.ucsf.edu/~MM/MMwiki/index.php/Citing_Micro-Manager");
} catch (IOException e1) {
ReportingUtils.showError(e1);
}
}
}
citePleaLabel.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
Pleader p = new Pleader();
p.start();
}
});
// add window listeners
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
closeSequence();
}
@Override
public void windowOpened(WindowEvent e) {
// initialize hardware
try {
core_ = new CMMCore();
} catch(UnsatisfiedLinkError ex) {
ReportingUtils.showError(ex, "Failed to open libMMCoreJ_wrap.jnilib");
return;
}
ReportingUtils.setCore(core_);
//core_.setDeviceDiscoveryEnabled(options_.enableDeviceDiscovery_);
core_.enableDebugLog(options_.debugLogEnabled_);
core_.logMessage("MM Studio version: " + getVersion());
core_.logMessage(core_.getVersionInfo());
core_.logMessage(core_.getAPIVersionInfo());
core_.logMessage("Operating System: " + System.getProperty("os.name") + " " + System.getProperty("os.version"));
core_.logMessage("JVM: " + System.getProperty("java.vm.name")
+ ", version " + System.getProperty("java.version")
+ "; " + System.getProperty("sun.arch.data.model") + " bit");
cameraLabel_ = "";
shutterLabel_ = "";
zStageLabel_ = "";
xyStageLabel_ = "";
engine_ = new AcquisitionWrapperEngine();
// register callback for MMCore notifications, this is a global
// to avoid garbage collection
cb_ = new CoreEventCallback();
core_.registerCallback(cb_);
try {
core_.setCircularBufferMemoryFootprint(options_.circularBufferSizeMB_);
} catch (Exception e2) {
ReportingUtils.showError(e2);
}
MMStudioMainFrame parent = (MMStudioMainFrame) e.getWindow();
if (parent != null) {
engine_.setParentGUI(parent);
}
loadMRUConfigFiles();
initializePlugins();
toFront();
if (!options_.doNotAskForConfigFile_) {
MMIntroDlg introDlg = new MMIntroDlg(VERSION, MRUConfigFiles_);
introDlg.setConfigFile(sysConfigFile_);
introDlg.setBackground(guiColors_.background.get((options_.displayBackground_)));
introDlg.setVisible(true);
sysConfigFile_ = introDlg.getConfigFile();
}
saveMRUConfigFiles();
mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_);
paint(MMStudioMainFrame.this.getGraphics());
engine_.setCore(core_, afMgr_);
posList_ = new PositionList();
engine_.setPositionList(posList_);
// load (but do no show) the scriptPanel
createScriptPanel();
// Create an instance of HotKeys so that they can be read in from prefs
hotKeys_ = new org.micromanager.utils.HotKeys();
hotKeys_.loadSettings();
// if an error occurred during config loading,
// do not display more errors than needed
if (!loadSystemConfiguration())
ReportingUtils.showErrorOn(false);
executeStartupScript();
// Create Multi-D window here but do not show it.
// This window needs to be created in order to properly set the "ChannelGroup"
// based on the Multi-D parameters
acqControlWin_ = new AcqControlDlg(engine_, mainPrefs_, MMStudioMainFrame.this);
addMMBackgroundListener(acqControlWin_);
configPad_.setCore(core_);
if (parent != null) {
configPad_.setParentGUI(parent);
}
configPadButtonPanel_.setCore(core_);
// initialize controls
// initializeGUI(); Not needed since it is already called in loadSystemConfiguration
initializeHelpMenu();
String afDevice = mainPrefs_.get(AUTOFOCUS_DEVICE, "");
if (afMgr_.hasDevice(afDevice)) {
try {
afMgr_.selectDevice(afDevice);
} catch (MMException e1) {
// this error should never happen
ReportingUtils.showError(e1);
}
}
// switch error reporting back on
ReportingUtils.showErrorOn(true);
}
private void initializePlugins() {
pluginMenu_ = new JMenu();
pluginMenu_.setText("Plugins");
menuBar_.add(pluginMenu_);
new Thread("Plugin loading") {
@Override
public void run() {
// Needed for loading clojure-based jars:
Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
loadPlugins();
}
}.run();
}
});
final JButton setRoiButton = new JButton();
setRoiButton.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class,
"/org/micromanager/icons/shape_handles.png"));
setRoiButton.setFont(new Font("Arial", Font.PLAIN, 10));
setRoiButton.setToolTipText("Set Region Of Interest to selected rectangle");
setRoiButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setROI();
}
});
topPanel.add(setRoiButton);
topLayout.putConstraint(SpringLayout.EAST, setRoiButton, 37,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, setRoiButton, 7,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.SOUTH, setRoiButton, 174,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, setRoiButton, 154,
SpringLayout.NORTH, topPanel);
final JButton clearRoiButton = new JButton();
clearRoiButton.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class,
"/org/micromanager/icons/arrow_out.png"));
clearRoiButton.setFont(new Font("Arial", Font.PLAIN, 10));
clearRoiButton.setToolTipText("Reset Region of Interest to full frame");
clearRoiButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
clearROI();
}
});
topPanel.add(clearRoiButton);
topLayout.putConstraint(SpringLayout.EAST, clearRoiButton, 70,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, clearRoiButton, 40,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.SOUTH, clearRoiButton, 174,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, clearRoiButton, 154,
SpringLayout.NORTH, topPanel);
final JLabel regionOfInterestLabel = new JLabel();
regionOfInterestLabel.setFont(new Font("Arial", Font.BOLD, 11));
regionOfInterestLabel.setText("ROI");
topPanel.add(regionOfInterestLabel);
topLayout.putConstraint(SpringLayout.SOUTH, regionOfInterestLabel,
154, SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, regionOfInterestLabel,
140, SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, regionOfInterestLabel,
71, SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, regionOfInterestLabel,
8, SpringLayout.WEST, topPanel);
metadataPanel_ = new MetadataPanel();
bottomPanel.add(metadataPanel_);
topLayout.putConstraint(SpringLayout.SOUTH, metadataPanel_, -20,
SpringLayout.SOUTH, bottomPanel);
topLayout.putConstraint(SpringLayout.NORTH, metadataPanel_, 0,
SpringLayout.NORTH, bottomPanel);
topLayout.putConstraint(SpringLayout.EAST, metadataPanel_, 0,
SpringLayout.EAST, bottomPanel);
topLayout.putConstraint(SpringLayout.WEST, metadataPanel_, 0,
SpringLayout.WEST, bottomPanel);
metadataPanel_.setBorder(BorderFactory.createEmptyBorder());
final JLabel regionOfInterestLabel_1 = new JLabel();
regionOfInterestLabel_1.setFont(new Font("Arial", Font.BOLD, 11));
regionOfInterestLabel_1.setText("Zoom");
topPanel.add(regionOfInterestLabel_1);
topLayout.putConstraint(SpringLayout.SOUTH,
regionOfInterestLabel_1, 154, SpringLayout.NORTH,
topPanel);
topLayout.putConstraint(SpringLayout.NORTH,
regionOfInterestLabel_1, 140, SpringLayout.NORTH,
topPanel);
topLayout.putConstraint(SpringLayout.EAST, regionOfInterestLabel_1,
139, SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, regionOfInterestLabel_1,
81, SpringLayout.WEST, topPanel);
final JButton zoomInButton = new JButton();
zoomInButton.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
zoomIn();
}
});
zoomInButton.setIcon(SwingResourceManager.getIcon(MMStudioMainFrame.class,
"/org/micromanager/icons/zoom_in.png"));
zoomInButton.setToolTipText("Zoom in");
zoomInButton.setFont(new Font("Arial", Font.PLAIN, 10));
topPanel.add(zoomInButton);
topLayout.putConstraint(SpringLayout.SOUTH, zoomInButton, 174,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, zoomInButton, 154,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, zoomInButton, 110,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, zoomInButton, 80,
SpringLayout.WEST, topPanel);
final JButton zoomOutButton = new JButton();
zoomOutButton.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
zoomOut();
}
});
zoomOutButton.setIcon(SwingResourceManager.getIcon(MMStudioMainFrame.class,
"/org/micromanager/icons/zoom_out.png"));
zoomOutButton.setToolTipText("Zoom out");
zoomOutButton.setFont(new Font("Arial", Font.PLAIN, 10));
topPanel.add(zoomOutButton);
topLayout.putConstraint(SpringLayout.SOUTH, zoomOutButton, 174,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, zoomOutButton, 154,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, zoomOutButton, 143,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, zoomOutButton, 113,
SpringLayout.WEST, topPanel);
// Profile
final JLabel profileLabel_ = new JLabel();
profileLabel_.setFont(new Font("Arial", Font.BOLD, 11));
profileLabel_.setText("Profile");
topPanel.add(profileLabel_);
topLayout.putConstraint(SpringLayout.SOUTH, profileLabel_, 154,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, profileLabel_, 140,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, profileLabel_, 217,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, profileLabel_, 154,
SpringLayout.WEST, topPanel);
final JButton buttonProf = new JButton();
buttonProf.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class,
"/org/micromanager/icons/chart_curve.png"));
buttonProf.setFont(new Font("Arial", Font.PLAIN, 10));
buttonProf.setToolTipText("Open line profile window (requires line selection)");
buttonProf.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openLineProfileWindow();
}
});
// buttonProf.setText("Profile");
topPanel.add(buttonProf);
topLayout.putConstraint(SpringLayout.SOUTH, buttonProf, 174,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, buttonProf, 154,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, buttonProf, 183,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, buttonProf, 153,
SpringLayout.WEST, topPanel);
// Autofocus
final JLabel autofocusLabel_ = new JLabel();
autofocusLabel_.setFont(new Font("Arial", Font.BOLD, 11));
autofocusLabel_.setText("Autofocus");
topPanel.add(autofocusLabel_);
topLayout.putConstraint(SpringLayout.SOUTH, autofocusLabel_, 154,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, autofocusLabel_, 140,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, autofocusLabel_, 274,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, autofocusLabel_, 194,
SpringLayout.WEST, topPanel);
buttonAutofocus_ = new JButton();
buttonAutofocus_.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class,
"/org/micromanager/icons/find.png"));
buttonAutofocus_.setFont(new Font("Arial", Font.PLAIN, 10));
buttonAutofocus_.setToolTipText("Autofocus now");
buttonAutofocus_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (afMgr_.getDevice() != null) {
new Thread() {
@Override
public void run() {
try {
boolean lmo = isLiveModeOn();
if(lmo)
enableLiveMode(false);
afMgr_.getDevice().fullFocus();
if(lmo)
enableLiveMode(true);
} catch (MMException ex) {
ReportingUtils.logError(ex);
}
}
}.start(); // or any other method from Autofocus.java API
}
}
});
topPanel.add(buttonAutofocus_);
topLayout.putConstraint(SpringLayout.SOUTH, buttonAutofocus_, 174,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, buttonAutofocus_, 154,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, buttonAutofocus_, 223,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, buttonAutofocus_, 193,
SpringLayout.WEST, topPanel);
buttonAutofocusTools_ = new JButton();
buttonAutofocusTools_.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class,
"/org/micromanager/icons/wrench_orange.png"));
buttonAutofocusTools_.setFont(new Font("Arial", Font.PLAIN, 10));
buttonAutofocusTools_.setToolTipText("Set autofocus options");
buttonAutofocusTools_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showAutofocusDialog();
}
});
topPanel.add(buttonAutofocusTools_);
topLayout.putConstraint(SpringLayout.SOUTH, buttonAutofocusTools_, 174,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, buttonAutofocusTools_, 154,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, buttonAutofocusTools_, 256,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, buttonAutofocusTools_, 226,
SpringLayout.WEST, topPanel);
saveConfigButton_ = new JButton();
saveConfigButton_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
saveConfigPresets();
}
});
saveConfigButton_.setToolTipText("Save current presets to the configuration file");
saveConfigButton_.setText("Save");
saveConfigButton_.setEnabled(false);
topPanel.add(saveConfigButton_);
topLayout.putConstraint(SpringLayout.SOUTH, saveConfigButton_, 20,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, saveConfigButton_, 2,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, saveConfigButton_, -5,
SpringLayout.EAST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, saveConfigButton_, -80,
SpringLayout.EAST, topPanel);
// Add our own keyboard manager that handles Micro-Manager shortcuts
MMKeyDispatcher mmKD = new MMKeyDispatcher(gui_);
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(mmKD);
}
private void handleException(Exception e, String msg) {
String errText = "Exception occurred: ";
if (msg.length() > 0) {
errText += msg + "
}
if (options_.debugLogEnabled_) {
errText += e.getMessage();
} else {
errText += e.toString() + "\n";
ReportingUtils.showError(e);
}
handleError(errText);
}
private void handleException(Exception e) {
handleException(e, "");
}
private void handleError(String message) {
if (isLiveModeOn()) {
// Should we always stop live mode on any error?
enableLiveMode(false);
}
JOptionPane.showMessageDialog(this, message);
core_.logMessage(message);
}
public void makeActive() {
toFront();
}
private void setExposure() {
try {
core_.setExposure(NumberUtils.displayStringToDouble(textFieldExp_.getText()));
// Display the new exposure time
double exposure = core_.getExposure();
textFieldExp_.setText(NumberUtils.doubleToDisplayString(exposure));
} catch (Exception exp) {
// Do nothing.
}
}
public boolean getConserveRamOption() {
return options_.conserveRam_;
}
public boolean getAutoreloadOption() {
return options_.autoreloadDevices_;
}
private void updateTitle() {
this.setTitle("System: " + sysConfigFile_);
}
public void updateLineProfile() {
if (WindowManager.getCurrentWindow() == null || profileWin_ == null
|| !profileWin_.isShowing()) {
return;
}
calculateLineProfileData(WindowManager.getCurrentImage());
profileWin_.setData(lineProfileData_);
}
private void openLineProfileWindow() {
if (WindowManager.getCurrentWindow() == null || WindowManager.getCurrentWindow().isClosed()) {
return;
}
calculateLineProfileData(WindowManager.getCurrentImage());
if (lineProfileData_ == null) {
return;
}
profileWin_ = new GraphFrame();
profileWin_.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
profileWin_.setData(lineProfileData_);
profileWin_.setAutoScale();
profileWin_.setTitle("Live line profile");
profileWin_.setBackground(guiColors_.background.get((options_.displayBackground_)));
addMMBackgroundListener(profileWin_);
profileWin_.setVisible(true);
}
public Rectangle getROI() throws MMScriptException {
// ROI values are given as x,y,w,h in individual one-member arrays (pointers in C++):
int[][] a = new int[4][1];
try {
core_.getROI(a[0], a[1], a[2], a[3]);
} catch (Exception e) {
throw new MMScriptException(e.getMessage());
}
// Return as a single array with x,y,w,h:
return new Rectangle(a[0][0], a[1][0], a[2][0], a[3][0]);
}
private void calculateLineProfileData(ImagePlus imp) {
// generate line profile
Roi roi = imp.getRoi();
if (roi == null || !roi.isLine()) {
// if there is no line ROI, create one
Rectangle r = imp.getProcessor().getRoi();
int iWidth = r.width;
int iHeight = r.height;
int iXROI = r.x;
int iYROI = r.y;
if (roi == null) {
iXROI += iWidth / 2;
iYROI += iHeight / 2;
}
roi = new Line(iXROI - iWidth / 4, iYROI - iWidth / 4, iXROI
+ iWidth / 4, iYROI + iHeight / 4);
imp.setRoi(roi);
roi = imp.getRoi();
}
ImageProcessor ip = imp.getProcessor();
ip.setInterpolate(true);
Line line = (Line) roi;
if (lineProfileData_ == null) {
lineProfileData_ = new GraphData();
}
lineProfileData_.setData(line.getPixels());
}
public void setROI(Rectangle r) throws MMScriptException {
boolean liveRunning = false;
if (isLiveModeOn()) {
liveRunning = true;
enableLiveMode(false);
}
try {
core_.setROI(r.x, r.y, r.width, r.height);
} catch (Exception e) {
throw new MMScriptException(e.getMessage());
}
updateStaticInfo();
if (liveRunning) {
enableLiveMode(true);
}
}
private void setROI() {
ImagePlus curImage = WindowManager.getCurrentImage();
if (curImage == null) {
return;
}
Roi roi = curImage.getRoi();
try {
if (roi == null) {
// if there is no ROI, create one
Rectangle r = curImage.getProcessor().getRoi();
int iWidth = r.width;
int iHeight = r.height;
int iXROI = r.x;
int iYROI = r.y;
if (roi == null) {
iWidth /= 2;
iHeight /= 2;
iXROI += iWidth / 2;
iYROI += iHeight / 2;
}
curImage.setRoi(iXROI, iYROI, iWidth, iHeight);
roi = curImage.getRoi();
}
if (roi.getType() != Roi.RECTANGLE) {
handleError("ROI must be a rectangle.\nUse the ImageJ rectangle tool to draw the ROI.");
return;
}
Rectangle r = roi.getBoundingRect();
// if we already had an ROI defined, correct for the offsets
Rectangle cameraR = getROI();
r.x += cameraR.x;
r.y += cameraR.y;
// Stop (and restart) live mode if it is running
setROI(r);
} catch (Exception e) {
ReportingUtils.showError(e);
}
}
private void clearROI() {
try {
boolean liveRunning = false;
if (isLiveModeOn()) {
liveRunning = true;
enableLiveMode(false);
}
core_.clearROI();
updateStaticInfo();
if (liveRunning) {
enableLiveMode(true);
}
} catch (Exception e) {
ReportingUtils.showError(e);
}
}
/**
* Returns instance of the core uManager object;
*/
public CMMCore getMMCore() {
return core_;
}
/**
* Returns singleton instance of MMStudioMainFrame
*/
public static MMStudioMainFrame getInstance() {
return gui_;
}
public MetadataPanel getMetadataPanel() {
return metadataPanel_;
}
public final void setExitStrategy(boolean closeOnExit) {
if (closeOnExit)
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
else
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
public void saveConfigPresets() {
MicroscopeModel model = new MicroscopeModel();
try {
model.loadFromFile(sysConfigFile_);
model.createSetupConfigsFromHardware(core_);
model.createResolutionsFromHardware(core_);
File f = FileDialogs.save(this, "Save the configuration file", MM_CONFIG_FILE);
if (f != null) {
model.saveToFile(f.getAbsolutePath());
sysConfigFile_ = f.getAbsolutePath();
mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_);
configChanged_ = false;
setConfigSaveButtonStatus(configChanged_);
updateTitle();
}
} catch (MMConfigFileException e) {
ReportingUtils.showError(e);
}
}
protected void setConfigSaveButtonStatus(boolean changed) {
saveConfigButton_.setEnabled(changed);
}
public String getAcqDirectory() {
return openAcqDirectory_;
}
public void setAcqDirectory(String dir) {
openAcqDirectory_ = dir;
}
/**
* Open an existing acquisition directory and build viewer window.
*
*/
public void openAcquisitionData() {
// choose the directory
File f = FileDialogs.openDir(this, "Please select an image data set", MM_DATA_SET);
if (f != null) {
if (f.isDirectory()) {
openAcqDirectory_ = f.getAbsolutePath();
} else {
openAcqDirectory_ = f.getParent();
}
openAcquisitionData(openAcqDirectory_);
}
}
public void openAcquisitionData(String dir) {
String rootDir = new File(dir).getAbsolutePath();
String name = new File(dir).getName();
rootDir= rootDir.substring(0, rootDir.length() - (name.length() + 1));
try {
acqMgr_.openAcquisition(name, rootDir, true, true, true);
acqMgr_.getAcquisition(name).initialize();
acqMgr_.closeAcquisition(name);
} catch (MMScriptException ex) {
ReportingUtils.showError(ex);
}
}
protected void zoomOut() {
ImageWindow curWin = WindowManager.getCurrentWindow();
if (curWin != null) {
ImageCanvas canvas = curWin.getCanvas();
Rectangle r = canvas.getBounds();
canvas.zoomOut(r.width / 2, r.height / 2);
}
}
protected void zoomIn() {
ImageWindow curWin = WindowManager.getCurrentWindow();
if (curWin != null) {
ImageCanvas canvas = curWin.getCanvas();
Rectangle r = canvas.getBounds();
canvas.zoomIn(r.width / 2, r.height / 2);
}
}
protected void changeBinning() {
try {
boolean liveRunning = false;
if (isLiveModeOn() ) {
liveRunning = true;
enableLiveMode(false);
}
if (isCameraAvailable()) {
Object item = comboBinning_.getSelectedItem();
if (item != null) {
core_.setProperty(cameraLabel_, MMCoreJ.getG_Keyword_Binning(), item.toString());
}
}
updateStaticInfo();
if (liveRunning) {
enableLiveMode(true);
}
} catch (Exception e) {
ReportingUtils.showError(e);
}
}
private void createPropertyEditor() {
if (propertyBrowser_ != null) {
propertyBrowser_.dispose();
}
propertyBrowser_ = new PropertyEditor();
propertyBrowser_.setGui(this);
propertyBrowser_.setVisible(true);
propertyBrowser_.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
propertyBrowser_.setCore(core_);
}
private void createCalibrationListDlg() {
if (calibrationListDlg_ != null) {
calibrationListDlg_.dispose();
}
calibrationListDlg_ = new CalibrationListDlg(core_);
calibrationListDlg_.setVisible(true);
calibrationListDlg_.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
calibrationListDlg_.setParentGUI(this);
}
public CalibrationListDlg getCalibrationListDlg() {
if (calibrationListDlg_ == null) {
createCalibrationListDlg();
}
return calibrationListDlg_;
}
private void createScriptPanel() {
if (scriptPanel_ == null) {
scriptPanel_ = new ScriptPanel(core_, options_, this);
scriptPanel_.insertScriptingObject(SCRIPT_CORE_OBJECT, core_);
scriptPanel_.insertScriptingObject(SCRIPT_ACQENG_OBJECT, engine_);
scriptPanel_.setParentGUI(this);
scriptPanel_.setBackground(guiColors_.background.get((options_.displayBackground_)));
addMMBackgroundListener(scriptPanel_);
}
}
/**
* Updates Status line in main window from cached values
*/
private void updateStaticInfoFromCache() {
String dimText = "Image size: " + staticInfo_.width_ + " X " + staticInfo_.height_ + " X "
+ staticInfo_.bytesPerPixel_ + ", Intensity range: " + staticInfo_.imageBitDepth_ + " bits";
dimText += ", " + TextUtils.FMT0.format(staticInfo_.pixSizeUm_ * 1000) + "nm/pix";
if (zStageLabel_.length() > 0) {
dimText += ", Z=" + TextUtils.FMT2.format(staticInfo_.zPos_) + "um";
}
if (xyStageLabel_.length() > 0) {
dimText += ", XY=(" + TextUtils.FMT2.format(staticInfo_.x_) + "," + TextUtils.FMT2.format(staticInfo_.y_) + ")um";
}
labelImageDimensions_.setText(dimText);
}
public void updateXYPos(double x, double y) {
staticInfo_.x_ = x;
staticInfo_.y_ = y;
updateStaticInfoFromCache();
}
public void updateZPos(double z) {
staticInfo_.zPos_ = z;
updateStaticInfoFromCache();
}
public void updateXYPosRelative(double x, double y) {
staticInfo_.x_ += x;
staticInfo_.y_ += y;
updateStaticInfoFromCache();
}
public void updateZPosRelative(double z) {
staticInfo_.zPos_ += z;
updateStaticInfoFromCache();
}
public void updateXYStagePosition(){
double x[] = new double[1];
double y[] = new double[1];
try {
if (xyStageLabel_.length() > 0)
core_.getXYPosition(xyStageLabel_, x, y);
} catch (Exception e) {
ReportingUtils.showError(e);
}
staticInfo_.x_ = x[0];
staticInfo_.y_ = y[0];
updateStaticInfoFromCache();
}
private void updatePixSizeUm (double pixSizeUm) {
staticInfo_.pixSizeUm_ = pixSizeUm;
updateStaticInfoFromCache();
}
private void updateStaticInfo() {
double zPos = 0.0;
double x[] = new double[1];
double y[] = new double[1];
try {
if (zStageLabel_.length() > 0) {
zPos = core_.getPosition(zStageLabel_);
}
if (xyStageLabel_.length() > 0) {
core_.getXYPosition(xyStageLabel_, x, y);
}
} catch (Exception e) {
handleException(e);
}
staticInfo_.width_ = core_.getImageWidth();
staticInfo_.height_ = core_.getImageHeight();
staticInfo_.bytesPerPixel_ = core_.getBytesPerPixel();
staticInfo_.imageBitDepth_ = core_.getImageBitDepth();
staticInfo_.pixSizeUm_ = core_.getPixelSizeUm();
staticInfo_.zPos_ = zPos;
staticInfo_.x_ = x[0];
staticInfo_.y_ = y[0];
updateStaticInfoFromCache();
}
public void toggleShutter() {
try {
if (!toggleButtonShutter_.isEnabled())
return;
toggleButtonShutter_.requestFocusInWindow();
if (toggleButtonShutter_.getText().equals("Open")) {
setShutterButton(true);
core_.setShutterOpen(true);
} else {
core_.setShutterOpen(false);
setShutterButton(false);
}
} catch (Exception e1) {
ReportingUtils.showError(e1);
}
}
private void setShutterButton(boolean state) {
if (state) {
// toggleButtonShutter_.setSelected(true);
toggleButtonShutter_.setText("Close");
} else {
// toggleButtonShutter_.setSelected(false);
toggleButtonShutter_.setText("Open");
}
}
// public interface available for scripting access
public void snapSingleImage() {
doSnap();
}
public Object getPixels() {
ImagePlus ip = WindowManager.getCurrentImage();
if (ip != null) {
return ip.getProcessor().getPixels();
}
return null;
}
public void setPixels(Object obj) {
ImagePlus ip = WindowManager.getCurrentImage();
if (ip == null) {
return;
}
ip.getProcessor().setPixels(obj);
}
public int getImageHeight() {
ImagePlus ip = WindowManager.getCurrentImage();
if (ip != null)
return ip.getHeight();
return 0;
}
public int getImageWidth() {
ImagePlus ip = WindowManager.getCurrentImage();
if (ip != null)
return ip.getWidth();
return 0;
}
public int getImageDepth() {
ImagePlus ip = WindowManager.getCurrentImage();
if (ip != null)
return ip.getBitDepth();
return 0;
}
public ImageProcessor getImageProcessor() {
ImagePlus ip = WindowManager.getCurrentImage();
if (ip == null)
return null;
return ip.getProcessor();
}
private boolean isCameraAvailable() {
return cameraLabel_.length() > 0;
}
/**
* Part of ScriptInterface API
* Opens the XYPositionList when it is not opened
* Adds the current position to the list (same as pressing the "Mark" button)
*/
public void markCurrentPosition() {
if (posListDlg_ == null) {
showXYPositionList();
}
if (posListDlg_ != null) {
posListDlg_.markPosition();
}
}
/**
* Implements ScriptInterface
*/
public AcqControlDlg getAcqDlg() {
return acqControlWin_;
}
/**
* Implements ScriptInterface
*/
public PositionListDlg getXYPosListDlg() {
if (posListDlg_ == null)
posListDlg_ = new PositionListDlg(core_, this, posList_, options_);
return posListDlg_;
}
/**
* Implements ScriptInterface
*/
public boolean isAcquisitionRunning() {
if (engine_ == null)
return false;
return engine_.isAcquisitionRunning();
}
/**
* Implements ScriptInterface
*/
public boolean versionLessThan(String version) throws MMScriptException {
try {
String[] v = VERSION.split(" ", 2);
String[] m = v[0].split("\\.", 3);
String[] v2 = version.split(" ", 2);
String[] m2 = v2[0].split("\\.", 3);
for (int i=0; i < 3; i++) {
if (Integer.parseInt(m[i]) < Integer.parseInt(m2[i])) {
ReportingUtils.showError("This code needs Micro-Manager version " + version + " or greater");
return true;
}
if (Integer.parseInt(m[i]) > Integer.parseInt(m2[i])) {
return false;
}
}
if (v2.length < 2 || v2[1].equals("") )
return false;
if (v.length < 2 ) {
ReportingUtils.showError("This code needs Micro-Manager version " + version + " or greater");
return true;
}
if (Integer.parseInt(v[1]) < Integer.parseInt(v2[1])) {
ReportingUtils.showError("This code needs Micro-Manager version " + version + " or greater");
return false;
}
return true;
} catch (Exception ex) {
throw new MMScriptException ("Format of version String should be \"a.b.c\"");
}
}
public boolean isLiveModeOn() {
return liveModeTimer_ != null && liveModeTimer_.isRunning();
}
public void enableLiveMode(boolean enable) {
if (core_ == null)
return;
if (enable == isLiveModeOn())
return;
if (enable) {
try {
checkSimpleAcquisition();
if (liveModeTimer_ == null)
liveModeTimer_ = new LiveModeTimer(33);
manageShutterLiveMode(enable);
liveModeTimer_.start();
enableLiveModeListeners(enable);
} catch (Exception ex) {
enableLiveMode(false);
ReportingUtils.logError(ex);
}
} else {
try {
liveModeTimer_.stop();
manageShutterLiveMode(enable);
enableLiveModeListeners(enable);
} catch (Exception ex) {
ReportingUtils.logError(ex);
}
}
updateButtonsForLiveMode(enable);
}
private void manageShutterLiveMode(boolean enable) throws Exception {
shutterLabel_ = core_.getShutterDevice();
if (shutterLabel_.length() > 0) {
if (enable) {
shutterOriginalState_ = core_.getShutterOpen();
autoShutterOriginalState_ = core_.getAutoShutter();
core_.setAutoShutter(false);
core_.setShutterOpen(true);
} else {
core_.setShutterOpen(shutterOriginalState_);
core_.setAutoShutter(autoShutterOriginalState_);
}
}
}
public void updateButtonsForLiveMode(boolean enable) {
toggleButtonShutter_.setEnabled(!enable);
autoShutterCheckBox_.setEnabled(!enable);
buttonSnap_.setEnabled(!enable);
toggleButtonLive_.setIcon(enable ? SwingResourceManager.getIcon(MMStudioMainFrame.class,
"/org/micromanager/icons/cancel.png")
: SwingResourceManager.getIcon(MMStudioMainFrame.class,
"/org/micromanager/icons/camera_go.png"));
toggleButtonLive_.setSelected(enable);
toggleButtonLive_.setText(enable ? "Stop Live" : "Live");
}
private void enableLiveModeListeners(boolean enable) {
if (enable) {
// attach mouse wheel listener to control focus:
if (zWheelListener_ == null)
zWheelListener_ = new ZWheelListener(core_, this);
zWheelListener_.start(getImageWin());
// attach key listener to control the stage and focus:
if (xyzKeyListener_ == null)
xyzKeyListener_ = new XYZKeyListener(core_, this);
xyzKeyListener_.start(getImageWin());
if (centerAndDragListener_ == null)
centerAndDragListener_ = new CenterAndDragListener(core_, this);
centerAndDragListener_.start();
} else {
if (zWheelListener_ != null)
zWheelListener_.stop();
if (xyzKeyListener_ != null)
xyzKeyListener_.stop();
if (centerAndDragListener_ != null)
centerAndDragListener_.stop();
}
}
public boolean getLiveMode() {
return isLiveModeOn();
}
public boolean updateImage() {
try {
if (isLiveModeOn()) {
enableLiveMode(false);
return true; // nothing to do, just show the last image
}
if (WindowManager.getCurrentWindow() == null) {
return false;
}
ImagePlus ip = WindowManager.getCurrentImage();
core_.snapImage();
Object img = core_.getImage();
ip.getProcessor().setPixels(img);
ip.updateAndRepaintWindow();
if (!isCurrentImageFormatSupported()) {
return false;
}
updateLineProfile();
} catch (Exception e) {
ReportingUtils.showError(e);
return false;
}
return true;
}
public boolean displayImage(final Object pixels) {
return displayImage(pixels, true);
}
public boolean displayImage(final Object pixels, boolean wait) {
try {
ImagePlus ip = WindowManager.getCurrentImage();
if (ip == null || !(ip instanceof VirtualAcquisitionDisplay.MMImagePlus
|| ip instanceof VirtualAcquisitionDisplay.MMCompositeImage)) {
return false;
}
VirtualAcquisitionDisplay virtAcq;
if (ip instanceof VirtualAcquisitionDisplay.MMImagePlus)
virtAcq = ((VirtualAcquisitionDisplay.MMImagePlus) ip).display_;
else
virtAcq = ((VirtualAcquisitionDisplay.MMCompositeImage) ip).display_;
JSONObject tags = virtAcq.getImageCache().getLastImageTags();
int width = MDUtils.getWidth(tags);
int height = MDUtils.getHeight(tags);
int depth = MDUtils.getBitDepth(tags);
if (height != core_.getImageHeight() || width != core_.getImageWidth() ||
depth != core_.getImageBitDepth())
return false;
TaggedImage ti = ImageUtils.makeTaggedImage(pixels, 0, 0, 0,0, width, height, depth);
virtAcq.getImageCache().putImage(ti);
virtAcq.showImage(ti, wait);
return true;
} catch (Exception ex) {
Logger.getLogger(MMStudioMainFrame.class.getName()).log(Level.SEVERE, null, ex);
return false;
}
}
public boolean displayImageWithStatusLine(Object pixels, String statusLine) {
try {
ImagePlus ip = WindowManager.getCurrentImage();
if (ip == null || !(ip instanceof VirtualAcquisitionDisplay.MMImagePlus
|| ip instanceof VirtualAcquisitionDisplay.MMCompositeImage)) {
return false;
}
VirtualAcquisitionDisplay virtAcq;
if (ip instanceof VirtualAcquisitionDisplay.MMImagePlus)
virtAcq = ((VirtualAcquisitionDisplay.MMImagePlus) ip).display_;
else
virtAcq = ((VirtualAcquisitionDisplay.MMCompositeImage) ip).display_;
JSONObject tags = virtAcq.getImageCache().getLastImageTags();
int width = MDUtils.getWidth(tags);
int height = MDUtils.getHeight(tags);
int depth = MDUtils.getBitDepth(tags);
if (height != core_.getImageHeight() || width != core_.getImageWidth() ||
depth != core_.getImageBitDepth())
return false;
TaggedImage ti = ImageUtils.makeTaggedImage(pixels, 0, 0, 0,0, width, height, depth);
virtAcq.getImageCache().putImage(ti);
virtAcq.showImage(ti);
virtAcq.displayStatusLine(statusLine);
return true;
} catch (Exception ex) {
ReportingUtils.logError(ex);
return false;
}
}
public void displayStatusLine(String statusLine) {
ImagePlus ip = WindowManager.getCurrentImage();
VirtualAcquisitionDisplay virtAcq;
if (ip instanceof VirtualAcquisitionDisplay.MMImagePlus )
virtAcq = ((VirtualAcquisitionDisplay.MMImagePlus) ip).display_;
else if (ip instanceof VirtualAcquisitionDisplay.MMCompositeImage)
virtAcq = ((VirtualAcquisitionDisplay.MMCompositeImage) ip).display_;
else
return;
virtAcq.displayStatusLine(statusLine);
}
private boolean isCurrentImageFormatSupported() {
boolean ret = false;
long channels = core_.getNumberOfComponents();
long bpp = core_.getBytesPerPixel();
if (channels > 1 && channels != 4 && bpp != 1) {
handleError("Unsupported image format.");
} else {
ret = true;
}
return ret;
}
public void doSnap() {
checkSimpleAcquisition();
try {
setCursor(new Cursor(Cursor.WAIT_CURSOR));
core_.snapImage();
getAcquisition(SIMPLE_ACQ).toFront();
long c = core_.getNumberOfCameraChannels();
for (int i = 0; i < c; i++) {
TaggedImage ti = ImageUtils.makeTaggedImage(core_.getImage(i),
i, 0, 0, 0,
getAcquisitionImageWidth(SIMPLE_ACQ),
getAcquisitionImageHeight(SIMPLE_ACQ),
getAcquisitionImageByteDepth(SIMPLE_ACQ));
boolean update = false;
if (i == c - 1)
update = true;
addImage(SIMPLE_ACQ, ti, update, true);
}
} catch (Exception ex) {
ReportingUtils.showError(ex);
}
setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}
public void initializeGUI() {
try {
// establish device roles
cameraLabel_ = core_.getCameraDevice();
shutterLabel_ = core_.getShutterDevice();
zStageLabel_ = core_.getFocusDevice();
xyStageLabel_ = core_.getXYStageDevice();
engine_.setZStageDevice(zStageLabel_);
if (cameraLabel_.length() > 0) {
ActionListener[] listeners;
// binning combo
if (comboBinning_.getItemCount() > 0) {
comboBinning_.removeAllItems();
}
StrVector binSizes = core_.getAllowedPropertyValues(
cameraLabel_, MMCoreJ.getG_Keyword_Binning());
listeners = comboBinning_.getActionListeners();
for (int i = 0; i < listeners.length; i++) {
comboBinning_.removeActionListener(listeners[i]);
}
for (int i = 0; i < binSizes.size(); i++) {
comboBinning_.addItem(binSizes.get(i));
}
comboBinning_.setMaximumRowCount((int) binSizes.size());
if (binSizes.size() == 0) {
comboBinning_.setEditable(true);
} else {
comboBinning_.setEditable(false);
}
for (int i = 0; i < listeners.length; i++) {
comboBinning_.addActionListener(listeners[i]);
}
}
// active shutter combo
try {
shutters_ = core_.getLoadedDevicesOfType(DeviceType.ShutterDevice);
} catch (Exception e) {
ReportingUtils.logError(e);
}
if (shutters_ != null) {
String items[] = new String[(int) shutters_.size()];
for (int i = 0; i < shutters_.size(); i++) {
items[i] = shutters_.get(i);
}
GUIUtils.replaceComboContents(shutterComboBox_, items);
String activeShutter = core_.getShutterDevice();
if (activeShutter != null) {
shutterComboBox_.setSelectedItem(activeShutter);
} else {
shutterComboBox_.setSelectedItem("");
}
}
// Autofocus
buttonAutofocusTools_.setEnabled(afMgr_.getDevice() != null);
buttonAutofocus_.setEnabled(afMgr_.getDevice() != null);
// Rebuild stage list in XY PositinList
if (posListDlg_ != null) {
posListDlg_.rebuildAxisList();
}
updateGUI(true);
} catch (Exception e) {
ReportingUtils.showError(e);
}
}
public String getVersion() {
return VERSION;
}
private void addPluginToMenu(final PluginItem plugin, Class<?> cl) {
// add plugin menu items
final JMenuItem newMenuItem = new JMenuItem();
newMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
ReportingUtils.logMessage("Plugin command: "
+ e.getActionCommand());
plugin.instantiate();
plugin.plugin.show();
}
});
newMenuItem.setText(plugin.menuItem);
String toolTipDescription = "";
try {
// Get this static field from the class implementing MMPlugin.
toolTipDescription = (String) cl.getDeclaredField("tooltipDescription").get(null);
} catch (SecurityException e) {
ReportingUtils.logError(e);
toolTipDescription = "Description not available";
} catch (NoSuchFieldException e) {
toolTipDescription = "Description not available";
ReportingUtils.logError(cl.getName() + " fails to implement static String tooltipDescription.");
} catch (IllegalArgumentException e) {
ReportingUtils.logError(e);
} catch (IllegalAccessException e) {
ReportingUtils.logError(e);
}
String mrjProp = System.getProperty("mrj.version");
if (mrjProp != null && !mrjProp.equals(null)) // running on a mac
newMenuItem.setToolTipText(toolTipDescription);
else
newMenuItem.setToolTipText( TooltipTextMaker.addHTMLBreaksForTooltip(toolTipDescription) );
pluginMenu_.add(newMenuItem);
pluginMenu_.validate();
menuBar_.validate();
}
public void updateGUI(boolean updateConfigPadStructure) {
try {
// establish device roles
cameraLabel_ = core_.getCameraDevice();
shutterLabel_ = core_.getShutterDevice();
zStageLabel_ = core_.getFocusDevice();
xyStageLabel_ = core_.getXYStageDevice();
afMgr_.refresh();
// camera settings
if (isCameraAvailable()) {
double exp = core_.getExposure();
textFieldExp_.setText(NumberUtils.doubleToDisplayString(exp));
String binSize = core_.getProperty(cameraLabel_, MMCoreJ.getG_Keyword_Binning());
GUIUtils.setComboSelection(comboBinning_, binSize);
}
if (liveModeTimer_ == null || !liveModeTimer_.isRunning()) {
autoShutterCheckBox_.setSelected(core_.getAutoShutter());
boolean shutterOpen = core_.getShutterOpen();
setShutterButton(shutterOpen);
if (autoShutterCheckBox_.isSelected()) {
toggleButtonShutter_.setEnabled(false);
} else {
toggleButtonShutter_.setEnabled(true);
}
}
// active shutter combo
if (shutters_ != null) {
String activeShutter = core_.getShutterDevice();
if (activeShutter != null) {
shutterComboBox_.setSelectedItem(activeShutter);
} else {
shutterComboBox_.setSelectedItem("");
}
}
// state devices
if (updateConfigPadStructure && (configPad_ != null)) {
configPad_.refreshStructure();
// Needed to update read-only properties. May slow things down...
core_.updateSystemStateCache();
}
// update Channel menus in Multi-dimensional acquisition dialog
updateChannelCombos();
} catch (Exception e) {
ReportingUtils.logError(e);
}
updateStaticInfo();
updateTitle();
}
public boolean okToAcquire() {
return !isLiveModeOn();
}
public void stopAllActivity() {
enableLiveMode(false);
}
private boolean cleanupOnClose() {
// NS: Save config presets if they were changed.
if (configChanged_) {
Object[] options = {"Yes", "No"};
int n = JOptionPane.showOptionDialog(null,
"Save Changed Configuration?", "Micro-Manager",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,
null, options, options[0]);
if (n == JOptionPane.YES_OPTION) {
saveConfigPresets();
}
}
if (liveModeTimer_ != null)
liveModeTimer_.stop();
if (!WindowManager.closeAllWindows())
return false;
if (profileWin_ != null) {
removeMMBackgroundListener(profileWin_);
profileWin_.dispose();
}
if (scriptPanel_ != null) {
removeMMBackgroundListener(scriptPanel_);
scriptPanel_.closePanel();
}
if (propertyBrowser_ != null) {
removeMMBackgroundListener(propertyBrowser_);
propertyBrowser_.dispose();
}
if (acqControlWin_ != null) {
removeMMBackgroundListener(acqControlWin_);
acqControlWin_.close();
}
if (engine_ != null) {
engine_.shutdown();
}
if (afMgr_ != null) {
afMgr_.closeOptionsDialog();
}
// dispose plugins
for (int i = 0; i < plugins_.size(); i++) {
MMPlugin plugin = (MMPlugin) plugins_.get(i).plugin;
if (plugin != null) {
plugin.dispose();
}
}
synchronized (shutdownLock_) {
try {
if (core_ != null){
core_.delete();
core_ = null;
}
} catch (Exception err) {
ReportingUtils.showError(err);
}
}
return true;
}
private void saveSettings() {
Rectangle r = this.getBounds();
mainPrefs_.putInt(MAIN_FRAME_X, r.x);
mainPrefs_.putInt(MAIN_FRAME_Y, r.y);
mainPrefs_.putInt(MAIN_FRAME_WIDTH, r.width);
mainPrefs_.putInt(MAIN_FRAME_HEIGHT, r.height);
mainPrefs_.putInt(MAIN_FRAME_DIVIDER_POS, this.splitPane_.getDividerLocation());
metadataPanel_.saveSettings();
mainPrefs_.put(OPEN_ACQ_DIR, openAcqDirectory_);
// save field values from the main window
// NOTE: automatically restoring these values on startup may cause
// problems
mainPrefs_.put(MAIN_EXPOSURE, textFieldExp_.getText());
// NOTE: do not save auto shutter state
if (afMgr_ != null && afMgr_.getDevice() != null) {
mainPrefs_.put(AUTOFOCUS_DEVICE, afMgr_.getDevice().getDeviceName());
}
}
private void loadConfiguration() {
File f = FileDialogs.openFile(this, "Load a config file",MM_CONFIG_FILE);
if (f != null) {
sysConfigFile_ = f.getAbsolutePath();
configChanged_ = false;
setConfigSaveButtonStatus(configChanged_);
mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_);
loadSystemConfiguration();
}
}
private void loadSystemState() {
File f = FileDialogs.openFile(this, "Load a system state file", MM_CONFIG_FILE);
if (f != null) {
sysStateFile_ = f.getAbsolutePath();
try {
// WaitDialog waitDlg = new
// WaitDialog("Loading saved state, please wait...");
// waitDlg.showDialog();
core_.loadSystemState(sysStateFile_);
GUIUtils.preventDisplayAdapterChangeExceptions();
// waitDlg.closeDialog();
initializeGUI();
} catch (Exception e) {
ReportingUtils.showError(e);
return;
}
}
}
private void saveSystemState() {
File f = FileDialogs.save(this,
"Save the system state to a config file", MM_CONFIG_FILE);
if (f != null) {
sysStateFile_ = f.getAbsolutePath();
try {
core_.saveSystemState(sysStateFile_);
} catch (Exception e) {
ReportingUtils.showError(e);
return;
}
}
}
public void closeSequence() {
if (!this.isRunning())
return;
if (engine_ != null && engine_.isAcquisitionRunning()) {
int result = JOptionPane.showConfirmDialog(
this,
"Acquisition in progress. Are you sure you want to exit and discard all data?",
"Micro-Manager", JOptionPane.YES_NO_OPTION,
JOptionPane.INFORMATION_MESSAGE);
if (result == JOptionPane.NO_OPTION) {
return;
}
}
stopAllActivity();
if (!cleanupOnClose())
return;
running_ = false;
saveSettings();
try {
configPad_.saveSettings();
options_.saveSettings();
hotKeys_.saveSettings();
} catch (NullPointerException e) {
if (core_ != null)
this.logError(e);
}
this.dispose();
if (options_.closeOnExit_) {
if (!runsAsPlugin_) {
System.exit(0);
} else {
ImageJ ij = IJ.getInstance();
if (ij != null) {
ij.quit();
}
}
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////FIX THIS
public void applyContrastSettings(ContrastSettings contrast8,
ContrastSettings contrast16) {
// metadataPanel_.getSingleChannelContrastPanel().applyContrastSettings(contrast8, contrast16);
}
@Override
public ContrastSettings getContrastSettings() {
// return metadataPanel_.getSingleChannelContrastPanel().getContrastSettings();
return null;
}
public boolean is16bit() {
ImagePlus ip = WindowManager.getCurrentImage();
if (ip != null && ip.getProcessor() instanceof ShortProcessor) {
return true;
}
return false;
}
public boolean isRunning() {
return running_;
}
/**
* Executes the beanShell script. This script instance only supports
* commands directed to the core object.
*/
private void executeStartupScript() {
// execute startup script
File f = new File(startupScriptFile_);
if (startupScriptFile_.length() > 0 && f.exists()) {
WaitDialog waitDlg = new WaitDialog(
"Executing startup script, please wait...");
waitDlg.showDialog();
Interpreter interp = new Interpreter();
try {
// insert core object only
interp.set(SCRIPT_CORE_OBJECT, core_);
interp.set(SCRIPT_ACQENG_OBJECT, engine_);
interp.set(SCRIPT_GUI_OBJECT, this);
// read text file and evaluate
interp.eval(TextUtils.readTextFile(startupScriptFile_));
} catch (IOException exc) {
ReportingUtils.showError(exc, "Unable to read the startup script (" + startupScriptFile_ + ").");
} catch (EvalError exc) {
ReportingUtils.showError(exc);
} finally {
waitDlg.closeDialog();
}
} else {
if (startupScriptFile_.length() > 0)
ReportingUtils.logMessage("Startup script file ("+startupScriptFile_+") not present.");
}
}
/**
* Loads system configuration from the cfg file.
*/
private boolean loadSystemConfiguration() {
boolean result = true;
saveMRUConfigFiles();
final WaitDialog waitDlg = new WaitDialog(
"Loading system configuration, please wait...");
waitDlg.setAlwaysOnTop(true);
waitDlg.showDialog();
this.setEnabled(false);
try {
if (sysConfigFile_.length() > 0) {
GUIUtils.preventDisplayAdapterChangeExceptions();
core_.waitForSystem();
ignorePropertyChanges_ = true;
core_.loadSystemConfiguration(sysConfigFile_);
ignorePropertyChanges_ = false;
GUIUtils.preventDisplayAdapterChangeExceptions();
}
} catch (final Exception err) {
GUIUtils.preventDisplayAdapterChangeExceptions();
ReportingUtils.showError(err);
result = false;
} finally {
waitDlg.closeDialog();
}
setEnabled(true);
initializeGUI();
updateSwitchConfigurationMenu();
FileDialogs.storePath(MM_CONFIG_FILE, new File(sysConfigFile_));
return result;
}
private void saveMRUConfigFiles() {
if (0 < sysConfigFile_.length()) {
if (MRUConfigFiles_.contains(sysConfigFile_)) {
MRUConfigFiles_.remove(sysConfigFile_);
}
if (maxMRUCfgs_ <= MRUConfigFiles_.size()) {
MRUConfigFiles_.remove(maxMRUCfgs_ - 1);
}
MRUConfigFiles_.add(0, sysConfigFile_);
// save the MRU list to the preferences
for (Integer icfg = 0; icfg < MRUConfigFiles_.size(); ++icfg) {
String value = "";
if (null != MRUConfigFiles_.get(icfg)) {
value = MRUConfigFiles_.get(icfg).toString();
}
mainPrefs_.put(CFGFILE_ENTRY_BASE + icfg.toString(), value);
}
}
}
private void loadMRUConfigFiles() {
sysConfigFile_ = mainPrefs_.get(SYSTEM_CONFIG_FILE, sysConfigFile_);
// startupScriptFile_ = mainPrefs_.get(STARTUP_SCRIPT_FILE,
// startupScriptFile_);
MRUConfigFiles_ = new ArrayList<String>();
for (Integer icfg = 0; icfg < maxMRUCfgs_; ++icfg) {
String value = "";
value = mainPrefs_.get(CFGFILE_ENTRY_BASE + icfg.toString(), value);
if (0 < value.length()) {
File ruFile = new File(value);
if (ruFile.exists()) {
if (!MRUConfigFiles_.contains(value)) {
MRUConfigFiles_.add(value);
}
}
}
}
// initialize MRU list from old persistant data containing only SYSTEM_CONFIG_FILE
if (0 < sysConfigFile_.length()) {
if (!MRUConfigFiles_.contains(sysConfigFile_)) {
// in case persistant data is inconsistent
if (maxMRUCfgs_ <= MRUConfigFiles_.size()) {
MRUConfigFiles_.remove(maxMRUCfgs_ - 1);
}
MRUConfigFiles_.add(0, sysConfigFile_);
}
}
}
/**
* Opens Acquisition dialog.
*/
private void openAcqControlDialog() {
try {
if (acqControlWin_ == null) {
acqControlWin_ = new AcqControlDlg(engine_, mainPrefs_, this);
}
if (acqControlWin_.isActive()) {
acqControlWin_.setTopPosition();
}
acqControlWin_.setVisible(true);
acqControlWin_.repaint();
// TODO: this call causes a strange exception the first time the
// dialog is created
// something to do with the order in which combo box creation is
// performed
// acqControlWin_.updateGroupsCombo();
} catch (Exception exc) {
ReportingUtils.showError(exc,
"\nAcquistion window failed to open due to invalid or corrupted settings.\n"
+ "Try resetting registry settings to factory defaults (Menu Tools|Options).");
}
}
* /** Opens a dialog to record stage positions
*/
@Override
public void showXYPositionList() {
if (posListDlg_ == null) {
posListDlg_ = new PositionListDlg(core_, this, posList_, options_);
}
posListDlg_.setVisible(true);
}
private void updateChannelCombos() {
if (this.acqControlWin_ != null) {
this.acqControlWin_.updateChannelAndGroupCombo();
}
}
@Override
public void setConfigChanged(boolean status) {
configChanged_ = status;
setConfigSaveButtonStatus(configChanged_);
}
/**
* Returns the current background color
* @return
*/
@Override
public Color getBackgroundColor() {
return guiColors_.background.get((options_.displayBackground_));
}
/*
* Changes background color of this window and all other MM windows
*/
@Override
public void setBackgroundStyle(String backgroundType) {
setBackground(guiColors_.background.get((backgroundType)));
paint(MMStudioMainFrame.this.getGraphics());
// sets background of all registered Components
for (Component comp:MMFrames_) {
if (comp != null)
comp.setBackground(guiColors_.background.get(backgroundType));
}
}
@Override
public String getBackgroundStyle() {
return options_.displayBackground_;
}
// Scripting interface
private class ExecuteAcq implements Runnable {
public ExecuteAcq() {
}
@Override
public void run() {
if (acqControlWin_ != null) {
acqControlWin_.runAcquisition();
}
}
}
private class LoadAcq implements Runnable {
private String filePath_;
public LoadAcq(String path) {
filePath_ = path;
}
@Override
public void run() {
// stop current acquisition if any
engine_.shutdown();
// load protocol
if (acqControlWin_ != null) {
acqControlWin_.loadAcqSettingsFromFile(filePath_);
}
}
}
private void testForAbortRequests() throws MMScriptException {
if (scriptPanel_ != null) {
if (scriptPanel_.stopRequestPending()) {
throw new MMScriptException("Script interrupted by the user!");
}
}
}
@Override
public void startAcquisition() throws MMScriptException {
testForAbortRequests();
SwingUtilities.invokeLater(new ExecuteAcq());
}
@Override
public String runAcquisition() throws MMScriptException {
testForAbortRequests();
if (acqControlWin_ != null) {
String name = acqControlWin_.runAcquisition();
try {
while (acqControlWin_.isAcquisitionRunning()) {
Thread.sleep(50);
}
} catch (InterruptedException e) {
ReportingUtils.showError(e);
}
return name;
} else {
throw new MMScriptException(
"Acquisition setup window must be open for this command to work.");
}
}
@Override
public String runAcquisition(String name, String root)
throws MMScriptException {
testForAbortRequests();
if (acqControlWin_ != null) {
String acqName = acqControlWin_.runAcquisition(name, root);
try {
while (acqControlWin_.isAcquisitionRunning()) {
Thread.sleep(100);
}
} catch (InterruptedException e) {
ReportingUtils.showError(e);
}
return acqName;
} else {
throw new MMScriptException(
"Acquisition setup window must be open for this command to work.");
}
}
@Override
public String runAcqusition(String name, String root) throws MMScriptException {
return runAcquisition(name, root);
}
@Override
public void loadAcquisition(String path) throws MMScriptException {
testForAbortRequests();
SwingUtilities.invokeLater(new LoadAcq(path));
}
@Override
public void setPositionList(PositionList pl) throws MMScriptException {
testForAbortRequests();
// use serialization to clone the PositionList object
posList_ = pl; // PositionList.newInstance(pl);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (posListDlg_ != null) {
posListDlg_.setPositionList(posList_);
engine_.setPositionList(posList_);
}
}
});
}
@Override
public PositionList getPositionList() throws MMScriptException {
testForAbortRequests();
// use serialization to clone the PositionList object
return posList_; //PositionList.newInstance(posList_);
}
@Override
public void sleep(long ms) throws MMScriptException {
if (scriptPanel_ != null) {
if (scriptPanel_.stopRequestPending()) {
throw new MMScriptException("Script interrupted by the user!");
}
scriptPanel_.sleep(ms);
}
}
@Override
public String getUniqueAcquisitionName(String stub) {
return acqMgr_.getUniqueAcquisitionName(stub);
}
// TODO:
@Override
public MMAcquisition getCurrentAcquisition() {
return null; // if none available
}
public void openAcquisition(String name, String rootDir) throws MMScriptException {
openAcquisition(name, rootDir, true);
}
public void openAcquisition(String name, String rootDir, boolean show) throws MMScriptException {
//acqMgr_.openAcquisition(name, rootDir, show);
TaggedImageStorage imageFileManager = new TaggedImageStorageDiskDefault((new File(rootDir, name)).getAbsolutePath());
MMImageCache cache = new MMImageCache(imageFileManager);
VirtualAcquisitionDisplay display = new VirtualAcquisitionDisplay(cache, (AcquisitionEngine) null);
display.show();
}
@Override
public void openAcquisition(String name, String rootDir, int nrFrames,
int nrChannels, int nrSlices, int nrPositions) throws MMScriptException {
this.openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices,
nrPositions, true, false);
}
@Override
public void openAcquisition(String name, String rootDir, int nrFrames,
int nrChannels, int nrSlices) throws MMScriptException {
openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, 0);
}
@Override
public void openAcquisition(String name, String rootDir, int nrFrames,
int nrChannels, int nrSlices, int nrPositions, boolean show)
throws MMScriptException {
this.openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, nrPositions, show, false);
}
@Override
public void openAcquisition(String name, String rootDir, int nrFrames,
int nrChannels, int nrSlices, boolean show)
throws MMScriptException {
this.openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, 0, show, false);
}
@Override
public void openAcquisition(String name, String rootDir, int nrFrames,
int nrChannels, int nrSlices, int nrPositions, boolean show, boolean virtual)
throws MMScriptException {
acqMgr_.openAcquisition(name, rootDir, show, virtual);
MMAcquisition acq = acqMgr_.getAcquisition(name);
acq.setDimensions(nrFrames, nrChannels, nrSlices, nrPositions);
}
@Override
public void openAcquisition(String name, String rootDir, int nrFrames,
int nrChannels, int nrSlices, boolean show, boolean virtual)
throws MMScriptException {
this.openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, 0, show, virtual);
}
public String createAcquisition(JSONObject summaryMetadata, boolean diskCached) {
return acqMgr_.createAcquisition(summaryMetadata, diskCached, engine_);
}
private void openAcquisitionSnap(String name, String rootDir, boolean show)
throws MMScriptException {
/*
MMAcquisition acq = acqMgr_.openAcquisitionSnap(name, rootDir, this,
show);
acq.setDimensions(0, 1, 1, 1);
try {
// acq.getAcqData().setPixelSizeUm(core_.getPixelSizeUm());
acq.setProperty(SummaryKeys.IMAGE_PIXEL_SIZE_UM, String.valueOf(core_.getPixelSizeUm()));
} catch (Exception e) {
ReportingUtils.showError(e);
}
*
*/
}
@Override
public void initializeSimpleAcquisition(String name, int width, int height,
int byteDepth, int bitDepth, int multiCamNumCh) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(name);
acq.setImagePhysicalDimensions(width, height, byteDepth, bitDepth, multiCamNumCh);
acq.initializeSimpleAcq();
}
@Override
public void initializeAcquisition(String name, int width, int height,
int depth) throws MMScriptException {
initializeAcquisition(name,width,height,depth,8*depth);
}
@Override
public void initializeAcquisition(String name, int width, int height,
int depth, int bitDepth) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(name);
//number of multi-cam cameras is set to 1 here for backwards compatibility
//might want to change this later
acq.setImagePhysicalDimensions(width, height, depth, bitDepth,1);
acq.initialize();
}
@Override
public int getAcquisitionImageWidth(String acqName) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(acqName);
return acq.getWidth();
}
@Override
public int getAcquisitionImageHeight(String acqName) throws MMScriptException{
MMAcquisition acq = acqMgr_.getAcquisition(acqName);
return acq.getHeight();
}
@Override
public int getAcquisitionImageBitDepth(String acqName) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(acqName);
return acq.getBitDepth();
}
@Override
public int getAcquisitionImageByteDepth(String acqName) throws MMScriptException{
MMAcquisition acq = acqMgr_.getAcquisition(acqName);
return acq.getDepth();
}
@Override public int getAcquisitionMultiCamNumChannels(String acqName) throws MMScriptException{
MMAcquisition acq = acqMgr_.getAcquisition(acqName);
return acq.getMultiCameraNumChannels();
}
@Override
public Boolean acquisitionExists(String name) {
return acqMgr_.acquisitionExists(name);
}
@Override
public void closeAcquisition(String name) throws MMScriptException {
acqMgr_.closeAcquisition(name);
}
@Override
public void closeAcquisitionImage5D(String acquisitionName) throws MMScriptException {
acqMgr_.closeImage5D(acquisitionName);
}
@Override
public void closeAcquisitionWindow(String acquisitionName) throws MMScriptException {
acqMgr_.closeImage5D(acquisitionName);
}
/**
* Since Burst and normal acquisition are now carried out by the same engine,
* loadBurstAcquistion simply calls loadAcquisition
* t
* @param path - path to file specifying acquisition settings
*/
@Override
public void loadBurstAcquisition(String path) throws MMScriptException {
this.loadAcquisition(path);
}
@Override
public void refreshGUI() {
updateGUI(true);
}
public void setAcquisitionProperty(String acqName, String propertyName,
String value) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(acqName);
acq.setProperty(propertyName, value);
}
public void setAcquisitionSystemState(String acqName, JSONObject md) throws MMScriptException {
acqMgr_.getAcquisition(acqName).setSystemState(md);
}
public void setAcquisitionSummary(String acqName, JSONObject md) throws MMScriptException {
acqMgr_.getAcquisition(acqName).setSummaryProperties(md);
}
public void setImageProperty(String acqName, int frame, int channel,
int slice, String propName, String value) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(acqName);
acq.setProperty(frame, channel, slice, propName, value);
}
public void snapAndAddImage(String name, int frame, int channel, int slice)
throws MMScriptException {
snapAndAddImage(name, frame, channel, slice, 0);
}
public void snapAndAddImage(String name, int frame, int channel, int slice, int position)
throws MMScriptException {
Metadata md = new Metadata();
try {
Object img;
if (core_.isSequenceRunning()) {
img = core_.getLastImage();
core_.getLastImageMD(0, 0, md);
} else {
core_.snapImage();
img = core_.getImage();
}
MMAcquisition acq = acqMgr_.getAcquisition(name);
long width = core_.getImageWidth();
long height = core_.getImageHeight();
long depth = core_.getBytesPerPixel();
long bitDepth = core_.getImageBitDepth();
int multiCamNumCh = (int) core_.getNumberOfCameraChannels();
if (!acq.isInitialized()) {
acq.setImagePhysicalDimensions((int) width, (int) height,
(int) depth, (int) bitDepth, multiCamNumCh);
acq.initialize();
}
acq.insertImage(img, frame, channel, slice, position);
// Insert exposure in metadata
// acq.setProperty(frame, channel, slice, ImagePropertyKeys.EXPOSURE_MS, NumberUtils.doubleToDisplayString(core_.getExposure()));
// Add pixel size calibration
/*
double pixSizeUm = core_.getPixelSizeUm();
if (pixSizeUm > 0) {
acq.setProperty(frame, channel, slice, ImagePropertyKeys.X_UM, NumberUtils.doubleToDisplayString(pixSizeUm));
acq.setProperty(frame, channel, slice, ImagePropertyKeys.Y_UM, NumberUtils.doubleToDisplayString(pixSizeUm));
}
// generate list with system state
JSONObject state = Annotator.generateJSONMetadata(core_.getSystemStateCache());
// and insert into metadata
acq.setSystemState(frame, channel, slice, state);
*/
} catch (Exception e) {
ReportingUtils.showError(e);
}
}
public void addToSnapSeries(Object img, String acqName) {
try {
acqMgr_.getCurrentAlbum();
if (acqName == null) {
acqName = "Snap" + snapCount_;
}
Boolean newSnap = false;
core_.setExposure(NumberUtils.displayStringToDouble(textFieldExp_.getText()));
long width = core_.getImageWidth();
long height = core_.getImageHeight();
long depth = core_.getBytesPerPixel();
//MMAcquisitionSnap acq = null;
if (! acqMgr_.hasActiveImage5D(acqName)) {
newSnap = true;
}
if (newSnap) {
snapCount_++;
acqName = "Snap" + snapCount_;
this.openAcquisitionSnap(acqName, null, true); // (dir=null) ->
// keep in
// memory; don't
// save to file.
initializeAcquisition(acqName, (int) width, (int) height,
(int) depth);
}
setChannelColor(acqName, 0, Color.WHITE);
setChannelName(acqName, 0, "Snap");
// acq = (MMAcquisitionSnap) acqMgr_.getAcquisition(acqName);
// acq.appendImage(img);
// add exposure to metadata
// acq.setProperty(acq.getFrames() - 1, acq.getChannels() - 1, acq.getSlices() - 1, ImagePropertyKeys.EXPOSURE_MS, NumberUtils.doubleToDisplayString(core_.getExposure()));
// Add pixel size calibration
double pixSizeUm = core_.getPixelSizeUm();
if (pixSizeUm > 0) {
// acq.setProperty(acq.getFrames() - 1, acq.getChannels() - 1, acq.getSlices() - 1, ImagePropertyKeys.X_UM, NumberUtils.doubleToDisplayString(pixSizeUm));
// acq.setProperty(acq.getFrames() - 1, acq.getChannels() - 1, acq.getSlices() - 1, ImagePropertyKeys.Y_UM, NumberUtils.doubleToDisplayString(pixSizeUm));
}
// generate list with system state
// JSONObject state = Annotator.generateJSONMetadata(core_.getSystemStateCache());
// and insert into metadata
// acq.setSystemState(acq.getFrames() - 1, acq.getChannels() - 1, acq.getSlices() - 1, state);
// closeAcquisition(acqName);
} catch (Exception e) {
ReportingUtils.showError(e);
}
}
public String getCurrentAlbum() {
return acqMgr_.getCurrentAlbum();
}
public String createNewAlbum() {
return acqMgr_.createNewAlbum();
}
public void appendImage(String name, TaggedImage taggedImg) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(name);
int f = 1 + acq.getLastAcquiredFrame();
try {
MDUtils.setFrameIndex(taggedImg.tags, f);
} catch (JSONException e) {
throw new MMScriptException("Unable to set the frame index.");
}
acq.insertTaggedImage(taggedImg, f, 0, 0);
}
public void addToAlbum(TaggedImage taggedImg) throws MMScriptException {
acqMgr_.addToAlbum(taggedImg);
}
public void addImage(String name, Object img, int frame, int channel,
int slice) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(name);
acq.insertImage(img, frame, channel, slice);
}
public void addImage(String name, TaggedImage taggedImg) throws MMScriptException {
acqMgr_.getAcquisition(name).insertImage(taggedImg);
}
public void addImage(String name, TaggedImage taggedImg, boolean updateDisplay) throws MMScriptException {
acqMgr_.getAcquisition(name).insertImage(taggedImg, updateDisplay);
}
public void addImage(String name, TaggedImage taggedImg,
boolean updateDisplay,
boolean waitForDisplay) throws MMScriptException {
acqMgr_.getAcquisition(name).insertImage(taggedImg, updateDisplay, waitForDisplay);
}
public void closeAllAcquisitions() {
acqMgr_.closeAll();
}
public String[] getAcquisitionNames()
{
return acqMgr_.getAcqusitionNames();
}
public MMAcquisition getAcquisition(String name) throws MMScriptException {
return acqMgr_.getAcquisition(name);
}
private class ScriptConsoleMessage implements Runnable {
String msg_;
public ScriptConsoleMessage(String text) {
msg_ = text;
}
public void run() {
if (scriptPanel_ != null)
scriptPanel_.message(msg_);
}
}
public void message(String text) throws MMScriptException {
if (scriptPanel_ != null) {
if (scriptPanel_.stopRequestPending()) {
throw new MMScriptException("Script interrupted by the user!");
}
SwingUtilities.invokeLater(new ScriptConsoleMessage(text));
}
}
public void clearMessageWindow() throws MMScriptException {
if (scriptPanel_ != null) {
if (scriptPanel_.stopRequestPending()) {
throw new MMScriptException("Script interrupted by the user!");
}
scriptPanel_.clearOutput();
}
}
public void clearOutput() throws MMScriptException {
clearMessageWindow();
}
public void clear() throws MMScriptException {
clearMessageWindow();
}
public void setChannelContrast(String title, int channel, int min, int max)
throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(title);
acq.setChannelContrast(channel, min, max);
}
public void setChannelName(String title, int channel, String name)
throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(title);
acq.setChannelName(channel, name);
}
public void setChannelColor(String title, int channel, Color color)
throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(title);
acq.setChannelColor(channel, color.getRGB());
}
public void setContrastBasedOnFrame(String title, int frame, int slice)
throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(title);
acq.setContrastBasedOnFrame(frame, slice);
}
public void setStagePosition(double z) throws MMScriptException {
try {
core_.setPosition(core_.getFocusDevice(),z);
core_.waitForDevice(core_.getFocusDevice());
} catch (Exception e) {
throw new MMScriptException(e.getMessage());
}
}
public void setRelativeStagePosition(double z) throws MMScriptException {
try {
core_.setRelativePosition(core_.getFocusDevice(), z);
core_.waitForDevice(core_.getFocusDevice());
} catch (Exception e) {
throw new MMScriptException(e.getMessage());
}
}
public void setXYStagePosition(double x, double y) throws MMScriptException {
try {
core_.setXYPosition(core_.getXYStageDevice(), x, y);
core_.waitForDevice(core_.getXYStageDevice());
} catch (Exception e) {
throw new MMScriptException(e.getMessage());
}
}
public void setRelativeXYStagePosition(double x, double y) throws MMScriptException {
try {
core_.setRelativeXYPosition(core_.getXYStageDevice(), x, y);
core_.waitForDevice(core_.getXYStageDevice());
} catch (Exception e) {
throw new MMScriptException(e.getMessage());
}
}
public Point2D.Double getXYStagePosition() throws MMScriptException {
String stage = core_.getXYStageDevice();
if (stage.length() == 0) {
throw new MMScriptException("XY Stage device is not available");
}
double x[] = new double[1];
double y[] = new double[1];
try {
core_.getXYPosition(stage, x, y);
Point2D.Double pt = new Point2D.Double(x[0], y[0]);
return pt;
} catch (Exception e) {
throw new MMScriptException(e.getMessage());
}
}
public String getXYStageName() {
return core_.getXYStageDevice();
}
public void setXYOrigin(double x, double y) throws MMScriptException {
String xyStage = core_.getXYStageDevice();
try {
core_.setAdapterOriginXY(xyStage, x, y);
} catch (Exception e) {
throw new MMScriptException(e);
}
}
public AcquisitionEngine getAcquisitionEngine() {
return engine_;
}
public String installPlugin(Class<?> cl) {
String className = cl.getSimpleName();
String msg = className + " module loaded.";
try {
for (PluginItem plugin : plugins_) {
if (plugin.className.contentEquals(className)) {
return className + " already loaded.";
}
}
PluginItem pi = new PluginItem();
pi.className = className;
try {
// Get this static field from the class implementing MMPlugin.
pi.menuItem = (String) cl.getDeclaredField("menuName").get(null);
} catch (SecurityException e) {
ReportingUtils.logError(e);
pi.menuItem = className;
} catch (NoSuchFieldException e) {
pi.menuItem = className;
ReportingUtils.logError(className + " fails to implement static String menuName.");
} catch (IllegalArgumentException e) {
ReportingUtils.logError(e);
} catch (IllegalAccessException e) {
ReportingUtils.logError(e);
}
if (pi.menuItem == null) {
pi.menuItem = className;
//core_.logMessage(className + " fails to implement static String menuName.");
}
pi.menuItem = pi.menuItem.replace("_", " ");
pi.pluginClass = cl;
plugins_.add(pi);
final PluginItem pi2 = pi;
final Class<?> cl2 = cl;
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
addPluginToMenu(pi2, cl2);
}
});
} catch (NoClassDefFoundError e) {
msg = className + " class definition not found.";
ReportingUtils.logError(e, msg);
}
return msg;
}
public String installPlugin(String className, String menuName) {
String msg = "installPlugin(String className, String menuName) is deprecated. Use installPlugin(String className) instead.";
core_.logMessage(msg);
installPlugin(className);
return msg;
}
public String installPlugin(String className) {
String msg = "";
try {
Class clazz = Class.forName(className);
return installPlugin(clazz);
} catch (ClassNotFoundException e) {
msg = className + " plugin not found.";
ReportingUtils.logError(e, msg);
return msg;
}
}
public String installAutofocusPlugin(String className) {
try {
return installAutofocusPlugin(Class.forName(className));
} catch (ClassNotFoundException e) {
String msg = "Internal error: AF manager not instantiated.";
ReportingUtils.logError(e, msg);
return msg;
}
}
public String installAutofocusPlugin(Class<?> autofocus) {
String msg = autofocus.getSimpleName() + " module loaded.";
if (afMgr_ != null) {
try {
afMgr_.refresh();
} catch (MMException e) {
msg = e.getMessage();
ReportingUtils.logError(e);
}
afMgr_.setAFPluginClassName(autofocus.getSimpleName());
} else {
msg = "Internal error: AF manager not instantiated.";
}
return msg;
}
public CMMCore getCore() {
return core_;
}
public Pipeline getPipeline() {
try {
pipelineClassLoadingThread_.join();
if (acquirePipeline_ == null) {
acquirePipeline_ = (Pipeline) pipelineClass_.newInstance();
}
return acquirePipeline_;
} catch (Exception e) {
ReportingUtils.logError(e);
return null;
}
}
public void snapAndAddToImage5D() {
try {
getPipeline().acquireSingle();
} catch (Exception ex) {
ReportingUtils.logError(ex);
}
}
public void setAcquisitionEngine(AcquisitionEngine eng) {
engine_ = eng;
}
public void suspendLiveMode() {
liveModeSuspended_ = isLiveModeOn();
enableLiveMode(false);
}
public void resumeLiveMode() {
if (liveModeSuspended_) {
enableLiveMode(true);
}
}
public Autofocus getAutofocus() {
return afMgr_.getDevice();
}
public void showAutofocusDialog() {
if (afMgr_.getDevice() != null) {
afMgr_.showOptionsDialog();
}
}
public AutofocusManager getAutofocusManager() {
return afMgr_;
}
public void selectConfigGroup(String groupName) {
configPad_.setGroup(groupName);
}
public String regenerateDeviceList() {
Cursor oldc = Cursor.getDefaultCursor();
Cursor waitc = new Cursor(Cursor.WAIT_CURSOR);
setCursor(waitc);
StringBuffer resultFile = new StringBuffer();
MicroscopeModel.generateDeviceListFile(resultFile, core_);
//MicroscopeModel.generateDeviceListFile();
setCursor(oldc);
return resultFile.toString();
}
private void loadPlugins() {
afMgr_ = new AutofocusManager(this);
ArrayList<Class<?>> pluginClasses = new ArrayList<Class<?>>();
ArrayList<Class<?>> autofocusClasses = new ArrayList<Class<?>>();
List<Class<?>> classes;
try {
long t1 = System.currentTimeMillis();
classes = JavaUtils.findClasses(new File("mmplugins"), 2);
//System.out.println("findClasses: " + (System.currentTimeMillis() - t1));
//System.out.println(classes.size());
for (Class<?> clazz : classes) {
for (Class<?> iface : clazz.getInterfaces()) {
//core_.logMessage("interface found: " + iface.getName());
if (iface == MMPlugin.class) {
pluginClasses.add(clazz);
}
}
}
classes = JavaUtils.findClasses(new File("mmautofocus"), 2);
for (Class<?> clazz : classes) {
for (Class<?> iface : clazz.getInterfaces()) {
//core_.logMessage("interface found: " + iface.getName());
if (iface == Autofocus.class) {
autofocusClasses.add(clazz);
}
}
}
} catch (ClassNotFoundException e1) {
ReportingUtils.logError(e1);
}
for (Class<?> plugin : pluginClasses) {
try {
ReportingUtils.logMessage("Attempting to install plugin " + plugin.getName());
installPlugin(plugin);
} catch (Exception e) {
ReportingUtils.logError(e, "Failed to install the \"" + plugin.getName() + "\" plugin .");
}
}
for (Class<?> autofocus : autofocusClasses) {
try {
ReportingUtils.logMessage("Attempting to install autofocus plugin " + autofocus.getName());
installAutofocusPlugin(autofocus.getName());
} catch (Exception e) {
ReportingUtils.logError("Failed to install the \"" + autofocus.getName() + "\" autofocus plugin.");
}
}
}
public void logMessage(String msg) {
ReportingUtils.logMessage(msg);
}
public void showMessage(String msg) {
ReportingUtils.showMessage(msg);
}
public void logError(Exception e, String msg) {
ReportingUtils.logError(e, msg);
}
public void logError(Exception e) {
ReportingUtils.logError(e);
}
public void logError(String msg) {
ReportingUtils.logError(msg);
}
public void showError(Exception e, String msg) {
ReportingUtils.showError(e, msg);
}
public void showError(Exception e) {
ReportingUtils.showError(e);
}
public void showError(String msg) {
ReportingUtils.showError(msg);
}
private void runHardwareWizard(boolean v2) {
try {
if (configChanged_) {
Object[] options = {"Yes", "No"};
int n = JOptionPane.showOptionDialog(null,
"Save Changed Configuration?", "Micro-Manager",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE, null, options,
options[0]);
if (n == JOptionPane.YES_OPTION) {
saveConfigPresets();
}
configChanged_ = false;
}
boolean liveRunning = false;
if (isLiveModeOn()) {
liveRunning = true;
enableLiveMode(false);
}
// unload all devices before starting configurator
core_.reset();
GUIUtils.preventDisplayAdapterChangeExceptions();
// run Configurator
if (v2) {
ConfiguratorDlg2 cfg2 = new ConfiguratorDlg2(core_, sysConfigFile_);
cfg2.setVisible(true);
GUIUtils.preventDisplayAdapterChangeExceptions();
// re-initialize the system with the new configuration file
sysConfigFile_ = cfg2.getFileName();
} else {
ConfiguratorDlg configurator = new ConfiguratorDlg(core_, sysConfigFile_);
configurator.setVisible(true);
GUIUtils.preventDisplayAdapterChangeExceptions();
// re-initialize the system with the new configuration file
sysConfigFile_ = configurator.getFileName();
}
mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_);
loadSystemConfiguration();
GUIUtils.preventDisplayAdapterChangeExceptions();
if (liveRunning) {
enableLiveMode(liveRunning);
}
} catch (Exception e) {
ReportingUtils.showError(e);
return;
}
}
}
class BooleanLock extends Object {
private boolean value;
public BooleanLock(boolean initialValue) {
value = initialValue;
}
public BooleanLock() {
this(false);
}
public synchronized void setValue(boolean newValue) {
if (newValue != value) {
value = newValue;
notifyAll();
}
}
public synchronized boolean waitToSetTrue(long msTimeout)
throws InterruptedException {
boolean success = waitUntilFalse(msTimeout);
if (success) {
setValue(true);
}
return success;
}
public synchronized boolean waitToSetFalse(long msTimeout)
throws InterruptedException {
boolean success = waitUntilTrue(msTimeout);
if (success) {
setValue(false);
}
return success;
}
public synchronized boolean isTrue() {
return value;
}
public synchronized boolean isFalse() {
return !value;
}
public synchronized boolean waitUntilTrue(long msTimeout)
throws InterruptedException {
return waitUntilStateIs(true, msTimeout);
}
public synchronized boolean waitUntilFalse(long msTimeout)
throws InterruptedException {
return waitUntilStateIs(false, msTimeout);
}
public synchronized boolean waitUntilStateIs(
boolean state,
long msTimeout) throws InterruptedException {
if (msTimeout == 0L) {
while (value != state) {
wait();
}
return true;
}
long endTime = System.currentTimeMillis() + msTimeout;
long msRemaining = msTimeout;
while ((value != state) && (msRemaining > 0L)) {
wait(msRemaining);
msRemaining = endTime - System.currentTimeMillis();
}
return (value == state);
}
}
|
package stroom.startup;
import io.dropwizard.setup.Environment;
import org.eclipse.jetty.servlet.ServletHolder;
public class Servlets {
/**
* Load all servlets.
*/
@SuppressWarnings("unchecked")
static void loadInto(Environment environment) throws ClassNotFoundException {
addServlet(environment, Servlets.newLog4jServlet(), 1,"", null);
|
package org.basex.gui.layout;
import static org.basex.Text.*;
import static org.basex.gui.GUIConstants.*;
import static org.basex.util.Token.*;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.RenderingHints;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.AbstractButton;
import javax.swing.JComponent;
import org.basex.BaseX;
import org.basex.gui.GUI;
import org.basex.gui.GUIConstants;
import org.basex.gui.GUIProp;
import org.basex.gui.dialog.Dialog;
import org.basex.gui.view.ViewRect;
import org.basex.index.FTTokenizer;
import org.basex.util.Array;
import org.basex.util.IntList;
import org.basex.util.Performance;
public final class BaseXLayout {
/** Date Format. */
public static final SimpleDateFormat DATE =
new SimpleDateFormat("dd.MM.yyyy hh:mm");
/** Private constructor. */
private BaseXLayout() { }
/**
* Creates a OK and CANCEL button.
* @param dialog reference to the component, reacting on button clicks.
* @return button list
*/
public static BaseXBack okCancel(final Dialog dialog) {
return newButtons(dialog, true,
new String[] { BUTTONOK, BUTTONCANCEL },
new byte[][] { HELPOK, HELPCANCEL });
}
/**
* Creates a new button list.
* @param dialog reference to the component, reacting on button clicks.
* @param hor horizontal alignment
* @param texts button names
* @param help help texts
* @return button list
*/
public static BaseXBack newButtons(final Dialog dialog,
final boolean hor, final String[] texts, final byte[][] help) {
// horizontal/vertical layout
final BaseXBack panel = new BaseXBack();
if(hor) {
panel.setBorder(12, 0, 0, 0);
panel.setLayout(new TableLayout(1, texts.length, 8, 0));
} else {
panel.setBorder(0, 0, 0, 0);
panel.setLayout(new GridLayout(texts.length, 1, 0, 3));
}
for(int i = 0; i < texts.length; i++) {
panel.add(new BaseXButton(texts[i], help[i], dialog));
}
final BaseXBack buttons = new BaseXBack();
buttons.setLayout(new BorderLayout());
buttons.add(panel, hor ? BorderLayout.EAST : BorderLayout.NORTH);
return buttons;
}
/**
* Enables/disables a button in the specified panel.
* @param panel button panel
* @param label button label
* @param enabled enabled/disabled
*/
public static void enableOK(final JComponent panel, final String label,
final boolean enabled) {
final Component[] jc = panel.getComponents();
for(final Component c : jc) {
if(!(c instanceof JComponent)) {
continue;
} else if(!(c instanceof BaseXButton)) {
enableOK((JComponent) c, label, enabled);
} else {
final BaseXButton b = (BaseXButton) c;
if(b.getText().equals(label)) enable(b, enabled);
}
}
}
/**
* Sets the component width, adopting the original component height.
* @param comp component
* @param w width
*/
public static void setWidth(final Container comp, final int w) {
comp.setPreferredSize(new Dimension(w, comp.getPreferredSize().height));
}
/**
* Sets the component height, adopting the original component width.
* @param comp component
* @param h height
*/
public static void setHeight(final Container comp, final int h) {
comp.setPreferredSize(new Dimension(comp.getPreferredSize().width, h));
}
/**
* Sets the component size.
* @param comp component
* @param w width
* @param h height
*/
public static void setSize(final Container comp, final int w, final int h) {
comp.setPreferredSize(new Dimension(w, h));
}
/**
* Adds default notifiers for ENTER and ESCAPE to the specified component.
* @param c the component that receives default notifications.
* @param l the parent dialog
*/
public static void addDefaultKeys(final Container c, final Dialog l) {
// no dialog listener specified..
if(l == null) return;
// add default keys
c.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(final KeyEvent e) {
// process key events
if(e.getKeyCode() == KeyEvent.VK_ENTER) {
if(!(e.getSource() instanceof BaseXButton)) l.close();
} else if(e.getKeyCode() == KeyEvent.VK_ESCAPE) {
l.cancel();
}
}
});
}
/**
* Adds a help notifier to the specified component.
* @param comp component
* @param hlp help text
*/
public static void addHelp(final Component comp, final byte[] hlp) {
comp.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(final MouseEvent e) {
GUI.get().focus(comp, hlp);
}
});
}
/**
* Enables or disables the specified component.
* @param comp component
* @param enable boolean flag
*/
public static void enable(final Container comp, final boolean enable) {
if(comp.isEnabled() != enable) comp.setEnabled(enable);
}
/**
* Selects or de-selects the specified component.
* @param but component
* @param select selection flag
*/
public static void select(final AbstractButton but, final boolean select) {
if(but.isSelected() != select) but.setSelected(select);
}
/**
* Returns the value of the specified pre value and attribute.
* @param val value to be evaluated
* @param size size flag
* @param date date flag
* @return value as string
*/
public static String value(final double val, final boolean size,
final boolean date) {
if(size) return Performance.format((long) val, true);
if(date) return DATE.format(new Date((long) val * 60000));
return string(chopNumber(token(val)));
}
/**
* Fills the specified area with a color gradient.
* @param gg graphics reference
* @param c1 first color
* @param c2 second color
* @param xs horizontal start position
* @param ys vertical start position
* @param xe horizontal end position
* @param ye vertical end position
*/
public static void fill(final Graphics gg, final Color c1,
final Color c2, final int xs, final int ys, final int xe, final int ye) {
final int w = xe - xs;
final int h = ye - ys;
final int r = c1.getRed();
final int g = c1.getGreen();
final int b = c1.getBlue();
final float rf = (c2.getRed() - r) / (float) h;
final float gf = (c2.getGreen() - g) / (float) h;
final float bf = (c2.getBlue() - b) / (float) h;
int nr = 0, ng = 0, nb = 0;
int cr = 0, cg = 0, cb = 0;
int hh = 0;
for(int y = 0; y < h; y++) {
nr = r + (int) (rf * y);
ng = g + (int) (gf * y);
nb = b + (int) (bf * y);
if(nr != cr || ng != cg || nb != cb) {
gg.setColor(new Color(nr, ng, nb));
gg.fillRect(xs, ys + y - hh, w, hh);
hh = 0;
}
cr = nr;
cg = ng;
cb = nb;
hh++;
}
gg.fillRect(xs, ys + h - hh, w, hh);
}
/**
* Draw the header of the scrollbar.
* @param g graphics reference
* @param xs horizontal start position
* @param xe horizontal end position
* @param ys vertical start position
* @param ye vertical end position
* @param focus highlighting flag
*/
public static void drawCell(final Graphics g, final int xs,
final int xe, final int ys, final int ye, final boolean focus) {
g.setColor(COLORBUTTON);
g.drawRect(xs, ys, xe - xs - 1, ye - ys - 1);
g.setColor(Color.white);
g.drawRect(xs + 1, ys + 1, xe - xs - 3, ye - ys - 3);
fill(g, focus ? COLORCELL : Color.white, COLORCELL,
xs + 2, ys + 2, xe - 1, ye - 1);
}
/**
* Enables/Disables anti-aliasing.
* @param g graphics reference
*/
public static void antiAlias(final Graphics g) {
Object hint = RenderingHints.VALUE_TEXT_ANTIALIAS_OFF;
if(GUIProp.fontalias) {
// Check out Java 1.6 rendering; if not available, use default rendering
try {
final Class<?> rh = RenderingHints.class;
hint = rh.getField("VALUE_TEXT_ANTIALIAS_" + GUIProp.fontaa).get(null);
} catch(final Exception e) {
hint = RenderingHints.VALUE_TEXT_ANTIALIAS_ON;
}
}
final Graphics2D gg = (Graphics2D) g;
gg.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, hint);
}
/**
* Draws a centered string to the panel.
* @param g graphics reference
* @param text text to be painted
* @param w panel width
* @param y vertical position
*/
public static void drawCenter(final Graphics g, final String text,
final int w, final int y) {
g.drawString(text, (w - width(g, text)) / 2, y);
}
/**
* Draws a visualization tooltip.
* @param g graphics reference
* @param tt tooltip label
* @param x horizontal position
* @param y vertical position
* @param w width
* @param c color color depth
*/
public static void drawTooltip(final Graphics g, final String tt,
final int x, final int y, final int w, final int c) {
final int tw = BaseXLayout.width(g, tt);
final int th = g.getFontMetrics().getHeight();
final int xx = Math.min(w - tw - 8, x);
g.setColor(GUIConstants.COLORS[c]);
g.fillRect(xx - 1, y - th, tw + 4, th);
g.setColor(GUIConstants.color1);
g.drawString(tt, xx, y - 4);
}
/**
* Returns the width of the specified text.
* @param g graphics reference
* @param s string to be evaluated
* @return string width
*/
public static int width(final Graphics g, final String s) {
return g.getFontMetrics().stringWidth(s);
}
/**
* Draws the specified string.
* @param g graphics reference
* @param s text
* @param x x coordinate
* @param y y coordinate
* @param w width
* @return width of printed string
*/
public static int chopString(final Graphics g, final byte[] s,
final int x, final int y, final int w) {
if(w < 12) return w;
final int[] cw = fontWidths(g.getFont());
int j = s.length;
int fw = 0;
int l = 0;
try {
for(int k = 0; k < j; k += l) {
final int ww = width(g, cw, cp(s, k));
if(fw + ww >= w - 4) {
j = Math.max(1, k - l);
if(k > 1) fw -= width(g, cw, cp(s, k - 1));
g.drawString("..", x + fw, y + GUIProp.fontsize);
break;
}
fw += ww;
l = cl(s[k]);
}
} catch(final Exception ex) {
BaseX.debug(ex);
}
g.drawString(string(s, 0, j), x, y + GUIProp.fontsize);
return fw;
}
/**
* Calculates if the string fits in one line; if yes, returns the
* horizontal start position. Otherwise, returns -1.
* @param g graphics reference
* @param s string to be checked
* @param ww maximum width
* @return result of check
*/
public static int centerPos(final Graphics g, final byte[] s, final int ww) {
final int[] cw = fontWidths(g.getFont());
int sw = 0;
final int j = s.length;
for(int k = 0; k < j; k += cl(s[k])) {
sw += width(g, cw, cp(s, k));
if(sw >= ww) return -1;
}
return (ww - sw - 2) >> 1;
}
/**
* Calculates the height of the specified text.
* @param g graphics reference
* @param r rectangle
* @param s text to be drawn
* @return last height that was occupied
*/
public static int calcHeight(final Graphics g, final ViewRect r,
final byte[] s) {
return drawText(g, r, s, s.length, false);
}
/**
* Draws a text.
* @param g graphics reference
* @param r rectangle
* @param s text to be drawn
* @return last height that was occupied
*/
public static int drawText(final Graphics g, final ViewRect r,
final byte[] s) {
return drawTextNew(g, r, s, s.length, true);
}
/**
* Draws a text.
* @param g graphics reference
* @param r rectangle
* @param s text to be drawn
* @param m length of text
* @param draw draw text (otherwise: just calculate space)
* @return last height that was occupied
*/
public static int drawText(final Graphics g, final ViewRect r,
final byte[] s, final int m, final boolean draw) {
// limit string to given space
final int[] cw = fontWidths(g.getFont());
final int fh = (int) (1.2 * GUIProp.fontsize);
final int ws = cw[' '];
int i = 0;
int j = m;
int xx = r.x;
int yy = r.y + fh;
int ww = r.w;
final Color textc = g.getColor();
// get index on first pre value
int count = 0;
int pp = 0;
do {
int sw = 0;
int l = i;
for(int n = i; n < j; n += cl(s[n])) {
sw += width(g, cw, cp(s, n));
if(sw >= ww) {
j = Math.max(i + 1, l);
ww = r.w;
break;
}
if(s[n] == '\n') {
j = n + 1;
ww = r.w;
break;
}
if(ws(s[n])) {
j = n + 1;
ww -= sw;
break;
}
l = n;
}
// draw string
if(draw) {
if (r.pos != null && pp < r.pos.length && count == r.pos[pp]) {
pp++;
g.setColor(COLORERROR);
} else
g.setColor(textc);
g.drawString(string(s, i, j - i), xx, yy);
count++;
}
if(ww < ws) ww = r.w;
if(ww == r.w) {
xx = r.x;
yy += fh;
} else {
xx += sw;
}
i = j;
j = m;
} while(i < j && yy - (draw ? 0 : GUIProp.fontsize) < r.y + r.h);
return yy - r.y;
}
/**
* Draws a text.
* @param g graphics reference
* @param r rectangle
* @param s text to be drawn
* @param m length of text
* @param draw draw text (otherwise: just calculate space)
* @return last height that was occupied
*/
public static int drawTextNew(final Graphics g, final ViewRect r,
final byte[] s, final int m, final boolean draw) {
// limit string to given space
final int[] cw = fontWidths(g.getFont());
final int fh = (int) (1.2 * GUIProp.fontsize);
int xx = r.x;
int yy = r.y + fh;
int ww = r.w;
final Color textc = g.getColor();
byte[] tmp;
if (s.length > m) {
tmp = new byte[m];
System.arraycopy(s, 0, tmp, 0, m);
} else tmp = s;
final FTTokenizer ftt = new FTTokenizer(tmp);
// get index on first pre value
int count = 0;
int pp = 0;
int ll = 0;
int cp = 0;
final int we = width(g, cw, ' ');
while(ftt.more()) {
if (cp < ftt.para) {
cp = ftt.para;
xx = r.x;
yy += fh;
ll = 0;
if (yy >= r.y + r.h)
return yy - r.y;
}
final byte[] tok = ftt.get();
int wl = 0;
for (byte b : tok) wl += width(g, cw, b);
if (ll + wl + we >= ww) {
xx = r.x;
yy += fh;
ll = 0;
if (yy >= r.y + r.h)
return yy - r.y;
}
if(draw) {
if (r.pos != null && pp < r.pos.length && count == r.pos[pp]) {
pp++;
g.setColor(thumbnailcolor[r.poi[pp]]);
} else g.setColor(textc);
g.drawString(new String(tok), xx + ll, yy);
count++;
}
ll += wl + we;
}
return yy - r.y;
}
/**
* Draws a text using thumbnail visualization.
* Calculates the needed space and chooses an abstraction level.
* Token/Sentence/Paragraphs
*
* @param g graphics reference
* @param r rectangle
* @param s text to be drawn
*/
public static void drawThumbnails(final Graphics g, final ViewRect r,
final byte[] s) {
final double f = 0.25 * GUIProp.fontsize;
// thumbnail height
final int fh = (int) Math.max(1, 0.5 * GUIProp.fontsize);
// empty line height
final int lh = (int) Math.max(1, 0.35 * GUIProp.fontsize);
int nl = (int) (s.length * f / r.w);
if (nl * fh + (nl - 1) * lh < r.h * 0.8)
drawThumbnailsToken(g, r, s);
else {
final FTTokenizer ftt = new FTTokenizer(s);
final int[] c = ftt.countSenPar();
nl = (int) ((s.length - c[0]) * f / r.w);
if (nl * fh + (nl - 1 + c[2]) * lh < r.h) {
// choose sentence as abstraction level
drawThumbnailsSentence(g, r, s, true);
return;
}
nl = (int) ((s.length - c[0] - c[1]) * f / r.w);
if (nl * fh + (nl - 1 + c[2]) * lh < r.h) {
// choose paragraph as abstraction level
drawThumbnailsSentence(g, r, s, false);
return;
}
if (r.pos != null) drawTextinContext(g, r, s);
else drawThumbnailsSentence(g, r, s, false);
}
}
/**
* Draws a text using thumbnail visualization.
* @param g graphics reference
* @param r rectangle
* @param s text to be drawn
*/
public static void drawThumbnailsToken(final Graphics g, final ViewRect r,
final byte[] s) {
final double xx = r.x;
final double ww = r.w;
final double f = 0.25 * GUIProp.fontsize;
// thumbnail height
final int fh = (int) Math.max(1, 0.5 * GUIProp.fontsize);
// empty line height
final int lh = (int) Math.max(1, 0.8 * GUIProp.fontsize);
final double ys = r.y + 3;
double yy = ys;
int wl = 0; // word length
int ll = 0; // line length
final FTTokenizer ftt = new FTTokenizer(s);
final Color textc = g.getColor();
int count = 0;
int pp = 0;
int cs = 0;
int cp = 0;
int ftts;
while(ftt.more()) {
if (cs < ftt.sent) cs = ftt.sent;
if (cp < ftt.para) {
yy += lh;
ll = 0;
cp = ftt.para;
}
ftts = ftt.s;
wl = ftt.p - ftts;
// check if rectangle fits in line
if (f * (ll + wl) > ww) {
yy += lh;
ll = 0;
}
if(yy + lh >= r.y + r.h) return;
// draw word
if (r.pos != null && pp < r.pos.length && count == r.pos[pp]) {
pp++;
g.setColor(thumbnailcolor[r.poi[pp]]);
} else
g.setColor(textc);
final int xw = (int) Math.min(ww - f * ll - 4, f * wl);
g.fillRect((int) (xx + f * ll), (int) yy, xw, fh);
ll += wl;
count++;
ll++;
wl = 0;
}
}
/**
* Draws a text using thumbnail visualization.
* @param g graphics reference
* @param r rectangle
* @param s text to be drawn
* @param sen flag for sentence or paragraphe
*/
public static void drawThumbnailsSentence(final Graphics g, final ViewRect r,
final byte[] s, final boolean sen) {
final double xx = r.x;
final double ww = r.w;
final double f = 0.25 * GUIProp.fontsize;
// thumbnail height
final int fh = (int) Math.max(1, 0.5 * GUIProp.fontsize);
// empty line height
final int lh = (int) Math.max(1, 0.8 * GUIProp.fontsize);
final double ys = r.y + 3;
double yy = ys;
int wl = 0; // word length
int ll = 0; // line length
final FTTokenizer ftt = new FTTokenizer(s);
final Color textc = g.getColor();
int count = -1;
int pp = 0;
int cp = 0;
int cs = 0;
boolean m = ftt.more();
int lastl = 0;
while (m) {
while (ll + wl < ww && m &&
(cs == ftt.sent && sen || cp == ftt.para && !sen) &&
(r.pos == null || (pp < r.pos.length && count < r.pos[pp])
|| pp == r.pos.length)) {
lastl = (int) ((ftt.p - ftt.s) * f);
wl += lastl;
count++;
m = ftt.more();
if (!m) break;
}
// doesn't fit in line
if (ll + wl > ww) {
final int fp = (int) (ww - ll);
if (fp <= f) {
yy += lh;
ll = 0;
} else {
final int sp = wl - fp;
// draw first part of the sentence
g.fillRect((int) (xx + ll), (int) yy, (int) (fp - f), fh);
ll += fp - f;
// color last rect of first part of the word black
g.setColor(new Color(0, 0, 0));
g.fillRect((int) (xx + ll), (int) yy, (int) f, fh);
g.setColor(textc);
if(yy + lh >= r.y + r.h) return;
yy += lh;
ll = 0;
// color first rec of second part of the word black
g.setColor(new Color(0, 0, 0));
g.fillRect((int) xx, (int) yy, (int) f, fh);
g.setColor(textc);
wl = sp;
ll = (int) f;
}
}
// color thumbnail because of fulltext hint
if (r.pos != null && pp < r.pos.length && count == r.pos[pp]) {
if (lastl > 0) {
g.fillRect((int) (xx + ll), (int) yy, wl - lastl, fh);
ll += wl - lastl;
wl = lastl;
}
pp++;
g.setColor(thumbnailcolor[r.poi[pp]]);
}
if (wl + ll < ww) {
g.fillRect((int) (xx + ll), (int) yy, wl, fh);
g.setColor(textc);
ll += wl;
wl = 0;
}
// begin new line / new sentence
if (cs < ftt.sent && sen || cp < ftt.para && !sen) {
// new sentence
if (sen) {
ll += f;
cs = ftt.sent;
}
if (cp < ftt.para) {
cp = ftt.para;
yy += lh;
wl = 0;
ll = 0;
}
}
}
}
/**
* Draws a text token within its context.
* @param g graphics reference
* @param r rectangle
* @param s text to be drawn
*/
public static void drawTextinContext(final Graphics g, final ViewRect r,
final byte[] s) {
// limit string to given space
final int[] cw = fontWidths(g.getFont());
final int fh = (int) (1.2 * GUIProp.fontsize);
int xx = r.x;
int yy = r.y + fh;
final Color textc = g.getColor();
int count = 0;
int pp = 0;
int sw = 0;
IntList poic = new IntList();
final int wd = width(g, cw, '.');
final int we = width(g, cw, ' ');
final String e = new String(" ");
final String d = new String(".");
FTTokenizer ftt = new FTTokenizer(s);
while(ftt.more()) {
if (r.pos != null && pp < r.pos.length && count == r.pos[pp]) {
sw += sw == 0 ? we + wd * 2 : we + wd;
if (sw > r.w) {
yy += fh;
xx = r.x;
sw = 2 * we;
if (yy >= r.y + r.h) return;
}
g.drawString(sw == we + wd * 2 ? d + d + e : d + e, xx, yy);
xx = r.x + sw;
byte[] tok = new byte[0];
byte[] t = null;
int c = 0;
while(pp + c + 1 < r.poi.length &&
r.poi[pp + 1] == r.poi[pp + c + 1] &&
r.pos[pp] == r.pos[pp + c] - c) {
if(t != null) {
ftt.more();
count++;
}
t = ftt.get();
for (byte b : t)
sw += width(g, cw, b);
sw += we;
if (sw > r.w) {
yy += fh;
xx = r.x;
sw = 2 * we;
if (yy >= r.y + r.h) return;
}
tok = Array.add(tok, Array.add(t, new byte[]{' '}));
c++;
}
sw -= we;
pp = pp + c;
g.setColor(thumbnailcolor[r.poi[pp]]);
g.drawString(new String(tok), xx, yy);
g.setColor(textc);
if(!poic.contains(r.poi[pp])) poic.add(r.poi[pp]);
xx = r.x + sw;
int k = 0;
int ll;
while (k < 2 && ftt.more()) {
ll = sw;
count++;
if (r.pos != null && pp < r.pos.length && count == r.pos[pp]) {
pp++;
g.setColor(thumbnailcolor[r.poi[pp]]);
if(!poic.contains(r.poi[pp])) poic.add(r.poi[pp]);
} else g.setColor(textc);
sw += we;
if (sw > r.w) {
yy += fh;
xx = r.x;
sw = 2 * we;
if (yy >= r.y + r.h) return;
}
tok = ftt.get();
for (byte b : tok)
sw += width(g, cw, b);
if (sw > r.w) {
yy += fh;
xx = r.x;
sw = 2 * we;
if (yy >= r.y + r.h) return;
}
g.drawString(e + new String(tok), xx, yy);
g.setColor(textc);
xx += sw - ll;
k++;
}
sw += we + wd;
if (sw > r.w) {
yy += fh;
xx = r.x;
sw = 2 * we;
if (yy >= r.y + r.h) return;
}
g.drawString(e + d, xx, yy);
xx = r.x + sw;
if (r.poi != null && r.poi[0] == poic.size) {
g.drawString(d, xx, yy);
yy += fh;
xx = r.x;
sw = 0;
poic = new IntList();
}
if (yy >= r.y + r.h) return;
}
count++;
}
}
/**
* Returns the width of the specified text.
* Cached font widths are used to speed up calculation.
* @param g graphics reference
* @param s string to be evaluated
* @return string width
*/
public static int width(final Graphics g, final byte[] s) {
final int[] cw = fontWidths(g.getFont());
final int l = s.length;
int fw = 0;
try {
// ignore faulty character sets
for(int k = 0; k < l; k += cl(s[k])) fw += width(g, cw, cp(s, k));
} catch(final Exception ex) {
BaseX.debug(ex);
}
return fw;
}
/**
* Returns the character width of the specified character.
* @param g graphics reference
* @param cw character array
* @param c character
* @return character width
*/
private static int width(final Graphics g, final int[] cw, final int c) {
return c > 255 ? g.getFontMetrics().charWidth(c) : cw[c];
}
}
|
package ch.ethz.inf.vs.californium.dtls;
import java.io.RandomAccessFile;
import java.security.KeyFactory;
import java.security.MessageDigest;
import java.security.PrivateKey;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import ch.ethz.inf.vs.californium.coap.EndpointAddress;
import ch.ethz.inf.vs.californium.dtls.AlertMessage.AlertDescription;
import ch.ethz.inf.vs.californium.dtls.AlertMessage.AlertLevel;
import ch.ethz.inf.vs.californium.dtls.CertificateRequest.ClientCertificateType;
import ch.ethz.inf.vs.californium.dtls.CertificateRequest.DistinguishedName;
import ch.ethz.inf.vs.californium.dtls.CertificateRequest.HashAlgorithm;
import ch.ethz.inf.vs.californium.dtls.CertificateRequest.SignatureAlgorithm;
import ch.ethz.inf.vs.californium.dtls.CipherSuite.KeyExchangeAlgorithm;
/**
* Server handshaker does the protocol handshaking from the point of view of a
* server. It is message-driven by the parent {@link Handshaker} class.
*
* @author Stefan Jucker
*
*/
public class ServerHandshaker extends Handshaker {
// Members ////////////////////////////////////////////////////////
/** Is the client required to authenticate itself? */
private boolean clientAuthenticationRequired;
/** The server's certificate. */
private X509Certificate[] certificates;
/** The server's private key. */
private PrivateKey privateKey;
private List<CipherSuite> supportedCipherSuites;
/*
* Store all the the message which can possibly be sent by the client. We
* need these to compute the handshake hash.
*/
/** The client's {@link ClientHello}. Mandatory. */
protected ClientHello clientHello;
/** The client's {@link ClientHello} raw byte representation. Used for computing the handshake hash. */
private byte[] clientHelloBytes;
/** The client's {@link CertificateMessage}. Optional. */
protected CertificateMessage clientCertificate = null;
/** The client's {@link ClientKeyExchange}. mandatory. */
protected ClientKeyExchange clientKeyExchange;
/** The client's {@link CertificateVerify}. Optional. */
protected CertificateVerify certificateVerify = null;
/** The client's {@link Finished} message. Mandatory. */
protected Finished clientFinished;
/**
* The cookie generated to be sent in the {@link HelloVerifyRequest}. Store
* it, to verify the client's response.
*/
private Cookie cookie;
// Constructors ///////////////////////////////////////////////////
/**
*
* @param endpointAddress
* the peer's address.
* @param certificates
* the server's certificate chain.
* @param session
* the {@link DTLSSession}.
*/
public ServerHandshaker(EndpointAddress endpointAddress, X509Certificate[] certificates, DTLSSession session) {
super(endpointAddress, false, session);
this.certificates = certificates;
this.privateKey = loadPrivateKey("C:\\Users\\Jucker\\git\\Californium\\src\\ch\\ethz\\inf\\vs\\californium\\dtls\\ec3.pk8");
this.supportedCipherSuites = new ArrayList<CipherSuite>();
this.supportedCipherSuites.add(CipherSuite.SSL_NULL_WITH_NULL_NULL);
this.supportedCipherSuites.add(CipherSuite.TLS_PSK_WITH_AES_128_CCM_8);
this.supportedCipherSuites.add(CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8);
}
// Methods ////////////////////////////////////////////////////////
@Override
public synchronized DTLSFlight processMessage(Record record) {
if (lastFlight != null) {
// we already sent the last flight, but the client did not receive
// it, since we received its finished message again, so we
// retransmit our last flight
LOG.info("Received client's finished message again, retransmit the last flight.");
return lastFlight;
}
DTLSFlight flight = null;
if (!processMessageNext(record)) {
return flight;
}
switch (record.getType()) {
case ALERT:
AlertMessage alert = (AlertMessage) record.getFragment();
switch (alert.getDescription()) {
case CLOSE_NOTIFY:
flight = closeConnection();
break;
default:
break;
}
break;
case CHANGE_CIPHER_SPEC:
record.getFragment();
setCurrentReadState();
session.incrementReadEpoch();
break;
case HANDSHAKE:
HandshakeMessage fragment = (HandshakeMessage) record.getFragment();
switch (fragment.getMessageType()) {
case CLIENT_HELLO:
clientHelloBytes = record.getFragmentBytes();
flight = receivedClientHello((ClientHello) fragment);
break;
case CERTIFICATE:
clientCertificate = (CertificateMessage) fragment;
// TODO verify client's certificate
break;
case CLIENT_KEY_EXCHANGE:
byte[] premasterSecret;
switch (keyExchange) {
case PSK:
premasterSecret = receivedClientKeyExchange((PSKClientKeyExchange) fragment);
generateKeys(premasterSecret);
break;
case EC_DIFFIE_HELLMAN:
premasterSecret = receivedClientKeyExchange((ECDHClientKeyExchange) fragment);
generateKeys(premasterSecret);
break;
case NULL:
clientKeyExchange = (NULLClientKeyExchange) fragment;
// by current assumption we take an empty premaster secret
// to compute the master secret and the resulting keys
generateKeys(new byte[] {});
break;
default:
LOG.severe("Unknown key exchange algorithm: " + keyExchange);
break;
}
break;
case CERTIFICATE_VERIFY:
certificateVerify = (CertificateVerify) fragment;
// TODO verify this
break;
case FINISHED:
flight = receivedClientFinished((Finished) fragment);
break;
default:
LOG.severe("Server received not supported handshake message:\n" + fragment.toString());
break;
}
break;
default:
LOG.severe("Server received not supported record:\n" + record.toString());
break;
}
if (flight == null) {
Record nextMessage = null;
// check queued message, if it is now their turn
for (Record queuedMessage : queuedMessages) {
if (processMessageNext(queuedMessage)) {
// queuedMessages.remove(queuedMessage);
nextMessage = queuedMessage;
}
}
if (nextMessage != null) {
flight = processMessage(nextMessage);
}
}
LOG.info("DTLS Message processed.");
System.out.println(record.toString());
return flight;
}
/**
* Called, when the server received the client's {@link Finished} message.
* Generate a {@link DTLSFlight} containing the
* {@link ChangeCipherSpecMessage} and {@link Finished} message. This flight
* will not be retransmitted, unless we receive the same finish message in
* the future; then, we retransmit this flight.
*
* @param message
* the client's {@link Finished} message.
* @return the server's last {@link DTLSFlight}.
*/
private DTLSFlight receivedClientFinished(Finished message) {
if (lastFlight != null) {
return null;
}
DTLSFlight flight = new DTLSFlight();
clientFinished = message;
// create handshake hash
if (clientCertificate != null) { // optional
md.update(clientCertificate.toByteArray());
}
System.out.println("Client key exchange bytes: " + Arrays.toString(clientKeyExchange.toByteArray()));
md.update(clientKeyExchange.toByteArray()); // mandatory
if (certificateVerify != null) { // optional
md.update(certificateVerify.toByteArray());
}
MessageDigest mdWithClientFinished = null;
try {
/*
* the handshake_messages for the Finished message sent by the
* client will be different from that for the Finished message sent
* by the server, because the one that is sent second will include
* the prior one.
*/
mdWithClientFinished = (MessageDigest) md.clone();
mdWithClientFinished.update(clientFinished.toByteArray());
} catch (CloneNotSupportedException e) {
LOG.severe("Clone not supported.");
e.printStackTrace();
}
// Verify client's data
byte[] handshakeHash = md.digest();
if (!clientFinished.verifyData(getMasterSecret(), true, handshakeHash)) {
AlertMessage alert = new AlertMessage(AlertLevel.FATAL, AlertDescription.HANDSHAKE_FAILURE);
flight.addMessage(wrapMessage(alert));
flight.setRetransmissionNeeded(false);
return flight;
}
// First, send change cipher spec
ChangeCipherSpecMessage changeCipherSpecMessage = new ChangeCipherSpecMessage();
flight.addMessage(wrapMessage(changeCipherSpecMessage));
setCurrentWriteState();
session.incrementWriteEpoch();
// Second, send own finished message
handshakeHash = mdWithClientFinished.digest();
Finished finished = new Finished(getMasterSecret(), isClient, handshakeHash);
setSequenceNumber(finished);
flight.addMessage(wrapMessage(finished));
state = HandshakeType.FINISHED.getCode();
session.setActive(true);
flight.setRetransmissionNeeded(false);
// store, if we need to retransmit this flight, see
// http://tools.ietf.org/html/rfc6347#section-4.2.4
lastFlight = flight;
return flight;
}
/**
* Called after the server receives a {@link ClientHello} handshake message.
* If the message has a {@link Cookie} set, verify it and continue with
* {@link ServerHello}, otherwise reply with a {@link HelloVerifyRequest}.
*
* @param message
* the client's {@link ClientHello} message.
* @return list of {@link DTLSMessage} that need to be sent after receiving
* a {@link ClientHello}.
*/
private DTLSFlight receivedClientHello(ClientHello message) {
DTLSFlight flight = new DTLSFlight();
if (message.getCookie().length() > 0 && isValidCookie(message.getCookie())) {
// client has set a cookie, so it is a response to
// helloVerifyRequest
clientHello = message;
System.out.println("Client hello bytes: " + Arrays.toString(clientHello.toByteArray()));
md.update(clientHelloBytes);
/*
* First, send SERVER HELLO
*/
ProtocolVersion serverVersion = negotiateProtocolVersion(clientHello.getClientVersion());
// store client random
clientRandom = message.getRandom();
// server random
serverRandom = new Random(new SecureRandom());
SessionId sessionId = new SessionId();
session.setSessionIdentifier(sessionId);
CipherSuite cipherSuite = negotiateCipherSuite(clientHello.getCipherSuites());
setCipherSuite(cipherSuite);
CompressionMethod compressionMethod = CompressionMethod.NULL;
setCompressionMethod(compressionMethod);
ServerHello serverHello = new ServerHello(serverVersion, serverRandom, sessionId, cipherSuite, compressionMethod, null);
setSequenceNumber(serverHello);
flight.addMessage(wrapMessage(serverHello));
md.update(serverHello.toByteArray());
System.out.println("Server hello bytes: " + Arrays.toString(serverHello.toByteArray()));
/*
* Second, send CERTIFICATE, if necessary
*/
CertificateMessage certificate = null;
switch (keyExchange) {
case EC_DIFFIE_HELLMAN:
// TODO make this variable
certificate = new CertificateMessage(certificates, true);
break;
default:
// NULL and PSK do not require the Certificate message
// See http://tools.ietf.org/html/rfc4279#section-2
break;
}
if (certificate != null) {
setSequenceNumber(certificate);
flight.addMessage(wrapMessage(certificate));
md.update(certificate.toByteArray());
}
/*
* Third, send SERVER KEY EXCHANGE, if necessary
*/
ServerKeyExchange serverKeyExchange = null;
switch (keyExchange) {
case EC_DIFFIE_HELLMAN:
ecdhe = new ECDHECryptography(privateKey);
serverKeyExchange = new ECDHServerKeyExchange(ecdhe, privateKey, clientRandom, serverRandom);
break;
case PSK:
// serverKeyExchange = new PSKServerKeyExchange("TEST");
break;
default:
// NULL does not require the server's key exchange message
break;
}
if (serverKeyExchange != null) {
setSequenceNumber(serverKeyExchange);
flight.addMessage(wrapMessage(serverKeyExchange));
md.update(serverKeyExchange.toByteArray());
}
/*
* Fourth, if required, send CERTIFICATE REQUEST for client, PSK
* does not require this message.
*/
if (clientAuthenticationRequired && keyExchange != KeyExchangeAlgorithm.PSK) {
CertificateRequest certificateRequest = new CertificateRequest();
certificateRequest.addCertificateType(ClientCertificateType.ECDSA_FIXED_ECDH);
certificateRequest.addSignatureAlgorithm(new SignatureAndHashAlgorithm(HashAlgorithm.MD5, SignatureAlgorithm.ECDSA));
certificateRequest.addCertificateAuthority(new DistinguishedName(new byte[6]));
setSequenceNumber(certificateRequest);
flight.addMessage(wrapMessage(certificateRequest));
md.update(certificateRequest.toByteArray());
}
/*
* Last, send SERVER HELLO DONE
*/
ServerHelloDone serverHelloDone = new ServerHelloDone();
setSequenceNumber(serverHelloDone);
flight.addMessage(wrapMessage(serverHelloDone));
md.update(serverHelloDone.toByteArray());
System.out.println("Server hello done bytes: " + Arrays.toString(serverHelloDone.toByteArray()));
} else {
// either first time, or cookies did not match
cookie = generateCookie();
HelloVerifyRequest helloVerifyRequest = new HelloVerifyRequest(new ProtocolVersion(), cookie);
setSequenceNumber(helloVerifyRequest);
flight.addMessage(wrapMessage(helloVerifyRequest));
}
return flight;
}
private byte[] receivedClientKeyExchange(ECDHClientKeyExchange message) {
clientKeyExchange = message;
byte[] premasterSecret = ecdhe.getSecret(message.getEncodedPoint()).getEncoded();
return premasterSecret;
}
private byte[] receivedClientKeyExchange(PSKClientKeyExchange message) {
clientKeyExchange = message;
// use the client's PSK identity to get right preshared key
String identity = message.getIdentity();
byte[] psk = sharedKeys.get(identity);
return generatePremasterSecretFromPSK(psk);
}
private Cookie generateCookie() {
// TODO as suggested in http://tools.ietf.org/html/rfc6347#section-4.2.1
// Cookie = HMAC(Secret, Client-IP, Client-Parameters)
return new Cookie(new Random(new SecureRandom()).getRandomBytes());
}
/**
*
* @param clientCookie
* the cookie in the client's hello message.
* @return <code>true</code> if the cookie matches, <code>false</code>
* otherwise.
*/
private boolean isValidCookie(Cookie clientCookie) {
return Arrays.equals(cookie.getCookie(), clientCookie.getCookie());
}
@Override
public DTLSFlight getStartHandshakeMessage() {
HelloRequest helloRequest = new HelloRequest();
setSequenceNumber(helloRequest);
DTLSFlight flight = new DTLSFlight();
flight.addMessage(wrapMessage(helloRequest));
return flight;
}
/**
* Negotiates the version to be used. It will return the lower of that
* suggested by the client in the client hello and the highest supported by
* the server.
*
* @param clientVersion
* the suggested version by the client.
* @return the version to be used in the handshake.
*/
private ProtocolVersion negotiateProtocolVersion(ProtocolVersion clientVersion) {
return new ProtocolVersion();
}
/**
* Selects one of the client's proposed cipher suites.
*
* @param cipherSuites
* the client's cipher suites.
* @return The single cipher suite selected by the server from the list.
*/
private CipherSuite negotiateCipherSuite(List<CipherSuite> cipherSuites) {
// the client's list is sorted by preference
for (CipherSuite cipherSuite : cipherSuites) {
if (supportedCipherSuites.contains(cipherSuite)) {
return cipherSuite;
}
}
return CipherSuite.SSL_NULL_WITH_NULL_NULL;
}
/**
* Loads the private key from a file encoded according to the PKCS #8
* standard.
*
* @param filename
* the filename where the private key resides.
* @return the private key.
*/
private PrivateKey loadPrivateKey(String filename) {
PrivateKey privateKey = null;
try {
RandomAccessFile raf = new RandomAccessFile(filename, "r");
byte[] encodedKey = new byte[(int) raf.length()];
raf.readFully(encodedKey);
raf.close();
PKCS8EncodedKeySpec kspec = new PKCS8EncodedKeySpec(encodedKey);
KeyFactory keyF = KeyFactory.getInstance("EC");
privateKey = keyF.generatePrivate(kspec);
} catch (Exception e) {
LOG.severe("Could not load private key: " + filename);
e.printStackTrace();
}
return privateKey;
}
}
|
package com.datatorrent.stram;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.lang.Thread.State;
import java.net.*;
import java.util.*;
import java.util.AbstractMap.SimpleEntry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import net.engio.mbassy.bus.BusConfiguration;
import net.engio.mbassy.bus.MBassador;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.ipc.RPC;
import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem;
import org.apache.hadoop.net.NetUtils;
import org.apache.hadoop.util.StringUtils;
import org.apache.log4j.LogManager;
import com.datatorrent.api.*;
import com.datatorrent.api.DAG.Locality;
import com.datatorrent.api.Operator.InputPort;
import com.datatorrent.api.Operator.OutputPort;
import com.datatorrent.api.Operator.ProcessingMode;
import com.datatorrent.api.StatsListener.OperatorCommand;
import com.datatorrent.bufferserver.server.Server;
import com.datatorrent.bufferserver.storage.DiskStorage;
import com.datatorrent.bufferserver.util.Codec;
import com.datatorrent.common.util.ScheduledThreadPoolExecutor;
import com.datatorrent.netlet.DefaultEventLoop;
import com.datatorrent.stram.OperatorDeployInfo.OperatorType;
import com.datatorrent.stram.api.*;
import com.datatorrent.stram.api.ContainerEvent.ContainerStatsEvent;
import com.datatorrent.stram.api.ContainerEvent.NodeActivationEvent;
import com.datatorrent.stram.api.ContainerEvent.NodeDeactivationEvent;
import com.datatorrent.stram.api.ContainerEvent.StreamActivationEvent;
import com.datatorrent.stram.api.ContainerEvent.StreamDeactivationEvent;
import com.datatorrent.stram.api.StreamingContainerUmbilicalProtocol.ContainerHeartbeat;
import com.datatorrent.stram.api.StreamingContainerUmbilicalProtocol.ContainerHeartbeatResponse;
import com.datatorrent.stram.api.StreamingContainerUmbilicalProtocol.ContainerStats;
import com.datatorrent.stram.api.StreamingContainerUmbilicalProtocol.OperatorHeartbeat;
import com.datatorrent.stram.api.StreamingContainerUmbilicalProtocol.StramToNodeRequest;
import com.datatorrent.stram.api.StreamingContainerUmbilicalProtocol.StreamingContainerContext;
import com.datatorrent.stram.debug.StdOutErrLog;
import com.datatorrent.stram.engine.Node;
import com.datatorrent.stram.engine.OperatorContext;
import com.datatorrent.stram.engine.PortContext;
import com.datatorrent.stram.engine.Stream;
import com.datatorrent.stram.engine.StreamContext;
import com.datatorrent.stram.engine.SweepableReservoir;
import com.datatorrent.stram.engine.WindowGenerator;
import com.datatorrent.stram.engine.WindowIdActivatedReservoir;
import com.datatorrent.stram.plan.logical.LogicalPlan;
import com.datatorrent.stram.plan.logical.Operators.PortContextPair;
import com.datatorrent.stram.plan.logical.Operators.PortMappingDescriptor;
import com.datatorrent.stram.stream.BufferServerPublisher;
import com.datatorrent.stram.stream.BufferServerSubscriber;
import com.datatorrent.stram.stream.FastPublisher;
import com.datatorrent.stram.stream.FastSubscriber;
import com.datatorrent.stram.stream.InlineStream;
import com.datatorrent.stram.stream.MuxStream;
import com.datatorrent.stram.stream.OiOStream;
import com.datatorrent.stram.stream.PartitionAwareSink;
/**
* Object which controls the container process launched by {@link com.datatorrent.stram.StramAppMaster}.
*
* @since 0.3.2
*/
public class StramChild
{
public static final int PORT_QUEUE_CAPACITY = 1024;
private final String containerId;
private final Configuration conf;
private final StreamingContainerUmbilicalProtocol umbilical;
protected final Map<Integer, Node<?>> nodes = new ConcurrentHashMap<Integer, Node<?>>();
protected final Set<Integer> failedNodes = Collections.newSetFromMap(new ConcurrentHashMap<Integer, Boolean>());
private final Map<String, ComponentContextPair<Stream, StreamContext>> streams = new ConcurrentHashMap<String, ComponentContextPair<Stream, StreamContext>>();
private final Map<String, ComponentContextPair<Stream, StreamContext>> disConnectedStreams = new ConcurrentHashMap<String, ComponentContextPair<Stream, StreamContext>>();
protected final Map<Integer, WindowGenerator> generators = new ConcurrentHashMap<Integer, WindowGenerator>();
/**
* OIO groups map
* key: operator id of oio owning thread node
* value: list of nodes which are in oio with oio owning thread node
*/
protected final Map<Integer, ArrayList<Integer>> oioGroups = new ConcurrentHashMap<Integer, ArrayList<Integer>>();
protected final Map<Integer, OperatorContext> activeNodes = new ConcurrentHashMap<Integer, OperatorContext>();
private final Map<Stream, StreamContext> activeStreams = new ConcurrentHashMap<Stream, StreamContext>();
private final Map<WindowGenerator, Object> activeGenerators = new ConcurrentHashMap<WindowGenerator, Object>();
private int heartbeatIntervalMillis = 1000;
private volatile boolean exitHeartbeatLoop = false;
private final Object heartbeatTrigger = new Object();
private String checkpointFsPath;
public static DefaultEventLoop eventloop;
/**
* List of listeners interested in listening into the status change of the nodes.
*/
private long firstWindowMillis;
private int windowWidthMillis;
private InetSocketAddress bufferServerAddress;
private com.datatorrent.bufferserver.server.Server bufferServer;
private int checkpointWindowCount;
private boolean fastPublisherSubscriber;
private StreamingContainerContext containerContext;
private List<StramToNodeRequest> nodeRequests;
private final HashMap<String, Object> singletons;
private final MBassador<ContainerEvent> eventBus; // event bus for publishing container events
HashSet<Component<ContainerContext>> components;
private RequestFactory requestFactory;
static {
try {
eventloop = new DefaultEventLoop("ProcessWideEventLoop");
}
catch (IOException io) {
throw new RuntimeException(io);
}
}
protected StramChild(String containerId, Configuration conf, StreamingContainerUmbilicalProtocol umbilical)
{
this.components = new HashSet<Component<ContainerContext>>();
this.eventBus = new MBassador<ContainerEvent>(BusConfiguration.Default());
this.singletons = new HashMap<String, Object>();
this.nodeRequests = new ArrayList<StramToNodeRequest>();
logger.debug("instantiated StramChild {}", containerId);
this.umbilical = umbilical;
this.containerId = containerId;
this.conf = conf;
}
@SuppressWarnings("unchecked")
public void setup(StreamingContainerContext ctx)
{
containerContext = ctx;
/* add a request factory local to this container */
this.requestFactory = new RequestFactory();
ctx.attributes.put(ContainerContext.REQUEST_FACTORY, requestFactory);
heartbeatIntervalMillis = ctx.getValue(DAGContext.HEARTBEAT_INTERVAL_MILLIS);
firstWindowMillis = ctx.startWindowMillis;
windowWidthMillis = ctx.getValue(DAGContext.STREAMING_WINDOW_SIZE_MILLIS);
checkpointWindowCount = ctx.getValue(DAGContext.CHECKPOINT_WINDOW_COUNT);
checkpointFsPath = ctx.getValue(DAGContext.APPLICATION_PATH) + "/" + LogicalPlan.SUBDIR_CHECKPOINTS;
fastPublisherSubscriber = ctx.getValue(LogicalPlan.FAST_PUBLISHER_SUBSCRIBER);
try {
if (ctx.deployBufferServer) {
eventloop.start();
// start buffer server, if it was not set externally
bufferServer = new Server(0, 64 * 1024 * 1024);
bufferServer.setSpoolStorage(new DiskStorage());
SocketAddress bindAddr = bufferServer.run(eventloop);
logger.info("Buffer server started: {}", bindAddr);
this.bufferServerAddress = NetUtils.getConnectAddress(((InetSocketAddress)bindAddr));
}
}
catch (Exception ex) {
logger.warn("deploy request failed due to {}", ex);
throw new IllegalStateException("Failed to deploy buffer server", ex);
}
for (Class<?> clazz : ContainerEvent.CONTAINER_EVENTS_LISTENERS) {
try {
Object newInstance = clazz.newInstance();
singletons.put(clazz.getName(), newInstance);
if (newInstance instanceof Component) {
components.add((Component<ContainerContext>)newInstance);
}
eventBus.subscribe(newInstance);
}
catch (Exception ex) {
logger.warn("Container Event Listener Instantiation", ex);
}
}
operateListeners(ctx, true);
}
public String getContainerId()
{
return this.containerId;
}
/**
* This method is introduced as replacement for getTupleRecorder method which was cluttering the code.
*
* @param classname
* @return
*/
public Object getInstance(String classname)
{
return singletons.get(classname);
}
/**
* Initialize container. Establishes heartbeat connection to the master
* distribute through the callback address provided on the command line. Deploys
* initial modules, then enters the heartbeat loop, which will only terminate
* once container receives shutdown request from the master. On shutdown,
* after exiting heartbeat loop, shutdown all modules and terminate
* processing threads.
*
* @param args
* @throws Throwable
*/
public static void main(String[] args) throws Throwable
{
StdOutErrLog.tieSystemOutAndErrToLog();
logger.debug("PID: " + System.getenv().get("JVM_PID"));
logger.info("Child starting with classpath: {}", System.getProperty("java.class.path"));
final Configuration defaultConf = new Configuration();
String host = args[0];
int port = Integer.parseInt(args[1]);
final InetSocketAddress address = NetUtils.createSocketAddrForHost(host, port);
final StreamingContainerUmbilicalProtocol umbilical = RPC.getProxy(StreamingContainerUmbilicalProtocol.class,
StreamingContainerUmbilicalProtocol.versionID, address, defaultConf);
int exitStatus = 1; // interpreted as unrecoverable container failure
final String childId = System.getProperty("stram.cid");
try {
StreamingContainerContext ctx = umbilical.getInitContext(childId);
StramChild stramChild = new StramChild(childId, defaultConf, umbilical);
logger.debug("Got context: " + ctx);
stramChild.setup(ctx);
try {
/* main thread enters heartbeat loop */
stramChild.heartbeatLoop();
exitStatus = 0;
}
finally {
stramChild.teardown();
}
}
catch (Exception exception) {
logger.warn("Exception running child : " + exception);
/* Report back any failures, for diagnostic purposes */
ByteArrayOutputStream baos = new ByteArrayOutputStream();
exception.printStackTrace(new PrintStream(baos));
umbilical.log(childId, "FATAL: " + baos.toString());
}
catch (Throwable throwable) {
logger.error("Error running child : "
+ StringUtils.stringifyException(throwable));
Throwable tCause = throwable.getCause();
String cause = tCause == null
? throwable.getMessage()
: StringUtils.stringifyException(tCause);
umbilical.log(childId, cause);
}
finally {
RPC.stopProxy(umbilical);
//FileSystem.closeAll();
DefaultMetricsSystem.shutdown();
// Shutting down log4j of the child-vm...
logger.info("exit status: {}", exitStatus);
LogManager.shutdown();
}
if (exitStatus != 0) {
System.exit(exitStatus);
}
}
public synchronized void deactivate()
{
ArrayList<Thread> activeThreads = new ArrayList<Thread>();
ArrayList<Integer> activeOperators = new ArrayList<Integer>();
for (Map.Entry<Integer, Node<?>> e : nodes.entrySet()) {
OperatorContext oc = activeNodes.get(e.getKey());
if (oc == null) {
disconnectNode(e.getKey());
}
else {
activeThreads.add(oc.getThread());
activeOperators.add(e.getKey());
e.getValue().shutdown();
}
}
try {
Iterator<Integer> iterator = activeOperators.iterator();
for (Thread t : activeThreads) {
t.join();
disconnectNode(iterator.next());
}
assert (activeNodes.isEmpty());
}
catch (InterruptedException ex) {
logger.info("Aborting wait for for operators to get deactivated as got interrupted with {}", ex);
}
for (WindowGenerator wg : activeGenerators.keySet()) {
wg.deactivate();
}
activeGenerators.clear();
for (Stream stream : activeStreams.keySet()) {
stream.deactivate();
}
activeStreams.clear();
}
private void disconnectNode(int nodeid)
{
Node<?> node = nodes.get(nodeid);
disconnectWindowGenerator(nodeid, node);
PortMappingDescriptor portMappingDescriptor = node.getPortMappingDescriptor();
Iterator<String> outputPorts = portMappingDescriptor.outputPorts.keySet().iterator();
while (outputPorts.hasNext()) {
String sourceIdentifier = String.valueOf(nodeid).concat(Component.CONCAT_SEPARATOR).concat(outputPorts.next());
ComponentContextPair<Stream, StreamContext> pair = streams.remove(sourceIdentifier);
if (pair != null) {
if (activeStreams.remove(pair.component) != null) {
pair.component.deactivate();
eventBus.publish(new StreamDeactivationEvent(pair));
}
if (pair.component instanceof Stream.MultiSinkCapableStream) {
String sinks = pair.context.getSinkId();
if (sinks == null) {
logger.error("mux sinks found connected at {} with sink id null", sourceIdentifier);
}
else {
String[] split = sinks.split(", ");
for (int i = split.length; i
ComponentContextPair<Stream, StreamContext> spair = streams.remove(split[i]);
if (spair == null) {
spair = disConnectedStreams.get(split[i]);
if (spair == null) {
logger.error("mux is missing the stream for sink {}", split[i]);
}
else {
logger.debug("already removed {}", split[i]);
}
}
else {
if (activeStreams.remove(spair.component) != null) {
spair.component.deactivate();
eventBus.publish(new StreamDeactivationEvent(spair));
}
spair.component.teardown();
}
}
}
}
else {
// it's either inline stream or it's bufferserver publisher.
}
pair.component.teardown();
}
}
Iterator<String> inputPorts = portMappingDescriptor.inputPorts.keySet().iterator();
while (inputPorts.hasNext()) {
String sinkIdentifier = String.valueOf(nodeid).concat(Component.CONCAT_SEPARATOR).concat(inputPorts.next());
ComponentContextPair<Stream, StreamContext> pair = streams.remove(sinkIdentifier);
if (pair != null) {
if (activeStreams.remove(pair.component) != null) {
pair.component.deactivate();
eventBus.publish(new StreamDeactivationEvent(pair));
}
disConnectedStreams.put(sinkIdentifier, pair);
pair.component.teardown();
}
}
}
private void disconnectWindowGenerator(int nodeid, Node<?> node)
{
WindowGenerator chosen1 = generators.remove(nodeid);
if (chosen1 != null) {
chosen1.releaseReservoir(Integer.toString(nodeid).concat(Component.CONCAT_SEPARATOR).concat(Node.INPUT));
// should we send the closure of the port to the node?
int count = 0;
for (WindowGenerator wg : generators.values()) {
if (chosen1 == wg) {
count++;
}
}
if (count == 0) {
activeGenerators.remove(chosen1);
chosen1.deactivate();
chosen1.teardown();
}
}
}
private synchronized void undeploy(List<OperatorDeployInfo> nodeList)
{
logger.info("got undeploy request {}", nodeList);
/**
* make sure that all the operators which we are asked to undeploy are in this container.
*/
HashMap<Integer, Node<?>> toUndeploy = new HashMap<Integer, Node<?>>();
for (OperatorDeployInfo ndi : nodeList) {
Node<?> node = nodes.get(ndi.id);
if (node == null) {
throw new IllegalArgumentException("Node " + ndi.id + " is not hosted in this container!");
}
else if (toUndeploy.containsKey(ndi.id)) {
throw new IllegalArgumentException("Node " + ndi.id + " is requested to be undeployed more than once");
}
else {
toUndeploy.put(ndi.id, node);
}
}
ArrayList<Thread> joinList = new ArrayList<Thread>();
ArrayList<Integer> discoList = new ArrayList<Integer>();
for (OperatorDeployInfo ndi : nodeList) {
OperatorContext oc = activeNodes.get(ndi.id);
if (oc == null) {
disconnectNode(ndi.id);
}
else {
joinList.add(oc.getThread());
discoList.add(ndi.id);
nodes.get(ndi.id).shutdown();
}
}
try {
Iterator<Integer> iterator = discoList.iterator();
for (Thread t : joinList) {
t.join(1000);
if (!t.getState().equals(State.TERMINATED)) {
t.interrupt();
}
disconnectNode(iterator.next());
}
logger.info("undeploy complete");
}
catch (InterruptedException ex) {
logger.warn("Aborted waiting for the deactivate to finish!");
}
for (OperatorDeployInfo ndi : nodeList) {
nodes.remove(ndi.id);
}
}
public void teardown()
{
operateListeners(containerContext, false);
deactivate();
disConnectedStreams.clear();
assert (streams.isEmpty());
nodes.clear();
HashSet<WindowGenerator> gens = new HashSet<WindowGenerator>();
gens.addAll(generators.values());
generators.clear();
for (WindowGenerator wg : gens) {
wg.teardown();
}
if (bufferServer != null) {
eventloop.stop(bufferServer);
eventloop.stop();
}
gens.clear();
}
protected void triggerHeartbeat()
{
synchronized (heartbeatTrigger) {
heartbeatTrigger.notifyAll();
}
}
protected void heartbeatLoop() throws Exception
{
umbilical.log(containerId, "[" + containerId + "] Entering heartbeat loop..");
logger.debug("Entering heartbeat loop (interval is {} ms)", this.heartbeatIntervalMillis);
while (!exitHeartbeatLoop) {
synchronized (this.heartbeatTrigger) {
try {
this.heartbeatTrigger.wait(heartbeatIntervalMillis);
}
catch (InterruptedException e1) {
logger.warn("Interrupted in heartbeat loop, exiting..");
break;
}
}
long currentTime = System.currentTimeMillis();
ContainerHeartbeat msg = new ContainerHeartbeat();
ContainerStats stats = new ContainerStats(containerId);
msg.setContainerStats(stats);
msg.jvmName = java.lang.management.ManagementFactory.getRuntimeMXBean().getName();
if (this.bufferServerAddress != null) {
msg.bufferServerHost = this.bufferServerAddress.getHostName();
msg.bufferServerPort = this.bufferServerAddress.getPort();
if (bufferServer != null && !eventloop.isActive()) {
logger.warn("Requesting restart due to terminated event loop");
msg.restartRequested = true;
}
}
msg.memoryMBFree = ((int)(Runtime.getRuntime().freeMemory() / (1024 * 1024)));
// gather heartbeat info for all operators
for (Map.Entry<Integer, Node<?>> e : nodes.entrySet()) {
OperatorHeartbeat hb = new OperatorHeartbeat();
hb.setNodeId(e.getKey());
hb.setGeneratedTms(currentTime);
hb.setIntervalMs(heartbeatIntervalMillis);
OperatorContext ctx = activeNodes.get(e.getKey());
if (ctx != null) {
ctx.drainStats(hb.getOperatorStatsContainer());
hb.setState(OperatorHeartbeat.DeployState.ACTIVE.toString());
}
else {
String state = failedNodes.contains(e.getKey()) ? OperatorHeartbeat.DeployState.FAILED.toString() : OperatorHeartbeat.DeployState.IDLE.toString();
logger.debug("Sending {} state for operator {}", state, e.getKey());
hb.setState(state);
}
stats.addNodeStats(hb);
}
/**
* Container stats published for whoever is interested in listening.
* Currently interested candidates are TupleRecorderCollection and BufferServerStatsSubscriber
*/
eventBus.publish(new ContainerStatsEvent(stats));
// heartbeat call and follow-up processing
//logger.debug("Sending heartbeat for {} operators.", msg.getContainerStats().size());
ContainerHeartbeatResponse rsp = umbilical.processHeartbeat(msg);
if (rsp != null) {
processHeartbeatResponse(rsp);
// keep polling at smaller interval if work is pending
while (rsp != null && rsp.hasPendingRequests) {
logger.info("Waiting for pending request.");
synchronized (this.heartbeatTrigger) {
try {
this.heartbeatTrigger.wait(500);
}
catch (InterruptedException e1) {
logger.warn("Interrupted in heartbeat loop, exiting..");
break;
}
}
rsp = umbilical.pollRequest(this.containerId);
if (rsp != null) {
processHeartbeatResponse(rsp);
}
}
}
}
logger.debug("Exiting hearbeat loop");
umbilical.log(containerId, "[" + containerId + "] Exiting heartbeat loop..");
}
private long lastCommittedWindowId = WindowGenerator.MIN_WINDOW_ID - 1;
private void processNodeRequests(boolean flagInvalid)
{
for (Iterator<StramToNodeRequest> it = nodeRequests.iterator(); it.hasNext();) {
StramToNodeRequest req = it.next();
OperatorContext oc = activeNodes.get(req.getOperatorId());
if (oc == null) {
if (flagInvalid) {
logger.warn("Received request with invalid operator id {} ({})", req.getOperatorId(), req);
it.remove();
}
}
else {
logger.debug("request received: {}", req);
OperatorCommand requestExecutor = requestFactory.getRequestExecutor(nodes.get(req.operatorId), req);
if (requestExecutor != null) {
oc.request(requestExecutor);
}
else {
logger.warn("No executor identified for the request {}", req);
}
it.remove();
}
}
}
protected void processHeartbeatResponse(ContainerHeartbeatResponse rsp)
{
if (rsp.nodeRequests != null) {
nodeRequests = rsp.nodeRequests;
}
if (rsp.committedWindowId != lastCommittedWindowId) {
lastCommittedWindowId = rsp.committedWindowId;
OperatorCommand nr = null;
for (Map.Entry<Integer, OperatorContext> e : activeNodes.entrySet()) {
Node<?> node = nodes.get(e.getKey());
if (node == null) {
continue;
}
if (node.getOperator() instanceof CheckpointListener) {
if (nr == null) {
nr = new OperatorCommand()
{
@Override
public void execute(Operator operator, int id, long windowId) throws IOException
{
((CheckpointListener)operator).committed(lastCommittedWindowId);
}
};
}
e.getValue().request(nr);
}
}
}
if (rsp.shutdown) {
logger.info("Received shutdown request");
processNodeRequests(false);
this.exitHeartbeatLoop = true;
return;
}
if (rsp.undeployRequest != null) {
logger.info("Undeploy request: {}", rsp.undeployRequest);
processNodeRequests(false);
undeploy(rsp.undeployRequest);
}
if (rsp.deployRequest != null) {
logger.info("Deploy request: {}", rsp.deployRequest);
try {
deploy(rsp.deployRequest);
}
catch (Exception e) {
logger.error("deploy request failed", e);
// TODO: report it to stram?
try {
umbilical.log(this.containerId, "deploy request failed: " + rsp.deployRequest + " " + ExceptionUtils.getStackTrace(e));
}
catch (IOException ioe) {
// ignore
}
this.exitHeartbeatLoop = true;
throw new IllegalStateException("Deploy request failed: " + rsp.deployRequest, e);
}
}
processNodeRequests(true);
}
private int getOutputQueueCapacity(List<OperatorDeployInfo> operatorList, int sourceOperatorId, String sourcePortName)
{
for (OperatorDeployInfo odi : operatorList) {
if (odi.id == sourceOperatorId) {
for (OperatorDeployInfo.OutputDeployInfo odiodi : odi.outputs) {
if (odiodi.portName.equals(sourcePortName)) {
return odiodi.getValue(PortContext.QUEUE_CAPACITY);
}
}
}
}
return PortContext.QUEUE_CAPACITY.defaultValue;
}
private synchronized void deploy(List<OperatorDeployInfo> nodeList) throws Exception
{
/*
* A little bit of up front sanity check would reduce the percentage of deploy failures later.
*/
for (OperatorDeployInfo ndi : nodeList) {
if (nodes.containsKey(ndi.id)) {
throw new IllegalStateException("Node with id: " + ndi.id + " already present in the container");
}
}
deployNodes(nodeList);
HashMap<String, ArrayList<String>> groupedInputStreams = new HashMap<String, ArrayList<String>>();
for (OperatorDeployInfo ndi : nodeList) {
groupInputStreams(groupedInputStreams, ndi);
}
HashMap<String, ComponentContextPair<Stream, StreamContext>> newStreams = deployOutputStreams(nodeList, groupedInputStreams);
deployInputStreams(nodeList, newStreams);
for (ComponentContextPair<Stream, StreamContext> pair : newStreams.values()) {
pair.component.setup(pair.context);
}
streams.putAll(newStreams);
HashMap<Integer, OperatorDeployInfo> operatorMap = new HashMap<Integer, OperatorDeployInfo>(nodeList.size());
for (OperatorDeployInfo o : nodeList) {
operatorMap.put(o.id, o);
}
activate(operatorMap, newStreams);
}
public static String getUnifierInputPortName(String portName, int sourceNodeId, String sourcePortName)
{
return portName + "(" + sourceNodeId + Component.CONCAT_SEPARATOR + sourcePortName + ")";
}
private void massageUnifierDeployInfo(OperatorDeployInfo odi)
{
for (OperatorDeployInfo.InputDeployInfo idi : odi.inputs) {
idi.portName = getUnifierInputPortName(idi.portName, idi.sourceNodeId, idi.sourcePortName);
}
}
private void deployNodes(List<OperatorDeployInfo> nodeList) throws Exception
{
for (OperatorDeployInfo ndi : nodeList) {
StorageAgent backupAgent;
if (ndi.contextAttributes == null) {
backupAgent = new FSStorageAgent(this.conf, this.checkpointFsPath);
}
else {
backupAgent = ndi.contextAttributes.get(OperatorContext.STORAGE_AGENT);
if (backupAgent == null) {
backupAgent = new FSStorageAgent(this.conf, this.checkpointFsPath);
ndi.contextAttributes.put(OperatorContext.STORAGE_AGENT, backupAgent);
}
}
try {
logger.debug("Restoring node {} to checkpoint {}", ndi.id, Codec.getStringWindowId(ndi.checkpointWindowId));
InputStream stream = backupAgent.getLoadStream(ndi.id, ndi.checkpointWindowId);
Node<?> node = Node.retrieveNode(stream, ndi.type);
stream.close();
node.currentWindowId = ndi.checkpointWindowId;
if (ndi.type == OperatorDeployInfo.OperatorType.UNIFIER) {
massageUnifierDeployInfo(ndi);
}
node.setId(ndi.id);
nodes.put(ndi.id, node);
logger.debug("Marking deployed {}", node);
}
catch (Exception e) {
logger.error("Deploy error", e);
throw e;
}
}
}
private HashMap.SimpleEntry<String, ComponentContextPair<Stream, StreamContext>> deployBufferServerPublisher(
String sourceIdentifier, long startingWindowId, int queueCapacity, OperatorDeployInfo.OutputDeployInfo nodi)
throws UnknownHostException
{
String sinkIdentifier = "tcp://".concat(nodi.bufferServerHost).concat(":").concat(String.valueOf(nodi.bufferServerPort)).concat("/").concat(sourceIdentifier);
StreamContext bssc = new StreamContext(nodi.declaredStreamId);
bssc.setSourceId(sourceIdentifier);
bssc.setSinkId(sinkIdentifier);
bssc.setFinishedWindowId(startingWindowId);
bssc.put(StreamContext.CODEC, StramUtils.getSerdeInstance(nodi.serDeClassName));
bssc.put(StreamContext.EVENT_LOOP, eventloop);
bssc.setBufferServerAddress(InetSocketAddress.createUnresolved(nodi.bufferServerHost, nodi.bufferServerPort));
if (NetUtils.isLocalAddress(bssc.getBufferServerAddress().getAddress())) {
bssc.setBufferServerAddress(new InetSocketAddress(InetAddress.getByName(null), nodi.bufferServerPort));
}
Stream publisher = fastPublisherSubscriber ? new FastPublisher(sourceIdentifier, queueCapacity * 256) : new BufferServerPublisher(sourceIdentifier, queueCapacity);
return new HashMap.SimpleEntry<String, ComponentContextPair<Stream, StreamContext>>(sinkIdentifier, new ComponentContextPair<Stream, StreamContext>(publisher, bssc));
}
private HashMap<String, ComponentContextPair<Stream, StreamContext>> deployOutputStreams(
List<OperatorDeployInfo> nodeList, HashMap<String, ArrayList<String>> groupedInputStreams)
throws Exception
{
HashMap<String, ComponentContextPair<Stream, StreamContext>> newStreams = new HashMap<String, ComponentContextPair<Stream, StreamContext>>();
/*
* We proceed to deploy all the output streams. At the end of this block, our streams collection
* will contain all the streams which originate at the output port of the operators. The streams
* are generally mapped against the "nodename.portname" string. But the BufferServerPublishers which
* share the output port with other inline streams are mapped against the Buffer Server port to
* avoid collision and at the same time keep track of these buffer streams.
*/
for (OperatorDeployInfo ndi : nodeList) {
Node<?> node = nodes.get(ndi.id);
long finishedWindowId = ndi.checkpointWindowId > 0 ? ndi.checkpointWindowId : 0;
for (OperatorDeployInfo.OutputDeployInfo nodi : ndi.outputs) {
String sourceIdentifier = Integer.toString(ndi.id).concat(Component.CONCAT_SEPARATOR).concat(nodi.portName);
int queueCapacity = nodi.getValue(PortContext.QUEUE_CAPACITY);
logger.debug("for stream {} the queue capacity is {}", sourceIdentifier, queueCapacity);
ArrayList<String> collection = groupedInputStreams.get(sourceIdentifier);
if (collection == null) {
assert (nodi.bufferServerHost != null): "resulting stream cannot be inline: " + nodi;
/*
* Let's create a stream to carry the data to the Buffer Server.
* Nobody in this container is interested in the output placed on this stream, but
* this stream exists. That means someone outside of this container must be interested.
*/
SimpleEntry<String, ComponentContextPair<Stream, StreamContext>> deployBufferServerPublisher =
deployBufferServerPublisher(sourceIdentifier, finishedWindowId, queueCapacity, nodi);
newStreams.put(sourceIdentifier, deployBufferServerPublisher.getValue());
node.connectOutputPort(nodi.portName, deployBufferServerPublisher.getValue().component);
}
else {
/*
* In this case we have 2 possibilities, either we have 1 inline or multiple streams.
* Since we cannot tell at this point, we assume that we will have multiple streams and
* plan accordingly. we possibly will come to this code block multiple times. We create
* the MuxStream only the first time and use it for subsequent calls of this block.
*/
ComponentContextPair<Stream, StreamContext> pair = newStreams.get(sourceIdentifier);
if (pair == null) {
/**
* Let's multiplex the output placed on this stream.
* This container itself contains more than one parties interested.
*/
StreamContext context = new StreamContext(nodi.declaredStreamId);
context.setSourceId(sourceIdentifier);
context.setFinishedWindowId(finishedWindowId);
Stream stream = new MuxStream();
newStreams.put(sourceIdentifier, pair = new ComponentContextPair<Stream, StreamContext>(stream, context));
node.connectOutputPort(nodi.portName, stream);
}
if (nodi.bufferServerHost != null) {
/*
* Although there is a node in this container interested in output placed on this stream, there
* seems to at least one more party interested but placed in a container other than this one.
*/
SimpleEntry<String, ComponentContextPair<Stream, StreamContext>> deployBufferServerPublisher =
deployBufferServerPublisher(sourceIdentifier, finishedWindowId, queueCapacity, nodi);
newStreams.put(deployBufferServerPublisher.getKey(), deployBufferServerPublisher.getValue());
String sinkIdentifier = pair.context.getSinkId();
if (sinkIdentifier == null) {
pair.context.setSinkId(deployBufferServerPublisher.getKey());
}
else {
pair.context.setSinkId(sinkIdentifier.concat(", ").concat(deployBufferServerPublisher.getKey()));
}
((Stream.MultiSinkCapableStream)pair.component).setSink(deployBufferServerPublisher.getKey(), deployBufferServerPublisher.getValue().component);
}
}
}
}
return newStreams;
}
/**
* If the port is connected, return the declared stream Id.
*
* @param operatorId id of the operator to which the port belongs.
* @param portname name of port to which the stream is connected.
* @return Stream Id if connected, null otherwise.
*/
public final String getDeclaredStreamId(int operatorId, String portname)
{
String identifier = String.valueOf(operatorId).concat(Component.CONCAT_SEPARATOR).concat(portname);
ComponentContextPair<Stream, StreamContext> spair = streams.get(identifier);
if (spair == null) {
return null;
}
return spair.context.getId();
}
private void deployInputStreams(List<OperatorDeployInfo> operatorList, HashMap<String, ComponentContextPair<Stream, StreamContext>> newStreams) throws UnknownHostException
{
/*
* collect any input operators along with their smallest window id,
* those are subsequently used to setup the window generator
*/
ArrayList<OperatorDeployInfo> inputNodes = new ArrayList<OperatorDeployInfo>();
long smallestCheckpointedWindowId = Long.MAX_VALUE;
//a simple map which maps the oio node to it's the node which owns the thread.
Map<Integer, Integer> oioNodes = new ConcurrentHashMap<Integer, Integer>();
/*
* Hook up all the downstream ports. There are 2 places where we deal with more than 1
* downstream ports. The first one follows immediately for WindowGenerator. The second
* case is when source for the input port of some node in this container is in another
* container. So we need to create the stream. We need to track this stream along with
* other streams,and many such streams may exist, we hash them against buffer server
* info as we did for outputs but throw in the sinkid in the mix as well.
*/
for (OperatorDeployInfo ndi : operatorList) {
if (ndi.inputs == null || ndi.inputs.isEmpty()) {
/*
* This has to be InputNode, so let's hook the WindowGenerator to it.
* A node which does not take any input cannot exist in the DAG since it would be completely
* unaware of the windows. So for that reason, AbstractInputNode allows Component.INPUT port.
*/
inputNodes.add(ndi);
/*
* When we activate the window Generator, we plan to activate it only from required windowId.
*/
ndi.checkpointWindowId = getFinishedWindowId(ndi);
if (ndi.checkpointWindowId < smallestCheckpointedWindowId) {
smallestCheckpointedWindowId = ndi.checkpointWindowId;
}
}
else {
Node<?> node = nodes.get(ndi.id);
for (OperatorDeployInfo.InputDeployInfo nidi : ndi.inputs) {
String sourceIdentifier = Integer.toString(nidi.sourceNodeId).concat(Component.CONCAT_SEPARATOR).concat(nidi.sourcePortName);
String sinkIdentifier = Integer.toString(ndi.id).concat(Component.CONCAT_SEPARATOR).concat(nidi.portName);
int queueCapacity = nidi.contextAttributes == null ? PORT_QUEUE_CAPACITY : nidi.getValue(PortContext.QUEUE_CAPACITY);
long finishedWindowId = getFinishedWindowId(ndi);
ComponentContextPair<Stream, StreamContext> pair = streams.get(sourceIdentifier);
if (pair == null) {
pair = newStreams.get(sourceIdentifier);
}
if (pair == null) {
/*
* We connect to the buffer server for the input on this port.
* We have already placed all the output streams for all the operators in this container.
* Yet, there is no stream which can source this port so it has to come from the buffer
* server, so let's make a connection to it.
*/
assert (nidi.locality != Locality.CONTAINER_LOCAL && nidi.locality != Locality.THREAD_LOCAL);
StreamContext context = new StreamContext(nidi.declaredStreamId);
context.setBufferServerAddress(InetSocketAddress.createUnresolved(nidi.bufferServerHost, nidi.bufferServerPort));
if (NetUtils.isLocalAddress(context.getBufferServerAddress().getAddress())) {
context.setBufferServerAddress(new InetSocketAddress(InetAddress.getByName(null), nidi.bufferServerPort));
}
context.put(StreamContext.CODEC, StramUtils.getSerdeInstance(nidi.serDeClassName));
context.put(StreamContext.EVENT_LOOP, eventloop);
context.setPartitions(nidi.partitionMask, nidi.partitionKeys);
context.setSourceId(sourceIdentifier);
context.setSinkId(sinkIdentifier);
context.setFinishedWindowId(finishedWindowId);
BufferServerSubscriber subscriber = fastPublisherSubscriber
? new FastSubscriber("tcp://".concat(nidi.bufferServerHost).concat(":").concat(String.valueOf(nidi.bufferServerPort)).concat("/").concat(sourceIdentifier), queueCapacity)
: new BufferServerSubscriber("tcp://".concat(nidi.bufferServerHost).concat(":").concat(String.valueOf(nidi.bufferServerPort)).concat("/").concat(sourceIdentifier), queueCapacity);
SweepableReservoir reservoir = subscriber.acquireReservoir(sinkIdentifier, queueCapacity);
if (finishedWindowId > 0) {
node.connectInputPort(nidi.portName, new WindowIdActivatedReservoir(sinkIdentifier, reservoir, finishedWindowId));
}
node.connectInputPort(nidi.portName, reservoir);
newStreams.put(sinkIdentifier, new ComponentContextPair<Stream, StreamContext>(subscriber, context));
logger.debug("put input stream {} against key {}", subscriber, sinkIdentifier);
}
else {
assert (nidi.locality == Locality.CONTAINER_LOCAL || nidi.locality == Locality.THREAD_LOCAL);
/* we are still dealing with the MuxStream originating at the output of the source port */
StreamContext inlineContext = new StreamContext(nidi.declaredStreamId);
inlineContext.setSourceId(sourceIdentifier);
inlineContext.setSinkId(sinkIdentifier);
Stream stream;
switch (nidi.locality) {
case CONTAINER_LOCAL:
int outputQueueCapacity = getOutputQueueCapacity(operatorList, nidi.sourceNodeId, nidi.sourcePortName);
if (outputQueueCapacity > queueCapacity) {
queueCapacity = outputQueueCapacity;
}
stream = new InlineStream(queueCapacity);
if (finishedWindowId > 0) {
node.connectInputPort(nidi.portName, new WindowIdActivatedReservoir(sinkIdentifier, (SweepableReservoir)stream, finishedWindowId));
}
break;
case THREAD_LOCAL:
stream = new OiOStream();
oioNodes.put(ndi.id, nidi.sourceNodeId);
break;
default:
throw new IllegalStateException("Locality can be either ContainerLocal or ThreadLocal");
}
node.connectInputPort(nidi.portName, (SweepableReservoir)stream);
newStreams.put(sinkIdentifier, new ComponentContextPair<Stream, StreamContext>(stream, inlineContext));
if (!(pair.component instanceof Stream.MultiSinkCapableStream)) {
String originalSinkId = pair.context.getSinkId();
/* we come here only if we are trying to augment the dag */
StreamContext muxContext = new StreamContext(nidi.declaredStreamId);
muxContext.setSourceId(sourceIdentifier);
muxContext.setFinishedWindowId(finishedWindowId);
muxContext.setSinkId(originalSinkId);
MuxStream muxStream = new MuxStream();
muxStream.setSink(originalSinkId, pair.component);
streams.put(originalSinkId, pair);
Node<?> sourceNode = nodes.get(nidi.sourceNodeId);
sourceNode.connectOutputPort(nidi.sourcePortName, muxStream);
newStreams.put(sourceIdentifier, pair = new ComponentContextPair<Stream, StreamContext>(muxStream, muxContext));
}
/* here everything should be multisink capable */
if (nidi.partitionKeys == null || nidi.partitionKeys.isEmpty()) {
((Stream.MultiSinkCapableStream)pair.component).setSink(sinkIdentifier, stream);
}
else {
/*
* generally speaking we do not have partitions on the inline streams so the control should not
* come here but if it comes, then we are ready to handle it using the partition aware streams.
*/
PartitionAwareSink<Object> pas = new PartitionAwareSink<Object>(StramUtils.getSerdeInstance(nidi.serDeClassName), nidi.partitionKeys, nidi.partitionMask, stream);
((Stream.MultiSinkCapableStream)pair.component).setSink(sinkIdentifier, pas);
}
String streamSinkId = pair.context.getSinkId();
if (streamSinkId == null) {
pair.context.setSinkId(sinkIdentifier);
}
else {
pair.context.setSinkId(streamSinkId.concat(", ").concat(sinkIdentifier));
}
}
}
}
}
setupOiOGroups(oioNodes);
if (!inputNodes.isEmpty()) {
WindowGenerator windowGenerator = setupWindowGenerator(smallestCheckpointedWindowId);
for (OperatorDeployInfo ndi : inputNodes) {
generators.put(ndi.id, windowGenerator);
Node<?> node = nodes.get(ndi.id);
SweepableReservoir reservoir = windowGenerator.acquireReservoir(String.valueOf(ndi.id), 1024);
if (ndi.checkpointWindowId > 0) {
node.connectInputPort(Node.INPUT, new WindowIdActivatedReservoir(Integer.toString(ndi.id), reservoir, ndi.checkpointWindowId));
}
node.connectInputPort(Node.INPUT, reservoir);
}
}
}
/**
* Populates oioGroups with owner OIO Node as key and list of corresponding OIO nodes which will run in its thread as value
* This method assumes that the DAG is valid as per OIO constraints
*/
private void setupOiOGroups(Map<Integer, Integer> oioNodes)
{
for (Integer child : oioNodes.keySet()) {
Integer oioParent = oioNodes.get(child);
Integer temp;
while ((temp = oioNodes.get(oioParent)) != null) {
oioParent = temp;
}
ArrayList<Integer> children = oioGroups.get(oioParent);
if (children == null) {
oioGroups.put(oioParent, children = new ArrayList<Integer>());
}
children.add(child);
}
}
/**
* Create the window generator for the given start window id.
* This is a hook for tests to control the window generation.
*
* @param finishedWindowId
* @return WindowGenerator
*/
protected WindowGenerator setupWindowGenerator(long finishedWindowId)
{
WindowGenerator windowGenerator = new WindowGenerator(new ScheduledThreadPoolExecutor(1, "WindowGenerator"), 1024);
/**
* let's make sure that we send the same window Ids with the same reset windows.
*/
windowGenerator.setResetWindow(firstWindowMillis);
long millisAtFirstWindow = (finishedWindowId >> 32) * 1000 + windowWidthMillis * (finishedWindowId & WindowGenerator.MAX_WINDOW_ID) + windowWidthMillis;
windowGenerator.setFirstWindow(millisAtFirstWindow > firstWindowMillis ? millisAtFirstWindow : firstWindowMillis);
windowGenerator.setWindowWidth(windowWidthMillis);
windowGenerator.setCheckpointCount(checkpointWindowCount);
return windowGenerator;
}
private void setupNode(OperatorDeployInfo ndi, Thread thread)
{
failedNodes.remove(ndi.id);
final Node<?> node = nodes.get(ndi.id);
OperatorContext operatorContext = new OperatorContext(new Integer(ndi.id), thread, ndi.contextAttributes, containerContext);
node.setup(operatorContext);
/* setup context for all the input ports */
LinkedHashMap<String, PortContextPair<InputPort<?>>> inputPorts = node.getPortMappingDescriptor().inputPorts;
LinkedHashMap<String, PortContextPair<InputPort<?>>> newInputPorts = new LinkedHashMap<String, PortContextPair<InputPort<?>>>(inputPorts.size());
for (OperatorDeployInfo.InputDeployInfo idi : ndi.inputs) {
InputPort<?> port = inputPorts.get(idi.portName).component;
PortContext context = new PortContext(idi.contextAttributes, operatorContext);
newInputPorts.put(idi.portName, new PortContextPair<InputPort<?>>(port, context));
port.setup(context);
}
inputPorts.putAll(newInputPorts);
/* setup context for all the output ports */
LinkedHashMap<String, PortContextPair<OutputPort<?>>> outputPorts = node.getPortMappingDescriptor().outputPorts;
LinkedHashMap<String, PortContextPair<OutputPort<?>>> newOutputPorts = new LinkedHashMap<String, PortContextPair<OutputPort<?>>>(outputPorts.size());
for (OperatorDeployInfo.OutputDeployInfo odi : ndi.outputs) {
OutputPort<?> port = outputPorts.get(odi.portName).component;
PortContext context = new PortContext(odi.contextAttributes, operatorContext);
newOutputPorts.put(odi.portName, new PortContextPair<OutputPort<?>>(port, context));
port.setup(context);
}
outputPorts.putAll(newOutputPorts);
activeNodes.put(ndi.id, operatorContext);
logger.info("activating {} in container {}", node, containerId);
processNodeRequests(false);
node.activate(operatorContext);
eventBus.publish(new NodeActivationEvent(node));
}
private void teardownNode(OperatorDeployInfo ndi)
{
activeNodes.remove(ndi.id);
final Node<?> node = nodes.get(ndi.id);
if (node == null) {
logger.warn("node {}/{} took longer to exit, resulting in unclean undeploy!", ndi.id, ndi.name);
}
else {
node.deactivate();
eventBus.publish(new NodeDeactivationEvent(node));
node.teardown();
logger.info("deactivated {}", node.getId());
}
}
public synchronized void activate(final Map<Integer, OperatorDeployInfo> nodeMap, Map<String, ComponentContextPair<Stream, StreamContext>> newStreams)
{
for (ComponentContextPair<Stream, StreamContext> pair : newStreams.values()) {
if (!(pair.component instanceof BufferServerSubscriber)) {
activeStreams.put(pair.component, pair.context);
pair.component.activate(pair.context);
eventBus.publish(new StreamActivationEvent(pair));
}
}
final CountDownLatch signal = new CountDownLatch(nodeMap.size());
for (final OperatorDeployInfo ndi : nodeMap.values()) {
/*
* OiO nodes get activated with their primary nodes.
*/
if (ndi.type == OperatorType.OIO) {
continue;
}
assert (!activeNodes.containsKey(ndi.id));
final Node<?> node = nodes.get(ndi.id);
new Thread(Integer.toString(ndi.id).concat("/").concat(ndi.name).concat(":").concat(node.getOperator().getClass().getSimpleName()))
{
@Override
public void run()
{
HashSet<OperatorDeployInfo> setOperators = new HashSet<OperatorDeployInfo>();
OperatorDeployInfo currentdi = ndi;
try {
/* primary operator initialization */
setupNode(currentdi, this);
setOperators.add(currentdi);
/* lets go for OiO operator initialization */
List<Integer> oioNodeIdList = oioGroups.get(ndi.id);
if (oioNodeIdList != null) {
for (Integer oioNodeId : oioNodeIdList) {
currentdi = nodeMap.get(oioNodeId);
setupNode(currentdi, this);
setOperators.add(currentdi);
}
}
currentdi = null;
for (int i = setOperators.size(); i
signal.countDown();
}
node.run(); /* this is a blocking call */
}
catch (Throwable ex) {
if (currentdi == null) {
failedNodes.add(ndi.id);
logger.error("Operator set {} failed stopped running due to an exception.", setOperators, ex);
}
else {
failedNodes.add(currentdi.id);
logger.error("Abandoning deployment of operator {} due setup failure", currentdi, ex);
}
}
finally {
if (setOperators.contains(ndi)) {
try {
teardownNode(ndi);
}
catch (Throwable ex) {
logger.error("Shutdown of operator {} failed due to an exception", ndi, ex);
}
}
else {
signal.countDown();
}
List<Integer> oioNodeIdList = oioGroups.get(ndi.id);
if (oioNodeIdList != null) {
for (Integer oioNodeId : oioNodeIdList) {
OperatorDeployInfo oiodi = nodeMap.get(oioNodeId);
if (setOperators.contains(oiodi)) {
try {
teardownNode(oiodi);
}
catch (Throwable ex) {
logger.error("Shutdown of operator {} failed due to an exception", oiodi, ex);
}
}
else {
signal.countDown();
}
}
}
}
}
}.start();
}
/**
* we need to make sure that before any of the operators gets the first message, it's activate.
*/
try {
signal.await();
}
catch (InterruptedException ex) {
logger.debug("Activation of Operators interruped", ex);
}
for (ComponentContextPair<Stream, StreamContext> pair : newStreams.values()) {
if (pair.component instanceof BufferServerSubscriber) {
activeStreams.put(pair.component, pair.context);
pair.component.activate(pair.context);
eventBus.publish(new StreamActivationEvent(pair));
}
}
for (WindowGenerator wg : generators.values()) {
if (!activeGenerators.containsKey(wg)) {
activeGenerators.put(wg, generators);
wg.activate(null);
}
}
}
private void groupInputStreams(HashMap<String, ArrayList<String>> groupedInputStreams, OperatorDeployInfo ndi)
{
for (OperatorDeployInfo.InputDeployInfo nidi : ndi.inputs) {
String source = Integer.toString(nidi.sourceNodeId).concat(Component.CONCAT_SEPARATOR).concat(nidi.sourcePortName);
/*
* if we do not want to combine multiple streams with different partitions from the
* same upstream node, we could also use the partition to group the streams together.
* This logic comes with the danger that the performance of the group which shares
* the same stream is bounded on the higher side by the performance of the lowest
* performer upstream port. May be combining the streams is not such a good thing
* but let's see if we allow this as an option to the user, what they end up choosing
* the most.
*/
ArrayList<String> collection = groupedInputStreams.get(source);
if (collection == null) {
collection = new ArrayList<String>();
groupedInputStreams.put(source, collection);
}
collection.add(Integer.toString(ndi.id).concat(Component.CONCAT_SEPARATOR).concat(nidi.portName));
}
}
protected long getFinishedWindowId(OperatorDeployInfo ndi)
{
long finishedWindowId;
if (ndi.contextAttributes != null
&& ndi.contextAttributes.get(OperatorContext.PROCESSING_MODE) == ProcessingMode.AT_MOST_ONCE) {
/* this is really not a valid window Id, but it works since the valid window id will be numerically bigger */
long currentMillis = System.currentTimeMillis();
long diff = currentMillis - firstWindowMillis;
long remainder = diff % (windowWidthMillis * (WindowGenerator.MAX_WINDOW_ID + 1));
long baseSeconds = (currentMillis - remainder) / 1000;
long windowId = remainder / windowWidthMillis;
finishedWindowId = baseSeconds << 32 | windowId;
logger.debug("using at most once on {} at {}", ndi.name, Codec.getStringWindowId(finishedWindowId));
}
else {
finishedWindowId = ndi.checkpointWindowId;
logger.debug("using at least once on {} at {}", ndi.name, Codec.getStringWindowId(finishedWindowId));
}
return finishedWindowId;
}
private static final Logger logger = LoggerFactory.getLogger(StramChild.class);
public void operateListeners(StreamingContainerContext ctx, boolean setup)
{
if (setup) {
for (Component<ContainerContext> c : components) {
c.setup(ctx);
}
}
else {
for (Component<ContainerContext> c : components) {
c.teardown();
}
}
}
}
|
//FILE: MMStudioMainFrame.java
//PROJECT: Micro-Manager
//SUBSYSTEM: mmstudio
// Modifications by Arthur Edelstein, Nico Stuurman
// This file is distributed in the hope that it will be useful,
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.
//CVS: $Id$
package org.micromanager;
import ij.IJ;
import ij.ImageJ;
import ij.ImagePlus;
import ij.WindowManager;
import ij.gui.Line;
import ij.gui.Roi;
import ij.process.ImageProcessor;
import ij.process.ShortProcessor;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.Point2D;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.prefs.Preferences;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JToggleButton;
import javax.swing.SpringLayout;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.ToolTipManager;
import javax.swing.UIManager;
import javax.swing.event.AncestorEvent;
import mmcorej.CMMCore;
import mmcorej.DeviceType;
import mmcorej.MMCoreJ;
import mmcorej.MMEventCallback;
import mmcorej.Metadata;
import mmcorej.StrVector;
import org.json.JSONObject;
import org.micromanager.acquisition.AcquisitionManager;
import org.micromanager.api.ImageCache;
import org.micromanager.api.ImageCacheListener;
import org.micromanager.acquisition.MMImageCache;
import org.micromanager.api.AcquisitionEngine;
import org.micromanager.api.Autofocus;
import org.micromanager.api.DeviceControlGUI;
import org.micromanager.api.MMPlugin;
import org.micromanager.api.ScriptInterface;
import org.micromanager.api.MMListenerInterface;
import org.micromanager.conf.ConfiguratorDlg;
import org.micromanager.conf.MMConfigFileException;
import org.micromanager.conf.MicroscopeModel;
import org.micromanager.graph.ContrastPanel;
import org.micromanager.graph.GraphData;
import org.micromanager.graph.GraphFrame;
import org.micromanager.navigation.CenterAndDragListener;
import org.micromanager.navigation.PositionList;
import org.micromanager.navigation.XYZKeyListener;
import org.micromanager.navigation.ZWheelListener;
import org.micromanager.utils.AutofocusManager;
import org.micromanager.utils.ContrastSettings;
import org.micromanager.utils.GUIColors;
import org.micromanager.utils.GUIUtils;
import org.micromanager.utils.JavaUtils;
import org.micromanager.utils.MMException;
import org.micromanager.utils.MMImageWindow;
import org.micromanager.utils.MMScriptException;
import org.micromanager.utils.NumberUtils;
import org.micromanager.utils.TextUtils;
import org.micromanager.utils.TooltipTextMaker;
import org.micromanager.utils.WaitDialog;
import bsh.EvalError;
import bsh.Interpreter;
import com.swtdesigner.SwingResourceManager;
import ij.gui.ImageCanvas;
import ij.gui.ImageWindow;
import ij.process.FloatProcessor;
import java.awt.Cursor;
import java.awt.Graphics;
import java.awt.KeyboardFocusManager;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Collections;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.event.AncestorListener;
import mmcorej.TaggedImage;
import org.json.JSONException;
import org.micromanager.acquisition.AcquisitionVirtualStack;
import org.micromanager.acquisition.AcquisitionWrapperEngine;
import org.micromanager.acquisition.MMAcquisition;
import org.micromanager.acquisition.MetadataPanel;
import org.micromanager.acquisition.TaggedImageStorageDiskDefault;
import org.micromanager.acquisition.VirtualAcquisitionDisplay;
import org.micromanager.utils.ImageFocusListener;
import org.micromanager.api.Pipeline;
import org.micromanager.api.TaggedImageStorage;
import org.micromanager.utils.FileDialogs;
import org.micromanager.utils.FileDialogs.FileType;
import org.micromanager.utils.HotKeysDialog;
import org.micromanager.utils.ImageUtils;
import org.micromanager.utils.MDUtils;
import org.micromanager.utils.MMKeyDispatcher;
import org.micromanager.utils.ReportingUtils;
/*
* Main panel and application class for the MMStudio.
*/
public class MMStudioMainFrame extends JFrame implements DeviceControlGUI, ScriptInterface {
private static final String MICRO_MANAGER_TITLE = "Micro-Manager 1.4";
private static final String VERSION = "1.4.7 20110927";
private static final long serialVersionUID = 3556500289598574541L;
private static final String MAIN_FRAME_X = "x";
private static final String MAIN_FRAME_Y = "y";
private static final String MAIN_FRAME_WIDTH = "width";
private static final String MAIN_FRAME_HEIGHT = "height";
private static final String MAIN_FRAME_DIVIDER_POS = "divider_pos";
private static final String MAIN_EXPOSURE = "exposure";
private static final String SYSTEM_CONFIG_FILE = "sysconfig_file";
private static final String MAIN_STRETCH_CONTRAST = "stretch_contrast";
private static final String MAIN_REJECT_OUTLIERS = "reject_outliers";
private static final String MAIN_REJECT_FRACTION = "reject_fraction";
private static final String CONTRAST_SETTINGS_8_MIN = "contrast8_MIN";
private static final String CONTRAST_SETTINGS_8_MAX = "contrast8_MAX";
private static final String CONTRAST_SETTINGS_16_MIN = "contrast16_MIN";
private static final String CONTRAST_SETTINGS_16_MAX = "contrast16_MAX";
private static final String OPEN_ACQ_DIR = "openDataDir";
private static final String SCRIPT_CORE_OBJECT = "mmc";
private static final String SCRIPT_ACQENG_OBJECT = "acq";
private static final String SCRIPT_GUI_OBJECT = "gui";
private static final String AUTOFOCUS_DEVICE = "autofocus_device";
private static final String MOUSE_MOVES_STAGE = "mouse_moves_stage";
private static final int TOOLTIP_DISPLAY_DURATION_MILLISECONDS = 15000;
// cfg file saving
private static final String CFGFILE_ENTRY_BASE = "CFGFileEntry"; // + {0, 1, 2, 3, 4}
// GUI components
private JComboBox comboBinning_;
private JComboBox shutterComboBox_;
private JTextField textFieldExp_;
private JLabel labelImageDimensions_;
private JToggleButton toggleButtonLive_;
private JCheckBox autoShutterCheckBox_;
private boolean autoShutterOrg_;
private boolean shutterOrg_;
private MMOptions options_;
private boolean runsAsPlugin_;
private JCheckBoxMenuItem centerAndDragMenuItem_;
private JButton buttonSnap_;
private JButton buttonAutofocus_;
private JButton buttonAutofocusTools_;
private JToggleButton toggleButtonShutter_;
private GUIColors guiColors_;
private GraphFrame profileWin_;
private PropertyEditor propertyBrowser_;
private CalibrationListDlg calibrationListDlg_;
private AcqControlDlg acqControlWin_;
private ReportProblemDialog reportProblemDialog_;
private JMenu pluginMenu_;
private ArrayList<PluginItem> plugins_;
private List<MMListenerInterface> MMListeners_
= (List<MMListenerInterface>)
Collections.synchronizedList(new ArrayList<MMListenerInterface>());
private List<Component> MMFrames_
= (List<Component>)
Collections.synchronizedList(new ArrayList<Component>());
private AutofocusManager afMgr_;
private final static String DEFAULT_CONFIG_FILE_NAME = "MMConfig_demo.cfg";
private ArrayList<String> MRUConfigFiles_;
private static final int maxMRUCfgs_ = 5;
private String sysConfigFile_;
private String startupScriptFile_;
private String sysStateFile_ = "MMSystemState.cfg";
private ConfigGroupPad configPad_;
private ContrastPanel contrastPanel_;
// Timer interval - image display interval
private double liveModeInterval_ = 40;
private Timer liveModeTimer_;
private LiveModeTimerTask liveModeTimerTask_;
private GraphData lineProfileData_;
private Object img_;
// labels for standard devices
private String cameraLabel_;
private String zStageLabel_;
private String shutterLabel_;
private String xyStageLabel_;
// applications settings
private Preferences mainPrefs_;
private Preferences systemPrefs_;
// MMcore
private CMMCore core_;
private AcquisitionEngine engine_;
private PositionList posList_;
private PositionListDlg posListDlg_;
private String openAcqDirectory_ = "";
private boolean running_;
private boolean liveRunning_ = false;
private boolean configChanged_ = false;
private StrVector shutters_ = null;
private JButton saveConfigButton_;
private ScriptPanel scriptPanel_;
private org.micromanager.utils.HotKeys hotKeys_;
private CenterAndDragListener centerAndDragListener_;
private ZWheelListener zWheelListener_;
private XYZKeyListener xyzKeyListener_;
private AcquisitionManager acqMgr_;
private static MMImageWindow imageWin_;
private final String multiCameraAcq_ = "Multi-Camera Snap";
private Color[] multiCameraColors_ = {Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW, Color.CYAN};
private boolean multiChannelCamera_ = false;
private long multiChannelCameraNrCh_ = 0;
private int snapCount_ = -1;
private boolean liveModeSuspended_;
public Font defaultScriptFont_ = null;
public static FileType MM_CONFIG_FILE
= new FileType("MM_CONFIG_FILE",
"Micro-Manager Config File",
"./MyScope.cfg",
true, "cfg");
// Our instance
private static MMStudioMainFrame gui_;
// Callback
private CoreEventCallback cb_;
// Lock invoked while shutting down
private final Object shutdownLock_ = new Object();
private JMenuBar menuBar_;
private ConfigPadButtonPanel configPadButtonPanel_;
private final JMenu switchConfigurationMenu_;
private final MetadataPanel metadataPanel_;
public static FileType MM_DATA_SET
= new FileType("MM_DATA_SET",
"Micro-Manager Image Location",
System.getProperty("user.home") + "/Untitled",
false, (String[]) null);
private Thread pipelineClassLoadingThread_ = null;
private Class pipelineClass_ = null;
private Pipeline acquirePipeline_ = null;
private final JSplitPane splitPane_;
public ImageWindow getImageWin() {
return imageWin_;
}
public static MMImageWindow getLiveWin() {
return imageWin_;
}
private void doSnapColor() {
try {
getPipeline().doSnap();
} catch (Exception ex) {
ReportingUtils.logError(ex);
}
}
private void doSnapFloat() {
try {
// just a test harness
core_.snapImage();
byte[] byteImage = (byte[]) core_.getImage();
int ii = (int)core_.getImageWidth();
int jj = (int)core_.getImageHeight();
int npoints = ii*jj;
float[] floatImage = new float[npoints];
ImagePlus implus = new ImagePlus();
int iiterator = 0;
int oiterator = 0;
for (; oiterator < npoints; ++oiterator) {
floatImage[oiterator] = Float.intBitsToFloat(((int) byteImage[iiterator+3 ] << 24) + ((int) byteImage[iiterator + 2] << 16) + ((int) byteImage[iiterator + 1] << 8) + (int) byteImage[iiterator]);
iiterator += 4;
}
FloatProcessor fp = new FloatProcessor(ii, jj, floatImage, null);
implus.setProcessor(fp);
ImageWindow iwindow = new ImageWindow(implus);
WindowManager.setCurrentWindow(iwindow);
} catch (Exception ex) {
ReportingUtils.showError(ex);
}
}
private void doSnapMonochrome() {
try {
Cursor waitCursor = new Cursor(Cursor.WAIT_CURSOR);
setCursor(waitCursor);
if (!isImageWindowOpen()) {
imageWin_ = createImageWindow();
}
if (imageWin_ == null) {
return;
}
imageWin_.toFront();
setIJCal(imageWin_);
// this is needed to clear the subtite, should be folded into
// drawInfo
imageWin_.getGraphics().clearRect(0, 0, imageWin_.getWidth(), 40);
imageWin_.drawInfo(imageWin_.getGraphics());
imageWin_.setSubTitle("Snap");
String expStr = textFieldExp_.getText();
if (expStr.length() > 0) {
core_.setExposure(NumberUtils.displayStringToDouble(expStr));
updateImage();
} else {
handleError("Exposure field is empty!");
}
} catch (Exception e) {
ReportingUtils.showError(e);
}
setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}
private void checkMultiChannelWindow()
{
int w = (int) core_.getImageWidth();
int h = (int) core_.getImageHeight();
int d = (int) core_.getBytesPerPixel();
long c = core_.getNumberOfCameraChannels();
if (c > 1)
{
try {
if (acquisitionExists(multiCameraAcq_)) {
if (c != (getAcquisition(multiCameraAcq_)).getChannels()) {
closeAcquisitionImage5D(multiCameraAcq_);
closeAcquisition(multiCameraAcq_);
}
if ( (getAcquisitionImageWidth(multiCameraAcq_) != w) ||
(getAcquisitionImageHeight(multiCameraAcq_) != h) ||
(getAcquisitionImageByteDepth(multiCameraAcq_) != d) ) {
closeAcquisitionImage5D(multiCameraAcq_);
closeAcquisition(multiCameraAcq_);
}
}
if (!acquisitionExists(multiCameraAcq_)) {
openAcquisition(multiCameraAcq_, "", 1, (int) c, 1, true);
for (int i = 0; i < c; i++) {
if (i < multiCameraColors_.length) {
setChannelColor(multiCameraAcq_, i, multiCameraColors_[i]);
}
setChannelName(multiCameraAcq_, i, core_.getCameraChannelName(i));
}
initializeAcquisition(multiCameraAcq_, w, h, d);
getAcquisition(multiCameraAcq_).promptToSave(false);
}
} catch (Exception ex) {
ReportingUtils.showError(ex);
}
}
}
/**
* Snaps an image for a multi-Channel camera
* This version does not (yet) support attachment of mouse listeners
* for stage movement.
*/
private void doSnapMultiChannel()
{
checkMultiChannelWindow();
try {
setCursor(new Cursor(Cursor.WAIT_CURSOR));
core_.snapImage();
getAcquisition(multiCameraAcq_).toFront();
long c = core_.getNumberOfCameraChannels();
for (int i = 0; i < c; i++) {
TaggedImage ti = ImageUtils.makeTaggedImage(core_.getImage(i),
i,
0,
0,
0,
getAcquisitionImageWidth(multiCameraAcq_),
getAcquisitionImageHeight(multiCameraAcq_),
getAcquisitionImageByteDepth(multiCameraAcq_) );
boolean update = false;
if (i == c -1)
update = true;
addImage(multiCameraAcq_,ti, update);
}
} catch (Exception ex) {
ReportingUtils.showError(ex);
}
setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}
private void initializeHelpMenu() {
// add help menu item
final JMenu helpMenu = new JMenu();
helpMenu.setText("Help");
menuBar_.add(helpMenu);
final JMenuItem usersGuideMenuItem = new JMenuItem();
usersGuideMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
ij.plugin.BrowserLauncher.openURL("http://valelab.ucsf.edu/~MM/MMwiki/index.php/Micro-Manager_User%27s_Guide");
} catch (IOException e1) {
ReportingUtils.showError(e1);
}
}
});
usersGuideMenuItem.setText("User's Guide...");
helpMenu.add(usersGuideMenuItem);
final JMenuItem configGuideMenuItem = new JMenuItem();
configGuideMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
ij.plugin.BrowserLauncher.openURL("http://valelab.ucsf.edu/~MM/MMwiki/index.php/Micro-Manager_Configuration_Guide");
} catch (IOException e1) {
ReportingUtils.showError(e1);
}
}
});
configGuideMenuItem.setText("Configuration Guide...");
helpMenu.add(configGuideMenuItem);
if (!systemPrefs_.getBoolean(RegistrationDlg.REGISTRATION, false)) {
final JMenuItem registerMenuItem = new JMenuItem();
registerMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
RegistrationDlg regDlg = new RegistrationDlg(systemPrefs_);
regDlg.setVisible(true);
} catch (Exception e1) {
ReportingUtils.showError(e1);
}
}
});
registerMenuItem.setText("Register your copy of Micro-Manager...");
helpMenu.add(registerMenuItem);
}
final MMStudioMainFrame thisFrame = this;
final JMenuItem reportProblemMenuItem = new JMenuItem();
reportProblemMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (null == reportProblemDialog_) {
reportProblemDialog_ = new ReportProblemDialog(core_, thisFrame, sysConfigFile_, options_);
thisFrame.addMMBackgroundListener(reportProblemDialog_);
reportProblemDialog_.setBackground(guiColors_.background.get(options_.displayBackground_));
}
reportProblemDialog_.setVisible(true);
}
});
reportProblemMenuItem.setText("Report Problem");
helpMenu.add(reportProblemMenuItem);
final JMenuItem aboutMenuItem = new JMenuItem();
aboutMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
MMAboutDlg dlg = new MMAboutDlg();
String versionInfo = "MM Studio version: " + VERSION;
versionInfo += "\n" + core_.getVersionInfo();
versionInfo += "\n" + core_.getAPIVersionInfo();
versionInfo += "\nUser: " + core_.getUserId();
versionInfo += "\nHost: " + core_.getHostName();
dlg.setVersionInfo(versionInfo);
dlg.setVisible(true);
}
});
aboutMenuItem.setText("About Micromanager...");
helpMenu.add(aboutMenuItem);
menuBar_.validate();
}
private void updateSwitchConfigurationMenu() {
switchConfigurationMenu_.removeAll();
for (final String configFile : MRUConfigFiles_) {
if (! configFile.equals(sysConfigFile_)) {
JMenuItem configMenuItem = new JMenuItem();
configMenuItem.setText(configFile);
configMenuItem.addActionListener(new ActionListener() {
String theConfigFile = configFile;
public void actionPerformed(ActionEvent e) {
sysConfigFile_ = theConfigFile;
loadSystemConfiguration();
mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_);
}
});
switchConfigurationMenu_.add(configMenuItem);
}
}
}
/**
* Allows MMListeners to register themselves
*/
public void addMMListener(MMListenerInterface newL) {
if (MMListeners_.contains(newL))
return;
MMListeners_.add(newL);
}
/**
* Allows MMListeners to remove themselves
*/
public void removeMMListener(MMListenerInterface oldL) {
if (!MMListeners_.contains(oldL))
return;
MMListeners_.remove(oldL);
}
/**
* Lets JComponents register themselves so that their background can be
* manipulated
*/
public void addMMBackgroundListener(Component comp) {
if (MMFrames_.contains(comp))
return;
MMFrames_.add(comp);
}
/**
* Lets JComponents remove themselves from the list whose background gets
* changes
*/
public void removeMMBackgroundListener(Component comp) {
if (!MMFrames_.contains(comp))
return;
MMFrames_.remove(comp);
}
public void updateContrast(ImagePlus iplus) {
contrastPanel_.updateContrast(iplus);
}
/**
* Part of ScriptInterface
* Manipulate acquisition so that it looks like a burst
*/
public void runBurstAcquisition() throws MMScriptException {
double interval = engine_.getFrameIntervalMs();
int nr = engine_.getNumFrames();
boolean doZStack = engine_.isZSliceSettingEnabled();
boolean doChannels = engine_.isChannelsSettingEnabled();
engine_.enableZSliceSetting(false);
engine_.setFrames(nr, 0);
engine_.enableChannelsSetting(false);
try {
engine_.acquire();
} catch (MMException e) {
throw new MMScriptException(e);
}
engine_.setFrames(nr, interval);
engine_.enableZSliceSetting(doZStack);
engine_.enableChannelsSetting(doChannels);
}
public void runBurstAcquisition(int nr) throws MMScriptException {
int originalNr = engine_.getNumFrames();
double interval = engine_.getFrameIntervalMs();
engine_.setFrames(nr, 0);
this.runBurstAcquisition();
engine_.setFrames(originalNr, interval);
}
public void runBurstAcquisition(int nr, String name, String root) throws MMScriptException {
//String originalName = engine_.getDirName();
String originalRoot = engine_.getRootName();
engine_.setDirName(name);
engine_.setRootName(root);
this.runBurstAcquisition(nr);
engine_.setRootName(originalRoot);
//engine_.setDirName(originalDirName);
}
/**
* @deprecated
* @throws MMScriptException
*/
public void startBurstAcquisition() throws MMScriptException {
runAcquisition();
}
public boolean isBurstAcquisitionRunning() throws MMScriptException {
if (engine_ == null)
return false;
return engine_.isAcquisitionRunning();
}
private void startLoadingPipelineClass() {
Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
pipelineClassLoadingThread_ = new Thread("Pipeline Class loading thread") {
@Override
public void run() {
try {
pipelineClass_ = Class.forName("org.micromanager.AcqEngine");
} catch (Exception ex) {
ReportingUtils.logError(ex);
pipelineClass_ = null;
}
}
};
pipelineClassLoadingThread_.start();
}
public void addImageStorageListener(ImageCacheListener listener) {
throw new UnsupportedOperationException("Not supported yet.");
}
public ImageCache getAcquisitionImageCache(String acquisitionName) {
throw new UnsupportedOperationException("Not supported yet.");
}
/**
* Callback to update GUI when a change happens in the MMCore.
*/
public class CoreEventCallback extends MMEventCallback {
public CoreEventCallback() {
super();
}
@Override
public void onPropertiesChanged() {
// TODO: remove test once acquisition engine is fully multithreaded
if (engine_ != null && engine_.isAcquisitionRunning()) {
core_.logMessage("Notification from MMCore ignored because acquistion is running!");
} else {
updateGUI(true);
// update all registered listeners
for (MMListenerInterface mmIntf:MMListeners_) {
mmIntf.propertiesChangedAlert();
}
core_.logMessage("Notification from MMCore!");
}
}
@Override
public void onPropertyChanged(String deviceName, String propName, String propValue) {
core_.logMessage("Notification for Device: " + deviceName + " Property: " +
propName + " changed to value: " + propValue);
// update all registered listeners
for (MMListenerInterface mmIntf:MMListeners_) {
mmIntf.propertyChangedAlert(deviceName, propName, propValue);
}
}
@Override
public void onConfigGroupChanged(String groupName, String newConfig) {
try {
configPad_.refreshGroup(groupName, newConfig);
} catch (Exception e) {
}
}
@Override
public void onPixelSizeChanged(double newPixelSizeUm) {
updatePixSizeUm (newPixelSizeUm);
}
@Override
public void onStagePositionChanged(String deviceName, double pos) {
if (deviceName.equals(zStageLabel_))
updateZPos(pos);
}
@Override
public void onStagePositionChangedRelative(String deviceName, double pos) {
if (deviceName.equals(zStageLabel_))
updateZPosRelative(pos);
}
@Override
public void onXYStagePositionChanged(String deviceName, double xPos, double yPos) {
if (deviceName.equals(xyStageLabel_))
updateXYPos(xPos, yPos);
}
@Override
public void onXYStagePositionChangedRelative(String deviceName, double xPos, double yPos) {
if (deviceName.equals(xyStageLabel_))
updateXYPosRelative(xPos, yPos);
}
}
private class PluginItem {
public Class<?> pluginClass = null;
public String menuItem = "undefined";
public MMPlugin plugin = null;
public String className = "";
public void instantiate() {
try {
if (plugin == null) {
plugin = (MMPlugin) pluginClass.newInstance();
}
} catch (InstantiationException e) {
ReportingUtils.logError(e);
} catch (IllegalAccessException e) {
ReportingUtils.logError(e);
}
plugin.setApp(MMStudioMainFrame.this);
}
}
/*
* Simple class used to cache static info
*/
private class StaticInfo {
public long width_;
public long height_;
public long bytesPerPixel_;
public long imageBitDepth_;
public double pixSizeUm_;
public double zPos_;
public double x_;
public double y_;
}
private StaticInfo staticInfo_ = new StaticInfo();
/**
* Main procedure for stand alone operation.
*/
public static void main(String args[]) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
MMStudioMainFrame frame = new MMStudioMainFrame(false);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
} catch (Throwable e) {
ReportingUtils.showError(e, "A java error has caused Micro-Manager to exit.");
System.exit(1);
}
}
public MMStudioMainFrame(boolean pluginStatus) {
super();
startLoadingPipelineClass();
options_ = new MMOptions();
try {
options_.loadSettings();
} catch (NullPointerException ex) {
ReportingUtils.logError(ex);
}
guiColors_ = new GUIColors();
plugins_ = new ArrayList<PluginItem>();
gui_ = this;
runsAsPlugin_ = pluginStatus;
setIconImage(SwingResourceManager.getImage(MMStudioMainFrame.class,
"icons/microscope.gif"));
running_ = true;
acqMgr_ = new AcquisitionManager();
sysConfigFile_ = System.getProperty("user.dir") + "/"
+ DEFAULT_CONFIG_FILE_NAME;
if (options_.startupScript_.length() > 0) {
startupScriptFile_ = System.getProperty("user.dir") + "/"
+ options_.startupScript_;
} else {
startupScriptFile_ = "";
}
ReportingUtils.SetContainingFrame(gui_);
// set the location for app preferences
try {
mainPrefs_ = Preferences.userNodeForPackage(this.getClass());
} catch (Exception e) {
ReportingUtils.logError(e);
}
systemPrefs_ = mainPrefs_;
// check system preferences
try {
Preferences p = Preferences.systemNodeForPackage(this.getClass());
if (null != p) {
// if we can not write to the systemPrefs, use AppPrefs instead
if (JavaUtils.backingStoreAvailable(p)) {
systemPrefs_ = p;
}
}
} catch (Exception e) {
ReportingUtils.logError(e);
}
// show registration dialog if not already registered
// first check user preferences (for legacy compatibility reasons)
boolean userReg = mainPrefs_.getBoolean(RegistrationDlg.REGISTRATION,
false) || mainPrefs_.getBoolean(RegistrationDlg.REGISTRATION_NEVER, false);
if (!userReg) {
boolean systemReg = systemPrefs_.getBoolean(
RegistrationDlg.REGISTRATION, false) || systemPrefs_.getBoolean(RegistrationDlg.REGISTRATION_NEVER, false);
if (!systemReg) {
// prompt for registration info
RegistrationDlg dlg = new RegistrationDlg(systemPrefs_);
dlg.setVisible(true);
}
}
liveModeTimer_ = new Timer("liveModeTimer");
// load application preferences
// NOTE: only window size and position preferences are loaded,
// not the settings for the camera and live imaging -
// attempting to set those automatically on startup may cause problems
// with the hardware
int x = mainPrefs_.getInt(MAIN_FRAME_X, 100);
int y = mainPrefs_.getInt(MAIN_FRAME_Y, 100);
int width = mainPrefs_.getInt(MAIN_FRAME_WIDTH, 580);
int height = mainPrefs_.getInt(MAIN_FRAME_HEIGHT, 482);
boolean stretch = mainPrefs_.getBoolean(MAIN_STRETCH_CONTRAST, true);
boolean reject = mainPrefs_.getBoolean(MAIN_REJECT_OUTLIERS, false);
double rejectFract = mainPrefs_.getDouble(MAIN_REJECT_FRACTION, 0.027);
int dividerPos = mainPrefs_.getInt(MAIN_FRAME_DIVIDER_POS, 178);
openAcqDirectory_ = mainPrefs_.get(OPEN_ACQ_DIR, "");
ToolTipManager ttManager = ToolTipManager.sharedInstance();
ttManager.setDismissDelay(TOOLTIP_DISPLAY_DURATION_MILLISECONDS);
setBounds(x, y, width, height);
setExitStrategy(options_.closeOnExit_);
setTitle(MICRO_MANAGER_TITLE);
setBackground(guiColors_.background.get((options_.displayBackground_)));
SpringLayout topLayout = new SpringLayout();
this.setMinimumSize(new Dimension(580,480));
JPanel topPanel = new JPanel();
topPanel.setLayout(topLayout);
topPanel.setMinimumSize(new Dimension(580, 175));
class ListeningJPanel extends JPanel implements AncestorListener {
public void ancestorMoved(AncestorEvent event) {
//System.out.println("moved!");
}
public void ancestorRemoved(AncestorEvent event) {}
public void ancestorAdded(AncestorEvent event) {}
}
ListeningJPanel bottomPanel = new ListeningJPanel();
bottomPanel.setLayout(topLayout);
splitPane_ = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true,
topPanel, bottomPanel);
splitPane_.setBorder(BorderFactory.createEmptyBorder());
splitPane_.setDividerLocation(dividerPos);
splitPane_.setResizeWeight(0.0);
splitPane_.addAncestorListener(bottomPanel);
getContentPane().add(splitPane_);
// Snap button
buttonSnap_ = new JButton();
buttonSnap_.setIconTextGap(6);
buttonSnap_.setText("Snap");
buttonSnap_.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class, "/org/micromanager/icons/camera.png"));
buttonSnap_.setFont(new Font("Arial", Font.PLAIN, 10));
buttonSnap_.setToolTipText("Snap single image");
buttonSnap_.setMaximumSize(new Dimension(0, 0));
buttonSnap_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
doSnap();
}
});
topPanel.add(buttonSnap_);
topLayout.putConstraint(SpringLayout.SOUTH, buttonSnap_, 25,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, buttonSnap_, 4,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, buttonSnap_, 95,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, buttonSnap_, 7,
SpringLayout.WEST, topPanel);
// Initialize
// Exposure field
final JLabel label_1 = new JLabel();
label_1.setFont(new Font("Arial", Font.PLAIN, 10));
label_1.setText("Exposure [ms]");
topPanel.add(label_1);
topLayout.putConstraint(SpringLayout.EAST, label_1, 198,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, label_1, 111,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.SOUTH, label_1, 39,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, label_1, 23,
SpringLayout.NORTH, topPanel);
textFieldExp_ = new JTextField();
textFieldExp_.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent fe) {
synchronized(shutdownLock_) {
if (core_ != null)
setExposure();
}
}
});
textFieldExp_.setFont(new Font("Arial", Font.PLAIN, 10));
textFieldExp_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setExposure();
}
});
topPanel.add(textFieldExp_);
topLayout.putConstraint(SpringLayout.SOUTH, textFieldExp_, 40,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, textFieldExp_, 21,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, textFieldExp_, 276,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, textFieldExp_, 203,
SpringLayout.WEST, topPanel);
// Live button
toggleButtonLive_ = new JToggleButton();
toggleButtonLive_.setMargin(new Insets(2, 2, 2, 2));
toggleButtonLive_.setIconTextGap(1);
toggleButtonLive_.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class,
"/org/micromanager/icons/camera_go.png"));
toggleButtonLive_.setIconTextGap(6);
toggleButtonLive_.setToolTipText("Continuous live view");
toggleButtonLive_.setFont(new Font("Arial", Font.PLAIN, 10));
toggleButtonLive_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!isLiveModeOn()) {
// Display interval for Live Mode changes as well
setLiveModeInterval();
}
enableLiveMode(!isLiveModeOn());
}
});
toggleButtonLive_.setText("Live");
topPanel.add(toggleButtonLive_);
topLayout.putConstraint(SpringLayout.SOUTH, toggleButtonLive_, 47,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, toggleButtonLive_, 26,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, toggleButtonLive_, 95,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, toggleButtonLive_, 7,
SpringLayout.WEST, topPanel);
// Acquire button
JButton acquireButton = new JButton();
acquireButton.setMargin(new Insets(2, 2, 2, 2));
acquireButton.setIconTextGap(1);
acquireButton.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class,
"/org/micromanager/icons/snapAppend.png"));
acquireButton.setIconTextGap(6);
acquireButton.setToolTipText("Acquire single frame and add to an album");
acquireButton.setFont(new Font("Arial", Font.PLAIN, 10));
acquireButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
snapAndAddToImage5D();
}
});
acquireButton.setText("Acquire");
topPanel.add(acquireButton);
topLayout.putConstraint(SpringLayout.SOUTH, acquireButton, 69,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, acquireButton, 48,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, acquireButton, 95,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, acquireButton, 7,
SpringLayout.WEST, topPanel);
// Shutter button
toggleButtonShutter_ = new JToggleButton();
toggleButtonShutter_.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
toggleShutter();
}
});
toggleButtonShutter_.setToolTipText("Open/close the shutter");
toggleButtonShutter_.setIconTextGap(6);
toggleButtonShutter_.setFont(new Font("Arial", Font.BOLD, 10));
toggleButtonShutter_.setText("Open");
topPanel.add(toggleButtonShutter_);
topLayout.putConstraint(SpringLayout.EAST, toggleButtonShutter_,
275, SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, toggleButtonShutter_,
203, SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.SOUTH, toggleButtonShutter_,
138 - 21, SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, toggleButtonShutter_,
117 - 21, SpringLayout.NORTH, topPanel);
// Active shutter label
final JLabel activeShutterLabel = new JLabel();
activeShutterLabel.setFont(new Font("Arial", Font.PLAIN, 10));
activeShutterLabel.setText("Shutter");
topPanel.add(activeShutterLabel);
topLayout.putConstraint(SpringLayout.SOUTH, activeShutterLabel,
108 - 22, SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, activeShutterLabel,
95 - 22, SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, activeShutterLabel,
160 - 2, SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, activeShutterLabel,
113 - 2, SpringLayout.WEST, topPanel);
// Active shutter Combo Box
shutterComboBox_ = new JComboBox();
shutterComboBox_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
if (shutterComboBox_.getSelectedItem() != null) {
core_.setShutterDevice((String) shutterComboBox_.getSelectedItem());
}
} catch (Exception e) {
ReportingUtils.showError(e);
}
return;
}
});
topPanel.add(shutterComboBox_);
topLayout.putConstraint(SpringLayout.SOUTH, shutterComboBox_,
114 - 22, SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, shutterComboBox_,
92 - 22, SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, shutterComboBox_, 275,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, shutterComboBox_, 170,
SpringLayout.WEST, topPanel);
menuBar_ = new JMenuBar();
setJMenuBar(menuBar_);
final JMenu fileMenu = new JMenu();
fileMenu.setText("File");
menuBar_.add(fileMenu);
final JMenuItem openMenuItem = new JMenuItem();
openMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
new Thread() {
@Override
public void run() {
openAcquisitionData();
}
}.start();
}
});
openMenuItem.setText("Open Acquisition Data...");
fileMenu.add(openMenuItem);
fileMenu.addSeparator();
final JMenuItem loadState = new JMenuItem();
loadState.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
loadSystemState();
}
});
loadState.setText("Load System State...");
fileMenu.add(loadState);
final JMenuItem saveStateAs = new JMenuItem();
fileMenu.add(saveStateAs);
saveStateAs.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
saveSystemState();
}
});
saveStateAs.setText("Save System State As...");
fileMenu.addSeparator();
final JMenuItem exitMenuItem = new JMenuItem();
exitMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
closeSequence();
}
});
fileMenu.add(exitMenuItem);
exitMenuItem.setText("Exit");
/*
final JMenu image5dMenu = new JMenu();
image5dMenu.setText("Image5D");
menuBar_.add(image5dMenu);
final JMenuItem closeAllMenuItem = new JMenuItem();
closeAllMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
WindowManager.closeAllWindows();
}
});
closeAllMenuItem.setText("Close All");
image5dMenu.add(closeAllMenuItem);
final JMenuItem duplicateMenuItem = new JMenuItem();
duplicateMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Duplicate_Image5D duplicate = new Duplicate_Image5D();
duplicate.run("");
}
});
duplicateMenuItem.setText("Duplicate");
image5dMenu.add(duplicateMenuItem);
final JMenuItem cropMenuItem = new JMenuItem();
cropMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Crop_Image5D crop = new Crop_Image5D();
crop.run("");
}
});
cropMenuItem.setText("Crop");
image5dMenu.add(cropMenuItem);
final JMenuItem makeMontageMenuItem = new JMenuItem();
makeMontageMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Make_Montage makeMontage = new Make_Montage();
makeMontage.run("");
}
});
makeMontageMenuItem.setText("Make Montage");
image5dMenu.add(makeMontageMenuItem);
final JMenuItem zProjectMenuItem = new JMenuItem();
zProjectMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Z_Project projection = new Z_Project();
projection.run("");
}
});
zProjectMenuItem.setText("Z Project");
image5dMenu.add(zProjectMenuItem);
final JMenuItem convertToRgbMenuItem = new JMenuItem();
convertToRgbMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Image5D_Stack_to_RGB stackToRGB = new Image5D_Stack_to_RGB();
stackToRGB.run("");
}
});
convertToRgbMenuItem.setText("Copy to RGB Stack(z)");
image5dMenu.add(convertToRgbMenuItem);
final JMenuItem convertToRgbtMenuItem = new JMenuItem();
convertToRgbtMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Image5D_Stack_to_RGB_t stackToRGB_t = new Image5D_Stack_to_RGB_t();
stackToRGB_t.run("");
}
});
convertToRgbtMenuItem.setText("Copy to RGB Stack(t)");
image5dMenu.add(convertToRgbtMenuItem);
final JMenuItem convertToStackMenuItem = new JMenuItem();
convertToStackMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Image5D_to_Stack image5DToStack = new Image5D_to_Stack();
image5DToStack.run("");
}
});
convertToStackMenuItem.setText("Copy to Stack");
image5dMenu.add(convertToStackMenuItem);
final JMenuItem convertToStacksMenuItem = new JMenuItem();
convertToStacksMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Image5D_Channels_to_Stacks image5DToStacks = new Image5D_Channels_to_Stacks();
image5DToStacks.run("");
}
});
convertToStacksMenuItem.setText("Copy to Stacks (channels)");
image5dMenu.add(convertToStacksMenuItem);
final JMenuItem volumeViewerMenuItem = new JMenuItem();
volumeViewerMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Image5D_to_VolumeViewer volumeViewer = new Image5D_to_VolumeViewer();
volumeViewer.run("");
}
});
volumeViewerMenuItem.setText("VolumeViewer");
image5dMenu.add(volumeViewerMenuItem);
final JMenuItem splitImageMenuItem = new JMenuItem();
splitImageMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Split_Image5D splitImage = new Split_Image5D();
splitImage.run("");
}
});
splitImageMenuItem.setText("SplitView");
image5dMenu.add(splitImageMenuItem);
*/
final JMenu toolsMenu = new JMenu();
toolsMenu.setText("Tools");
menuBar_.add(toolsMenu);
final JMenuItem refreshMenuItem = new JMenuItem();
refreshMenuItem.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class, "icons/arrow_refresh.png"));
refreshMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
updateGUI(true);
}
});
refreshMenuItem.setText("Refresh GUI");
refreshMenuItem.setToolTipText("Refresh all GUI controls directly from the hardware");
toolsMenu.add(refreshMenuItem);
final JMenuItem rebuildGuiMenuItem = new JMenuItem();
rebuildGuiMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
initializeGUI();
}
});
rebuildGuiMenuItem.setText("Rebuild GUI");
rebuildGuiMenuItem.setToolTipText("Regenerate micromanager user interface");
toolsMenu.add(rebuildGuiMenuItem);
toolsMenu.addSeparator();
final JMenuItem scriptPanelMenuItem = new JMenuItem();
toolsMenu.add(scriptPanelMenuItem);
scriptPanelMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
scriptPanel_.setVisible(true);
}
});
scriptPanelMenuItem.setText("Script Panel...");
scriptPanelMenuItem.setToolTipText("Open micromanager script editor window");
final JMenuItem hotKeysMenuItem = new JMenuItem();
toolsMenu.add(hotKeysMenuItem);
hotKeysMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
HotKeysDialog hk = new HotKeysDialog
(guiColors_.background.get((options_.displayBackground_)));
//hk.setBackground(guiColors_.background.get((options_.displayBackground_)));
}
});
hotKeysMenuItem.setText("Shortcuts...");
hotKeysMenuItem.setToolTipText("Create keyboard shortcuts to activate image acquisition, mark positions, or run custom scripts");
final JMenuItem propertyEditorMenuItem = new JMenuItem();
toolsMenu.add(propertyEditorMenuItem);
propertyEditorMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
createPropertyEditor();
}
});
propertyEditorMenuItem.setText("Device/Property Browser...");
propertyEditorMenuItem.setToolTipText("Open new window to view and edit property values in current configuration");
toolsMenu.addSeparator();
final JMenuItem xyListMenuItem = new JMenuItem();
xyListMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
showXYPositionList();
}
});
xyListMenuItem.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class, "icons/application_view_list.png"));
xyListMenuItem.setText("XY List...");
toolsMenu.add(xyListMenuItem);
xyListMenuItem.setToolTipText("Open position list manager window");
final JMenuItem acquisitionMenuItem = new JMenuItem();
acquisitionMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openAcqControlDialog();
}
});
acquisitionMenuItem.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class, "icons/film.png"));
acquisitionMenuItem.setText("Multi-Dimensional Acquisition...");
toolsMenu.add(acquisitionMenuItem);
acquisitionMenuItem.setToolTipText("Open multi-dimensional acquisition window");
/*
final JMenuItem splitViewMenuItem = new JMenuItem();
splitViewMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
splitViewDialog();
}
});
splitViewMenuItem.setText("Split View...");
toolsMenu.add(splitViewMenuItem);
*/
centerAndDragMenuItem_ = new JCheckBoxMenuItem();
centerAndDragMenuItem_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (centerAndDragListener_ == null) {
centerAndDragListener_ = new CenterAndDragListener(core_, gui_);
}
if (!centerAndDragListener_.isRunning()) {
centerAndDragListener_.start();
centerAndDragMenuItem_.setSelected(true);
} else {
centerAndDragListener_.stop();
centerAndDragMenuItem_.setSelected(false);
}
mainPrefs_.putBoolean(MOUSE_MOVES_STAGE, centerAndDragMenuItem_.isSelected());
}
});
centerAndDragMenuItem_.setText("Mouse Moves Stage");
centerAndDragMenuItem_.setSelected(mainPrefs_.getBoolean(MOUSE_MOVES_STAGE, false));
centerAndDragMenuItem_.setToolTipText("When enabled, double clicking in live window moves stage");
toolsMenu.add(centerAndDragMenuItem_);
final JMenuItem calibrationMenuItem = new JMenuItem();
toolsMenu.add(calibrationMenuItem);
calibrationMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
createCalibrationListDlg();
}
});
calibrationMenuItem.setText("Pixel Size Calibration...");
toolsMenu.add(calibrationMenuItem);
String calibrationTooltip = "Define size calibrations specific to each objective lens. " +
"When the objective in use has a calibration defined, " +
"micromanager will automatically use it when " +
"calculating metadata";
String mrjProp = System.getProperty("mrj.version");
if (mrjProp != null && !mrjProp.equals(null)) // running on a mac
calibrationMenuItem.setToolTipText(calibrationTooltip);
else
calibrationMenuItem.setToolTipText(TooltipTextMaker.addHTMLBreaksForTooltip(calibrationTooltip));
toolsMenu.addSeparator();
final JMenuItem configuratorMenuItem = new JMenuItem();
configuratorMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
if (configChanged_) {
Object[] options = {"Yes", "No"};
int n = JOptionPane.showOptionDialog(null,
"Save Changed Configuration?", "Micro-Manager",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE, null, options,
options[0]);
if (n == JOptionPane.YES_OPTION) {
saveConfigPresets();
}
configChanged_ = false;
}
boolean liveRunning = false;
if (liveRunning_) {
liveRunning = liveRunning_;
enableLiveMode(false);
}
// unload all devices before starting configurator
core_.reset();
GUIUtils.preventDisplayAdapterChangeExceptions();
// run Configurator
ConfiguratorDlg configurator = new ConfiguratorDlg(core_,
sysConfigFile_);
configurator.setVisible(true);
GUIUtils.preventDisplayAdapterChangeExceptions();
// re-initialize the system with the new configuration file
sysConfigFile_ = configurator.getFileName();
mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_);
loadSystemConfiguration();
GUIUtils.preventDisplayAdapterChangeExceptions();
if (liveRunning) {
enableLiveMode(liveRunning);
}
} catch (Exception e) {
ReportingUtils.showError(e);
return;
}
}
});
configuratorMenuItem.setText("Hardware Configuration Wizard...");
toolsMenu.add(configuratorMenuItem);
configuratorMenuItem.setToolTipText("Open wizard to create new hardware configuration");
final JMenuItem loadSystemConfigMenuItem = new JMenuItem();
toolsMenu.add(loadSystemConfigMenuItem);
loadSystemConfigMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
loadConfiguration();
initializeGUI();
}
});
loadSystemConfigMenuItem.setText("Load Hardware Configuration...");
loadSystemConfigMenuItem.setToolTipText("Un-initialize current configuration and initialize new one");
switchConfigurationMenu_ = new JMenu();
for (int i=0; i<5; i++)
{
JMenuItem configItem = new JMenuItem();
configItem.setText(Integer.toString(i));
switchConfigurationMenu_.add(configItem);
}
final JMenuItem reloadConfigMenuItem = new JMenuItem();
toolsMenu.add(reloadConfigMenuItem);
reloadConfigMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
loadSystemConfiguration();
initializeGUI();
}
});
reloadConfigMenuItem.setText("Reload Hardware Configuration");
reloadConfigMenuItem.setToolTipText("Un-initialize current configuration and initialize most recently loaded configuration");
switchConfigurationMenu_.setText("Switch Hardware Configuration");
toolsMenu.add(switchConfigurationMenu_);
switchConfigurationMenu_.setToolTipText("Switch between recently used configurations");
final JMenuItem saveConfigurationPresetsMenuItem = new JMenuItem();
saveConfigurationPresetsMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
saveConfigPresets();
updateChannelCombos();
}
});
saveConfigurationPresetsMenuItem.setText("Save Configuration Settings as...");
toolsMenu.add(saveConfigurationPresetsMenuItem);
saveConfigurationPresetsMenuItem.setToolTipText("Save current configuration settings as new configuration file");
/*
final JMenuItem regenerateConfiguratorDeviceListMenuItem = new JMenuItem();
regenerateConfiguratorDeviceListMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Cursor oldc = Cursor.getDefaultCursor();
Cursor waitc = new Cursor(Cursor.WAIT_CURSOR);
setCursor(waitc);
StringBuffer resultFile = new StringBuffer();
MicroscopeModel.generateDeviceListFile(options_.enableDeviceDiscovery_, resultFile,core_);
setCursor(oldc);
}
});
regenerateConfiguratorDeviceListMenuItem.setText("Regenerate Configurator Device List");
toolsMenu.add(regenerateConfiguratorDeviceListMenuItem);
*/
toolsMenu.addSeparator();
final MMStudioMainFrame thisInstance = this;
final JMenuItem optionsMenuItem = new JMenuItem();
optionsMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
int oldBufsize = options_.circularBufferSizeMB_;
OptionsDlg dlg = new OptionsDlg(options_, core_, mainPrefs_,
thisInstance, sysConfigFile_);
dlg.setVisible(true);
// adjust memory footprint if necessary
if (oldBufsize != options_.circularBufferSizeMB_) {
try {
core_.setCircularBufferMemoryFootprint(options_.circularBufferSizeMB_);
} catch (Exception exc) {
ReportingUtils.showError(exc);
}
}
}
});
optionsMenuItem.setText("Options...");
toolsMenu.add(optionsMenuItem);
final JLabel binningLabel = new JLabel();
binningLabel.setFont(new Font("Arial", Font.PLAIN, 10));
binningLabel.setText("Binning");
topPanel.add(binningLabel);
topLayout.putConstraint(SpringLayout.SOUTH, binningLabel, 64,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, binningLabel, 43,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, binningLabel, 200 - 1,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, binningLabel, 112 - 1,
SpringLayout.WEST, topPanel);
labelImageDimensions_ = new JLabel();
labelImageDimensions_.setFont(new Font("Arial", Font.PLAIN, 10));
bottomPanel.add(labelImageDimensions_);
topLayout.putConstraint(SpringLayout.SOUTH, labelImageDimensions_,
-5, SpringLayout.SOUTH, bottomPanel);
topLayout.putConstraint(SpringLayout.NORTH, labelImageDimensions_,
-25, SpringLayout.SOUTH, bottomPanel);
topLayout.putConstraint(SpringLayout.EAST, labelImageDimensions_,
-5, SpringLayout.EAST, bottomPanel);
topLayout.putConstraint(SpringLayout.WEST, labelImageDimensions_,
5, SpringLayout.WEST, bottomPanel);
comboBinning_ = new JComboBox();
comboBinning_.setFont(new Font("Arial", Font.PLAIN, 10));
comboBinning_.setMaximumRowCount(4);
comboBinning_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
changeBinning();
}
});
topPanel.add(comboBinning_);
topLayout.putConstraint(SpringLayout.EAST, comboBinning_, 275,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, comboBinning_, 200,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.SOUTH, comboBinning_, 66,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, comboBinning_, 43,
SpringLayout.NORTH, topPanel);
final JLabel cameraSettingsLabel = new JLabel();
cameraSettingsLabel.setFont(new Font("Arial", Font.BOLD, 11));
cameraSettingsLabel.setText("Camera settings");
topPanel.add(cameraSettingsLabel);
topLayout.putConstraint(SpringLayout.EAST, cameraSettingsLabel,
211, SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, cameraSettingsLabel, 6,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.WEST, cameraSettingsLabel,
109, SpringLayout.WEST, topPanel);
configPad_ = new ConfigGroupPad();
configPad_.setFont(new Font("", Font.PLAIN, 10));
topPanel.add(configPad_);
topLayout.putConstraint(SpringLayout.EAST, configPad_, -4,
SpringLayout.EAST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, configPad_, 5,
SpringLayout.EAST, comboBinning_);
topLayout.putConstraint(SpringLayout.SOUTH, configPad_, -21,
SpringLayout.SOUTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, configPad_, 21,
SpringLayout.NORTH, topPanel);
configPadButtonPanel_ = new ConfigPadButtonPanel();
configPadButtonPanel_.setConfigPad(configPad_);
configPadButtonPanel_.setGUI(this);
topPanel.add(configPadButtonPanel_);
topLayout.putConstraint(SpringLayout.EAST, configPadButtonPanel_, -4,
SpringLayout.EAST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, configPadButtonPanel_, 5,
SpringLayout.EAST, comboBinning_);
topLayout.putConstraint(SpringLayout.SOUTH, configPadButtonPanel_, 0,
SpringLayout.SOUTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, configPadButtonPanel_, -18,
SpringLayout.SOUTH, topPanel);
final JLabel stateDeviceLabel = new JLabel();
stateDeviceLabel.setFont(new Font("Arial", Font.BOLD, 11));
stateDeviceLabel.setText("Configuration settings");
topPanel.add(stateDeviceLabel);
topLayout.putConstraint(SpringLayout.SOUTH, stateDeviceLabel, 0,
SpringLayout.SOUTH, cameraSettingsLabel);
topLayout.putConstraint(SpringLayout.NORTH, stateDeviceLabel, 0,
SpringLayout.NORTH, cameraSettingsLabel);
topLayout.putConstraint(SpringLayout.EAST, stateDeviceLabel, 150,
SpringLayout.WEST, configPad_);
topLayout.putConstraint(SpringLayout.WEST, stateDeviceLabel, 0,
SpringLayout.WEST, configPad_);
final JButton buttonAcqSetup = new JButton();
buttonAcqSetup.setMargin(new Insets(2, 2, 2, 2));
buttonAcqSetup.setIconTextGap(1);
buttonAcqSetup.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class, "/org/micromanager/icons/film.png"));
buttonAcqSetup.setToolTipText("Open multi-dimensional acquisition window");
buttonAcqSetup.setFont(new Font("Arial", Font.PLAIN, 10));
buttonAcqSetup.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openAcqControlDialog();
}
});
buttonAcqSetup.setText("Multi-D Acq.");
topPanel.add(buttonAcqSetup);
topLayout.putConstraint(SpringLayout.SOUTH, buttonAcqSetup, 91,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, buttonAcqSetup, 70,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, buttonAcqSetup, 95,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, buttonAcqSetup, 7,
SpringLayout.WEST, topPanel);
autoShutterCheckBox_ = new JCheckBox();
autoShutterCheckBox_.setFont(new Font("Arial", Font.PLAIN, 10));
autoShutterCheckBox_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
core_.setAutoShutter(autoShutterCheckBox_.isSelected());
if (shutterLabel_.length() > 0) {
try {
setShutterButton(core_.getShutterOpen());
} catch (Exception e1) {
ReportingUtils.showError(e1);
}
}
if (autoShutterCheckBox_.isSelected()) {
toggleButtonShutter_.setEnabled(false);
} else {
toggleButtonShutter_.setEnabled(true);
}
}
});
autoShutterCheckBox_.setIconTextGap(6);
autoShutterCheckBox_.setHorizontalTextPosition(SwingConstants.LEADING);
autoShutterCheckBox_.setText("Auto shutter");
topPanel.add(autoShutterCheckBox_);
topLayout.putConstraint(SpringLayout.EAST, autoShutterCheckBox_,
202 - 3, SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, autoShutterCheckBox_,
110 - 3, SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.SOUTH, autoShutterCheckBox_,
141 - 22, SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, autoShutterCheckBox_,
118 - 22, SpringLayout.NORTH, topPanel);
final JButton refreshButton = new JButton();
refreshButton.setMargin(new Insets(2, 2, 2, 2));
refreshButton.setIconTextGap(1);
refreshButton.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class,
"/org/micromanager/icons/arrow_refresh.png"));
refreshButton.setFont(new Font("Arial", Font.PLAIN, 10));
refreshButton.setToolTipText("Refresh all GUI controls directly from the hardware");
refreshButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
updateGUI(true);
}
});
refreshButton.setText("Refresh");
topPanel.add(refreshButton);
topLayout.putConstraint(SpringLayout.SOUTH, refreshButton, 113,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, refreshButton, 92,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, refreshButton, 95,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, refreshButton, 7,
SpringLayout.WEST, topPanel);
JLabel citePleaLabel = new JLabel("<html>Please <a href=\"http://micro-manager.org\">cite Micro-Manager</a> so funding will continue!</html>");
topPanel.add(citePleaLabel);
citePleaLabel.setFont(new Font("Arial", Font.PLAIN, 11));
topLayout.putConstraint(SpringLayout.SOUTH, citePleaLabel, 139,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, citePleaLabel, 119,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, citePleaLabel, 270,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, citePleaLabel, 7,
SpringLayout.WEST, topPanel);
class Pleader extends Thread{
Pleader(){
super("pleader");
}
@Override
public void run(){
try {
ij.plugin.BrowserLauncher.openURL("https://valelab.ucsf.edu/~MM/MMwiki/index.php/Citing_Micro-Manager");
} catch (IOException e1) {
ReportingUtils.showError(e1);
}
}
}
citePleaLabel.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
Pleader p = new Pleader();
p.start();
}
});
// add window listeners
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
closeSequence();
running_ = false;
}
@Override
public void windowOpened(WindowEvent e) {
// initialize hardware
try {
core_ = new CMMCore();
} catch(UnsatisfiedLinkError ex) {
ReportingUtils.showError(ex, "Failed to open libMMCoreJ_wrap.jnilib");
return;
}
ReportingUtils.setCore(core_);
//core_.setDeviceDiscoveryEnabled(options_.enableDeviceDiscovery_);
core_.enableDebugLog(options_.debugLogEnabled_);
core_.logMessage("MM Studio version: " + getVersion());
core_.logMessage(core_.getVersionInfo());
core_.logMessage(core_.getAPIVersionInfo());
core_.logMessage("Operating System: " + System.getProperty("os.name") + " " + System.getProperty("os.version"));
cameraLabel_ = "";
shutterLabel_ = "";
zStageLabel_ = "";
xyStageLabel_ = "";
engine_ = new AcquisitionWrapperEngine();
// register callback for MMCore notifications, this is a global
// to avoid garbage collection
cb_ = new CoreEventCallback();
core_.registerCallback(cb_);
try {
core_.setCircularBufferMemoryFootprint(options_.circularBufferSizeMB_);
} catch (Exception e2) {
ReportingUtils.showError(e2);
}
MMStudioMainFrame parent = (MMStudioMainFrame) e.getWindow();
if (parent != null) {
engine_.setParentGUI(parent);
}
loadMRUConfigFiles();
initializePlugins();
toFront();
if (!options_.doNotAskForConfigFile_) {
MMIntroDlg introDlg = new MMIntroDlg(VERSION, MRUConfigFiles_);
introDlg.setConfigFile(sysConfigFile_);
introDlg.setBackground(guiColors_.background.get((options_.displayBackground_)));
introDlg.setVisible(true);
sysConfigFile_ = introDlg.getConfigFile();
}
saveMRUConfigFiles();
mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_);
paint(MMStudioMainFrame.this.getGraphics());
engine_.setCore(core_, afMgr_);
posList_ = new PositionList();
engine_.setPositionList(posList_);
// load (but do no show) the scriptPanel
createScriptPanel();
// Create an instance of HotKeys so that they can be read in from prefs
hotKeys_ = new org.micromanager.utils.HotKeys();
hotKeys_.loadSettings();
// if an error occurred during config loading,
// do not display more errors than needed
if (!loadSystemConfiguration())
ReportingUtils.showErrorOn(false);
executeStartupScript();
// Create Multi-D window here but do not show it.
// This window needs to be created in order to properly set the "ChannelGroup"
// based on the Multi-D parameters
acqControlWin_ = new AcqControlDlg(engine_, mainPrefs_, MMStudioMainFrame.this);
addMMBackgroundListener(acqControlWin_);
configPad_.setCore(core_);
if (parent != null) {
configPad_.setParentGUI(parent);
}
configPadButtonPanel_.setCore(core_);
// initialize controls
initializeGUI();
initializeHelpMenu();
String afDevice = mainPrefs_.get(AUTOFOCUS_DEVICE, "");
if (afMgr_.hasDevice(afDevice)) {
try {
afMgr_.selectDevice(afDevice);
} catch (MMException e1) {
// this error should never happen
ReportingUtils.showError(e1);
}
}
// switch error reporting back on
ReportingUtils.showErrorOn(true);
}
private void initializePlugins() {
pluginMenu_ = new JMenu();
pluginMenu_.setText("Plugins");
menuBar_.add(pluginMenu_);
new Thread("Plugin loading") {
@Override
public void run() {
// Needed for loading clojure-based jars:
Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
loadPlugins();
}
}.run();
}
});
final JButton setRoiButton = new JButton();
setRoiButton.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class,
"/org/micromanager/icons/shape_handles.png"));
setRoiButton.setFont(new Font("Arial", Font.PLAIN, 10));
setRoiButton.setToolTipText("Set Region Of Interest to selected rectangle");
setRoiButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setROI();
}
});
topPanel.add(setRoiButton);
topLayout.putConstraint(SpringLayout.EAST, setRoiButton, 37,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, setRoiButton, 7,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.SOUTH, setRoiButton, 174,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, setRoiButton, 154,
SpringLayout.NORTH, topPanel);
final JButton clearRoiButton = new JButton();
clearRoiButton.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class,
"/org/micromanager/icons/arrow_out.png"));
clearRoiButton.setFont(new Font("Arial", Font.PLAIN, 10));
clearRoiButton.setToolTipText("Reset Region of Interest to full frame");
clearRoiButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
clearROI();
}
});
topPanel.add(clearRoiButton);
topLayout.putConstraint(SpringLayout.EAST, clearRoiButton, 70,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, clearRoiButton, 40,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.SOUTH, clearRoiButton, 174,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, clearRoiButton, 154,
SpringLayout.NORTH, topPanel);
final JLabel regionOfInterestLabel = new JLabel();
regionOfInterestLabel.setFont(new Font("Arial", Font.BOLD, 11));
regionOfInterestLabel.setText("ROI");
topPanel.add(regionOfInterestLabel);
topLayout.putConstraint(SpringLayout.SOUTH, regionOfInterestLabel,
154, SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, regionOfInterestLabel,
140, SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, regionOfInterestLabel,
71, SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, regionOfInterestLabel,
8, SpringLayout.WEST, topPanel);
contrastPanel_ = new ContrastPanel();
contrastPanel_.setFont(new Font("", Font.PLAIN, 10));
contrastPanel_.setContrastStretch(stretch);
contrastPanel_.setRejectOutliers(reject);
contrastPanel_.setFractionToReject(rejectFract);
contrastPanel_.setBorder(BorderFactory.createEmptyBorder());
bottomPanel.add(contrastPanel_);
topLayout.putConstraint(SpringLayout.SOUTH, contrastPanel_, -20,
SpringLayout.SOUTH, bottomPanel);
topLayout.putConstraint(SpringLayout.NORTH, contrastPanel_, 0,
SpringLayout.NORTH, bottomPanel);
topLayout.putConstraint(SpringLayout.EAST, contrastPanel_, 0,
SpringLayout.EAST, bottomPanel);
topLayout.putConstraint(SpringLayout.WEST, contrastPanel_, 0,
SpringLayout.WEST, bottomPanel);
metadataPanel_ = new MetadataPanel();
metadataPanel_.setVisible(false);
bottomPanel.add(metadataPanel_);
topLayout.putConstraint(SpringLayout.SOUTH, metadataPanel_, -20,
SpringLayout.SOUTH, bottomPanel);
topLayout.putConstraint(SpringLayout.NORTH, metadataPanel_, 0,
SpringLayout.NORTH, bottomPanel);
topLayout.putConstraint(SpringLayout.EAST, metadataPanel_, 0,
SpringLayout.EAST, bottomPanel);
topLayout.putConstraint(SpringLayout.WEST, metadataPanel_, 0,
SpringLayout.WEST, bottomPanel);
metadataPanel_.setBorder(BorderFactory.createEmptyBorder());
GUIUtils.registerImageFocusListener(new ImageFocusListener() {
public void focusReceived(ImageWindow focusedWindow) {
if (focusedWindow == null) {
contrastPanel_.setVisible(true);
metadataPanel_.setVisible(false);
} else if (focusedWindow instanceof MMImageWindow) {
contrastPanel_.setVisible(true);
metadataPanel_.setVisible(false);
} else if (focusedWindow.getImagePlus().getStack() instanceof AcquisitionVirtualStack) {
contrastPanel_.setVisible(false);
metadataPanel_.setVisible(true);
}
}
});
final JLabel regionOfInterestLabel_1 = new JLabel();
regionOfInterestLabel_1.setFont(new Font("Arial", Font.BOLD, 11));
regionOfInterestLabel_1.setText("Zoom");
topPanel.add(regionOfInterestLabel_1);
topLayout.putConstraint(SpringLayout.SOUTH,
regionOfInterestLabel_1, 154, SpringLayout.NORTH,
topPanel);
topLayout.putConstraint(SpringLayout.NORTH,
regionOfInterestLabel_1, 140, SpringLayout.NORTH,
topPanel);
topLayout.putConstraint(SpringLayout.EAST, regionOfInterestLabel_1,
139, SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, regionOfInterestLabel_1,
81, SpringLayout.WEST, topPanel);
final JButton zoomInButton = new JButton();
zoomInButton.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
zoomIn();
}
});
zoomInButton.setIcon(SwingResourceManager.getIcon(MMStudioMainFrame.class,
"/org/micromanager/icons/zoom_in.png"));
zoomInButton.setToolTipText("Zoom in");
zoomInButton.setFont(new Font("Arial", Font.PLAIN, 10));
topPanel.add(zoomInButton);
topLayout.putConstraint(SpringLayout.SOUTH, zoomInButton, 174,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, zoomInButton, 154,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, zoomInButton, 110,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, zoomInButton, 80,
SpringLayout.WEST, topPanel);
final JButton zoomOutButton = new JButton();
zoomOutButton.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
zoomOut();
}
});
zoomOutButton.setIcon(SwingResourceManager.getIcon(MMStudioMainFrame.class,
"/org/micromanager/icons/zoom_out.png"));
zoomOutButton.setToolTipText("Zoom out");
zoomOutButton.setFont(new Font("Arial", Font.PLAIN, 10));
topPanel.add(zoomOutButton);
topLayout.putConstraint(SpringLayout.SOUTH, zoomOutButton, 174,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, zoomOutButton, 154,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, zoomOutButton, 143,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, zoomOutButton, 113,
SpringLayout.WEST, topPanel);
// Profile
final JLabel profileLabel_ = new JLabel();
profileLabel_.setFont(new Font("Arial", Font.BOLD, 11));
profileLabel_.setText("Profile");
topPanel.add(profileLabel_);
topLayout.putConstraint(SpringLayout.SOUTH, profileLabel_, 154,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, profileLabel_, 140,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, profileLabel_, 217,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, profileLabel_, 154,
SpringLayout.WEST, topPanel);
final JButton buttonProf = new JButton();
buttonProf.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class,
"/org/micromanager/icons/chart_curve.png"));
buttonProf.setFont(new Font("Arial", Font.PLAIN, 10));
buttonProf.setToolTipText("Open line profile window (requires line selection)");
buttonProf.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openLineProfileWindow();
}
});
// buttonProf.setText("Profile");
topPanel.add(buttonProf);
topLayout.putConstraint(SpringLayout.SOUTH, buttonProf, 174,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, buttonProf, 154,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, buttonProf, 183,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, buttonProf, 153,
SpringLayout.WEST, topPanel);
// Autofocus
final JLabel autofocusLabel_ = new JLabel();
autofocusLabel_.setFont(new Font("Arial", Font.BOLD, 11));
autofocusLabel_.setText("Autofocus");
topPanel.add(autofocusLabel_);
topLayout.putConstraint(SpringLayout.SOUTH, autofocusLabel_, 154,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, autofocusLabel_, 140,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, autofocusLabel_, 274,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, autofocusLabel_, 194,
SpringLayout.WEST, topPanel);
buttonAutofocus_ = new JButton();
buttonAutofocus_.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class,
"/org/micromanager/icons/find.png"));
buttonAutofocus_.setFont(new Font("Arial", Font.PLAIN, 10));
buttonAutofocus_.setToolTipText("Autofocus now");
buttonAutofocus_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (afMgr_.getDevice() != null) {
new Thread() {
@Override
public void run() {
try {
boolean lmo = isLiveModeOn();
if(lmo)
enableLiveMode(false);
afMgr_.getDevice().fullFocus();
if(lmo)
enableLiveMode(true);
} catch (MMException ex) {
ReportingUtils.logError(ex);
}
}
}.start(); // or any other method from Autofocus.java API
}
}
});
topPanel.add(buttonAutofocus_);
topLayout.putConstraint(SpringLayout.SOUTH, buttonAutofocus_, 174,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, buttonAutofocus_, 154,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, buttonAutofocus_, 223,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, buttonAutofocus_, 193,
SpringLayout.WEST, topPanel);
buttonAutofocusTools_ = new JButton();
buttonAutofocusTools_.setIcon(SwingResourceManager.getIcon(
MMStudioMainFrame.class,
"/org/micromanager/icons/wrench_orange.png"));
buttonAutofocusTools_.setFont(new Font("Arial", Font.PLAIN, 10));
buttonAutofocusTools_.setToolTipText("Set autofocus options");
buttonAutofocusTools_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showAutofocusDialog();
}
});
topPanel.add(buttonAutofocusTools_);
topLayout.putConstraint(SpringLayout.SOUTH, buttonAutofocusTools_, 174,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, buttonAutofocusTools_, 154,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, buttonAutofocusTools_, 256,
SpringLayout.WEST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, buttonAutofocusTools_, 226,
SpringLayout.WEST, topPanel);
saveConfigButton_ = new JButton();
saveConfigButton_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
saveConfigPresets();
}
});
saveConfigButton_.setToolTipText("Save current presets to the configuration file");
saveConfigButton_.setText("Save");
saveConfigButton_.setEnabled(false);
topPanel.add(saveConfigButton_);
topLayout.putConstraint(SpringLayout.SOUTH, saveConfigButton_, 20,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.NORTH, saveConfigButton_, 2,
SpringLayout.NORTH, topPanel);
topLayout.putConstraint(SpringLayout.EAST, saveConfigButton_, -5,
SpringLayout.EAST, topPanel);
topLayout.putConstraint(SpringLayout.WEST, saveConfigButton_, -80,
SpringLayout.EAST, topPanel);
// Add our own keyboard manager that handles Micro-Manager shortcuts
MMKeyDispatcher mmKD = new MMKeyDispatcher(gui_);
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(mmKD);
}
private void handleException(Exception e, String msg) {
String errText = "Exception occurred: ";
if (msg.length() > 0) {
errText += msg + "
}
if (options_.debugLogEnabled_) {
errText += e.getMessage();
} else {
errText += e.toString() + "\n";
ReportingUtils.showError(e);
}
handleError(errText);
}
private void handleException(Exception e) {
handleException(e, "");
}
private void handleError(String message) {
if (isLiveModeOn()) {
// Should we always stop live mode on any error?
enableLiveMode(false);
}
JOptionPane.showMessageDialog(this, message);
core_.logMessage(message);
}
public void makeActive() {
toFront();
}
private void setExposure() {
try {
core_.setExposure(NumberUtils.displayStringToDouble(textFieldExp_.getText()));
// Display the new exposure time
double exposure = core_.getExposure();
textFieldExp_.setText(NumberUtils.doubleToDisplayString(exposure));
// Interval for Live Mode changes as well
setLiveModeInterval();
} catch (Exception exp) {
// Do nothing.
}
}
public boolean getConserveRamOption() {
return options_.conserveRam_;
}
public boolean getAutoreloadOption() {
return options_.autoreloadDevices_;
}
private void updateTitle() {
this.setTitle("System: " + sysConfigFile_);
}
private void updateLineProfile() {
if (!isImageWindowOpen() || profileWin_ == null
|| !profileWin_.isShowing()) {
return;
}
calculateLineProfileData(imageWin_.getImagePlus());
profileWin_.setData(lineProfileData_);
}
private void openLineProfileWindow() {
if (imageWin_ == null || imageWin_.isClosed()) {
return;
}
calculateLineProfileData(imageWin_.getImagePlus());
if (lineProfileData_ == null) {
return;
}
profileWin_ = new GraphFrame();
profileWin_.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
profileWin_.setData(lineProfileData_);
profileWin_.setAutoScale();
profileWin_.setTitle("Live line profile");
profileWin_.setBackground(guiColors_.background.get((options_.displayBackground_)));
addMMBackgroundListener(profileWin_);
profileWin_.setVisible(true);
}
public Rectangle getROI() throws MMScriptException {
// ROI values are give as x,y,w,h in individual one-member arrays (pointers in C++):
int[][] a = new int[4][1];
try {
core_.getROI(a[0], a[1], a[2], a[3]);
} catch (Exception e) {
throw new MMScriptException(e.getMessage());
}
// Return as a single array with x,y,w,h:
return new Rectangle(a[0][0], a[1][0], a[2][0], a[3][0]);
}
private void calculateLineProfileData(ImagePlus imp) {
// generate line profile
Roi roi = imp.getRoi();
if (roi == null || !roi.isLine()) {
// if there is no line ROI, create one
Rectangle r = imp.getProcessor().getRoi();
int iWidth = r.width;
int iHeight = r.height;
int iXROI = r.x;
int iYROI = r.y;
if (roi == null) {
iXROI += iWidth / 2;
iYROI += iHeight / 2;
}
roi = new Line(iXROI - iWidth / 4, iYROI - iWidth / 4, iXROI
+ iWidth / 4, iYROI + iHeight / 4);
imp.setRoi(roi);
roi = imp.getRoi();
}
ImageProcessor ip = imp.getProcessor();
ip.setInterpolate(true);
Line line = (Line) roi;
if (lineProfileData_ == null) {
lineProfileData_ = new GraphData();
}
lineProfileData_.setData(line.getPixels());
}
public void setROI(Rectangle r) throws MMScriptException {
boolean liveRunning = false;
if (liveRunning_) {
liveRunning = liveRunning_;
enableLiveMode(false);
}
try {
core_.setROI(r.x, r.y, r.width, r.height);
} catch (Exception e) {
throw new MMScriptException(e.getMessage());
}
updateStaticInfo();
if (liveRunning) {
enableLiveMode(true);
}
}
private void setROI() {
ImagePlus curImage = WindowManager.getCurrentImage();
if (curImage == null) {
return;
}
Roi roi = curImage.getRoi();
try {
if (roi == null) {
// if there is no ROI, create one
Rectangle r = curImage.getProcessor().getRoi();
int iWidth = r.width;
int iHeight = r.height;
int iXROI = r.x;
int iYROI = r.y;
if (roi == null) {
iWidth /= 2;
iHeight /= 2;
iXROI += iWidth / 2;
iYROI += iHeight / 2;
}
curImage.setRoi(iXROI, iYROI, iWidth, iHeight);
roi = curImage.getRoi();
}
if (roi.getType() != Roi.RECTANGLE) {
handleError("ROI must be a rectangle.\nUse the ImageJ rectangle tool to draw the ROI.");
return;
}
Rectangle r = roi.getBoundingRect();
// Stop (and restart) live mode if it is running
setROI(r);
} catch (Exception e) {
ReportingUtils.showError(e);
}
}
private void clearROI() {
try {
boolean liveRunning = false;
if (liveRunning_) {
liveRunning = liveRunning_;
enableLiveMode(false);
}
core_.clearROI();
updateStaticInfo();
if (liveRunning) {
enableLiveMode(true);
}
} catch (Exception e) {
ReportingUtils.showError(e);
}
}
private BooleanLock creatingImageWindow_ = new BooleanLock(false);
private static long waitForCreateImageWindowTimeout_ = 5000;
private MMImageWindow createImageWindow() {
if (creatingImageWindow_.isTrue()) {
try {
creatingImageWindow_.waitToSetFalse(waitForCreateImageWindowTimeout_);
} catch (Exception e) {
ReportingUtils.showError(e);
}
return imageWin_;
}
creatingImageWindow_.setValue(true);
MMImageWindow win = imageWin_;
removeMMBackgroundListener(imageWin_);
imageWin_ = null;
try {
if (win != null) {
win.saveAttributes();
win.dispose();
win = null;
}
win = new MMImageWindow(core_, this);
core_.logMessage("createImageWin1");
win.setBackground(guiColors_.background.get((options_.displayBackground_)));
addMMBackgroundListener(win);
setIJCal(win);
// listeners
if (centerAndDragListener_ != null
&& centerAndDragListener_.isRunning()) {
centerAndDragListener_.attach(win.getImagePlus().getWindow());
}
if (zWheelListener_ != null && zWheelListener_.isRunning()) {
zWheelListener_.attach(win.getImagePlus().getWindow());
}
if (xyzKeyListener_ != null && xyzKeyListener_.isRunning()) {
xyzKeyListener_.attach(win.getImagePlus().getWindow());
}
win.getCanvas().requestFocus();
imageWin_ = win;
} catch (Exception e) {
if (win != null) {
win.saveAttributes();
WindowManager.removeWindow(win);
win.dispose();
}
ReportingUtils.showError(e);
}
creatingImageWindow_.setValue(false);
return imageWin_;
}
/**
* Returns instance of the core uManager object;
*/
public CMMCore getMMCore() {
return core_;
}
/**
* Returns singleton instance of MMStudioMainFrame
*/
public static MMStudioMainFrame getInstance() {
return gui_;
}
public final void setExitStrategy(boolean closeOnExit) {
if (closeOnExit)
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
else
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
public void saveConfigPresets() {
MicroscopeModel model = new MicroscopeModel();
try {
model.loadFromFile(sysConfigFile_);
model.createSetupConfigsFromHardware(core_);
model.createResolutionsFromHardware(core_);
File f = FileDialogs.save(this, "Save the configuration file", MM_CONFIG_FILE);
if (f != null) {
model.saveToFile(f.getAbsolutePath());
sysConfigFile_ = f.getAbsolutePath();
mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_);
configChanged_ = false;
setConfigSaveButtonStatus(configChanged_);
updateTitle();
}
} catch (MMConfigFileException e) {
ReportingUtils.showError(e);
}
}
protected void setConfigSaveButtonStatus(boolean changed) {
saveConfigButton_.setEnabled(changed);
}
public String getAcqDirectory() {
return openAcqDirectory_;
}
public void setAcqDirectory(String dir) {
openAcqDirectory_ = dir;
}
/**
* Open an existing acquisition directory and build viewer window.
*
*/
public void openAcquisitionData() {
// choose the directory
File f = FileDialogs.openDir(this, "Please select an image data set", MM_DATA_SET);
if (f != null) {
if (f.isDirectory()) {
openAcqDirectory_ = f.getAbsolutePath();
} else {
openAcqDirectory_ = f.getParent();
}
openAcquisitionData(openAcqDirectory_);
}
}
public void openAcquisitionData(String dir) {
String rootDir = new File(dir).getAbsolutePath();
String name = new File(dir).getName();
rootDir= rootDir.substring(0, rootDir.length() - (name.length() + 1));
try {
acqMgr_.openAcquisition(name, rootDir, true, true, true);
acqMgr_.getAcquisition(name).initialize();
acqMgr_.closeAcquisition(name);
} catch (MMScriptException ex) {
ReportingUtils.showError(ex);
}
}
protected void zoomOut() {
ImageWindow curWin = WindowManager.getCurrentWindow();
if (curWin != null) {
ImageCanvas canvas = curWin.getCanvas();
Rectangle r = canvas.getBounds();
canvas.zoomOut(r.width / 2, r.height / 2);
}
}
protected void zoomIn() {
ImageWindow curWin = WindowManager.getCurrentWindow();
if (curWin != null) {
ImageCanvas canvas = curWin.getCanvas();
Rectangle r = canvas.getBounds();
canvas.zoomIn(r.width / 2, r.height / 2);
}
}
protected void changeBinning() {
try {
boolean liveRunning = false;
if (liveRunning_) {
liveRunning = liveRunning_;
enableLiveMode(false);
}
if (isCameraAvailable()) {
Object item = comboBinning_.getSelectedItem();
if (item != null) {
core_.setProperty(cameraLabel_, MMCoreJ.getG_Keyword_Binning(), item.toString());
}
}
updateStaticInfo();
if (liveRunning) {
enableLiveMode(true);
}
} catch (Exception e) {
ReportingUtils.showError(e);
}
}
private void createPropertyEditor() {
if (propertyBrowser_ != null) {
propertyBrowser_.dispose();
}
propertyBrowser_ = new PropertyEditor();
propertyBrowser_.setGui(this);
propertyBrowser_.setVisible(true);
propertyBrowser_.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
propertyBrowser_.setCore(core_);
}
private void createCalibrationListDlg() {
if (calibrationListDlg_ != null) {
calibrationListDlg_.dispose();
}
calibrationListDlg_ = new CalibrationListDlg(core_);
calibrationListDlg_.setVisible(true);
calibrationListDlg_.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
calibrationListDlg_.setParentGUI(this);
}
public CalibrationListDlg getCalibrationListDlg() {
if (calibrationListDlg_ == null) {
createCalibrationListDlg();
}
return calibrationListDlg_;
}
private void createScriptPanel() {
if (scriptPanel_ == null) {
scriptPanel_ = new ScriptPanel(core_, options_, this);
scriptPanel_.insertScriptingObject(SCRIPT_CORE_OBJECT, core_);
scriptPanel_.insertScriptingObject(SCRIPT_ACQENG_OBJECT, engine_);
scriptPanel_.setParentGUI(this);
scriptPanel_.setBackground(guiColors_.background.get((options_.displayBackground_)));
addMMBackgroundListener(scriptPanel_);
}
}
/**
* Updates Status line in main window from cached values
*/
private void updateStaticInfoFromCache() {
String dimText = "Image size: " + staticInfo_.width_ + " X " + staticInfo_.height_ + " X "
+ staticInfo_.bytesPerPixel_ + ", Intensity range: " + staticInfo_.imageBitDepth_ + " bits";
dimText += ", " + TextUtils.FMT0.format(staticInfo_.pixSizeUm_ * 1000) + "nm/pix";
if (zStageLabel_.length() > 0) {
dimText += ", Z=" + TextUtils.FMT2.format(staticInfo_.zPos_) + "um";
}
if (xyStageLabel_.length() > 0) {
dimText += ", XY=(" + TextUtils.FMT2.format(staticInfo_.x_) + "," + TextUtils.FMT2.format(staticInfo_.y_) + ")um";
}
labelImageDimensions_.setText(dimText);
}
public void updateXYPos(double x, double y) {
staticInfo_.x_ = x;
staticInfo_.y_ = y;
updateStaticInfoFromCache();
}
public void updateZPos(double z) {
staticInfo_.zPos_ = z;
updateStaticInfoFromCache();
}
public void updateXYPosRelative(double x, double y) {
staticInfo_.x_ += x;
staticInfo_.y_ += y;
updateStaticInfoFromCache();
}
public void updateZPosRelative(double z) {
staticInfo_.zPos_ += z;
updateStaticInfoFromCache();
}
public void updateXYStagePosition(){
double x[] = new double[1];
double y[] = new double[1];
try {
if (xyStageLabel_.length() > 0)
core_.getXYPosition(xyStageLabel_, x, y);
} catch (Exception e) {
ReportingUtils.showError(e);
}
staticInfo_.x_ = x[0];
staticInfo_.y_ = y[0];
updateStaticInfoFromCache();
}
private void updatePixSizeUm (double pixSizeUm) {
staticInfo_.pixSizeUm_ = pixSizeUm;
updateStaticInfoFromCache();
}
private void updateStaticInfo() {
double zPos = 0.0;
double x[] = new double[1];
double y[] = new double[1];
try {
if (zStageLabel_.length() > 0) {
zPos = core_.getPosition(zStageLabel_);
}
if (xyStageLabel_.length() > 0) {
core_.getXYPosition(xyStageLabel_, x, y);
}
} catch (Exception e) {
handleException(e);
}
staticInfo_.width_ = core_.getImageWidth();
staticInfo_.height_ = core_.getImageHeight();
staticInfo_.bytesPerPixel_ = core_.getBytesPerPixel();
staticInfo_.imageBitDepth_ = core_.getImageBitDepth();
staticInfo_.pixSizeUm_ = core_.getPixelSizeUm();
staticInfo_.zPos_ = zPos;
staticInfo_.x_ = x[0];
staticInfo_.y_ = y[0];
updateStaticInfoFromCache();
}
public void toggleShutter() {
try {
if (!toggleButtonShutter_.isEnabled())
return;
toggleButtonShutter_.requestFocusInWindow();
if (toggleButtonShutter_.getText().equals("Open")) {
setShutterButton(true);
core_.setShutterOpen(true);
} else {
core_.setShutterOpen(false);
setShutterButton(false);
}
} catch (Exception e1) {
ReportingUtils.showError(e1);
}
}
private void setShutterButton(boolean state) {
if (state) {
toggleButtonShutter_.setSelected(true);
toggleButtonShutter_.setText("Close");
} else {
toggleButtonShutter_.setSelected(false);
toggleButtonShutter_.setText("Open");
}
}
// public interface available for scripting access
public void snapSingleImage() {
doSnap();
}
public Object getPixels() {
if (imageWin_ != null) {
return imageWin_.getImagePlus().getProcessor().getPixels();
}
return null;
}
public void setPixels(Object obj) {
if (imageWin_ == null) {
return;
}
imageWin_.getImagePlus().getProcessor().setPixels(obj);
}
public int getImageHeight() {
if (imageWin_ != null) {
return imageWin_.getImagePlus().getHeight();
}
return 0;
}
public int getImageWidth() {
if (imageWin_ != null) {
return imageWin_.getImagePlus().getWidth();
}
return 0;
}
public int getImageDepth() {
if (imageWin_ != null) {
return imageWin_.getImagePlus().getBitDepth();
}
return 0;
}
public ImageProcessor getImageProcessor() {
if (imageWin_ == null) {
return null;
}
return imageWin_.getImagePlus().getProcessor();
}
private boolean isCameraAvailable() {
return cameraLabel_.length() > 0;
}
/**
* Part of ScriptInterface API
* Opens the XYPositionList when it is not opened
* Adds the current position to the list (same as pressing the "Mark" button)
*/
public void markCurrentPosition() {
if (posListDlg_ == null) {
showXYPositionList();
}
if (posListDlg_ != null) {
posListDlg_.markPosition();
}
}
/**
* Implements ScriptInterface
*/
public AcqControlDlg getAcqDlg() {
return acqControlWin_;
}
/**
* Implements ScriptInterface
*/
public PositionListDlg getXYPosListDlg() {
if (posListDlg_ == null)
posListDlg_ = new PositionListDlg(core_, this, posList_, options_);
return posListDlg_;
}
/**
* Implements ScriptInterface
*/
public boolean isAcquisitionRunning() {
if (engine_ == null)
return false;
return engine_.isAcquisitionRunning();
}
/**
* Implements ScriptInterface
*/
public boolean versionLessThan(String version) throws MMScriptException {
try {
String[] v = VERSION.split(" ", 2);
String[] m = v[0].split("\\.", 3);
String[] v2 = version.split(" ", 2);
String[] m2 = v2[0].split("\\.", 3);
for (int i=0; i < 3; i++) {
if (Integer.parseInt(m[i]) < Integer.parseInt(m2[i])) {
ReportingUtils.showError("This code needs Micro-Manager version " + version + " or greater");
return true;
}
if (Integer.parseInt(m[i]) > Integer.parseInt(m2[i])) {
return false;
}
}
if (v2.length < 2 || v2[1].equals("") )
return false;
if (v.length < 2 ) {
ReportingUtils.showError("This code needs Micro-Manager version " + version + " or greater");
return true;
}
if (Integer.parseInt(v[1]) < Integer.parseInt(v2[1])) {
ReportingUtils.showError("This code needs Micro-Manager version " + version + " or greater");
return false;
}
return true;
} catch (Exception ex) {
throw new MMScriptException ("Format of version String should be \"a.b.c\"");
}
}
public boolean isImageWindowOpen() {
boolean ret = imageWin_ != null;
ret = ret && !imageWin_.isClosed();
if (ret) {
try {
Graphics g = imageWin_.getGraphics();
if (null != g) {
int ww = imageWin_.getWidth();
g.clearRect(0, 0, ww, 40);
imageWin_.drawInfo(g);
} else {
// explicitly clean up if Graphics is null, rather
// than cleaning up in the exception handler below..
WindowManager.removeWindow(imageWin_);
imageWin_.saveAttributes();
imageWin_.dispose();
imageWin_ = null;
ret = false;
}
} catch (Exception e) {
WindowManager.removeWindow(imageWin_);
imageWin_.saveAttributes();
imageWin_.dispose();
imageWin_ = null;
ReportingUtils.showError(e);
ret = false;
}
}
return ret;
}
public boolean isLiveModeOn() {
if (core_.getNumberOfComponents() == 1) {
return liveModeTimerTask_ != null && liveModeTimerTask_.isRunning();
} else {
return getPipeline().isLiveRunning();
}
}
// Timer task that displays the live image
class LiveModeTimerTask extends TimerTask {
public boolean running_ = false;
public synchronized boolean isRunning() {
return running_;
}
@Override
public synchronized boolean cancel() {
running_ = false;
return super.cancel();
}
public void run() {
Thread.currentThread().setPriority(3);
running_ = true;
if (!multiChannelCamera_ && !isImageWindowOpen()) {
// stop live acquisition if user closed the window
enableLiveMode(false);
return;
} else if (multiChannelCamera_ && !acquisitionExists(multiCameraAcq_)) {
enableLiveMode(false);
return;
}
try {
if (core_.getRemainingImageCount() > 0) {
if (!multiChannelCamera_) {
Object img = core_.getLastImage();
if (img != img_) {
img_ = img;
displayImage(img_);
Thread.yield();
}
} else {
boolean foundAll = false;
boolean[] found = new boolean[(int)multiChannelCameraNrCh_];
while (!foundAll && core_.getRemainingImageCount() > 0) {
TaggedImage ti = core_.getLastTaggedImage();
int channel = ti.tags.getInt("CameraChannelIndex");
if (!found[channel]) {
found[channel] = true;
ti.tags.put("Channel", core_.getCameraChannelName(channel));
MDUtils.setChannelIndex(ti.tags, channel);
MDUtils.setFrameIndex(ti.tags, 0);
MDUtils.setSliceIndex(ti.tags, 0);
MDUtils.setPositionIndex(ti.tags, 0);
boolean update = false;
if (multiChannelCameraNrCh_ == channel + 1)
update = true;
addImage(multiCameraAcq_, ti, update);
if (!acquisitionExists(multiCameraAcq_)) {
enableLiveMode(false);
return;
}
// TODO: remove after debugging
System.out.println("Channel: " + channel);
foundAll = true;
for (int i = 0; i < found.length; i++)
if (!found[i])
foundAll = false;
}
}
}
}
} catch (Exception e) {
ReportingUtils.showError(e);
enableLiveMode(false);
return;
}
}
};
public void enableLiveMode(boolean enable) {
if (core_ == null)
return;
if (core_.getNumberOfComponents() == 1) {
if (enable) {
if (isLiveModeOn()) {
return;
}
try {
multiChannelCameraNrCh_ = core_.getNumberOfCameraChannels();
if (multiChannelCameraNrCh_ > 1) {
multiChannelCamera_ = true;
checkMultiChannelWindow();
getAcquisition(multiCameraAcq_).toFront();
} else {
multiChannelCamera_ = false;
if (!isImageWindowOpen() && creatingImageWindow_.isFalse()) {
imageWin_ = createImageWindow();
}
// this is needed to clear the subtitle, should be folded into
// drawInfo
imageWin_.getGraphics().clearRect(0, 0, imageWin_.getWidth(),
40);
imageWin_.drawInfo(imageWin_.getGraphics());
imageWin_.toFront();
}
// turn off auto shutter and open the shutter
autoShutterOrg_ = core_.getAutoShutter();
if (shutterLabel_.length() > 0) {
shutterOrg_ = core_.getShutterOpen();
}
core_.setAutoShutter(false);
// Hide the autoShutter Checkbox
autoShutterCheckBox_.setEnabled(false);
shutterLabel_ = core_.getShutterDevice();
// only open the shutter when we have one and the Auto shutter
// checkbox was checked
if ((shutterLabel_.length() > 0) && autoShutterOrg_) {
core_.setShutterOpen(true);
}
if (!multiChannelCamera_) {
// attach mouse wheel listener to control focus:
if (zWheelListener_ == null) {
zWheelListener_ = new ZWheelListener(core_, this);
}
zWheelListener_.start(imageWin_);
// attach key listener to control the stage and focus:
if (xyzKeyListener_ == null) {
xyzKeyListener_ = new XYZKeyListener(core_, this);
}
xyzKeyListener_.start(imageWin_);
}
// Do not display more often than dictated by the exposure time
setLiveModeInterval();
core_.startContinuousSequenceAcquisition(0.0);
liveModeTimerTask_ = new LiveModeTimerTask();
liveModeTimer_.schedule(liveModeTimerTask_, (long) 0, (long) liveModeInterval_ );
// Only hide the shutter checkbox if we are in autoshuttermode
buttonSnap_.setEnabled(false);
if (autoShutterOrg_) {
toggleButtonShutter_.setEnabled(false);
}
if (core_.getNumberOfCameraChannels() == 1)
imageWin_.setSubTitle("Live (running)");
liveRunning_ = true;
} catch (Exception err) {
ReportingUtils.showError(err, "Failed to enable live mode.");
if (imageWin_ != null) {
imageWin_.saveAttributes();
WindowManager.removeWindow(imageWin_);
imageWin_.dispose();
imageWin_ = null;
}
}
} else {
if (!isLiveModeOn()) {
return;
}
try {
liveModeTimerTask_.cancel();
core_.stopSequenceAcquisition();
if (zWheelListener_ != null) {
zWheelListener_.stop();
}
if (xyzKeyListener_ != null) {
xyzKeyListener_.stop();
}
// restore auto shutter and close the shutter
if (shutterLabel_.length() > 0) {
core_.setShutterOpen(shutterOrg_);
}
core_.setAutoShutter(autoShutterOrg_);
if (autoShutterOrg_) {
toggleButtonShutter_.setEnabled(false);
} else {
toggleButtonShutter_.setEnabled(true);
}
liveRunning_ = false;
buttonSnap_.setEnabled(true);
autoShutterCheckBox_.setEnabled(true);
// TODO: add timeout so that we can not hang here
while (liveModeTimerTask_.isRunning()); // Make sure Timer properly stops.
// This is here to avoid crashes when changing ROI in live mode
// with Sensicam
// Should be removed when underlying problem is dealt with
Thread.sleep(100);
if (!multiChannelCamera_)
imageWin_.setSubTitle("Live (stopped)");
liveModeTimerTask_ = null;
} catch (Exception err) {
ReportingUtils.showError(err, "Failed to disable live mode.");
if (imageWin_ != null) {
WindowManager.removeWindow(imageWin_);
imageWin_.dispose();
imageWin_ = null;
}
}
}
} else {
buttonSnap_.setEnabled(!enable);
autoShutterCheckBox_.setEnabled(!enable);
Pipeline p = getPipeline();
if (p != null)
p.enableLiveMode(enable);
liveRunning_ = enable;
}
toggleButtonLive_.setIcon(liveRunning_ ? SwingResourceManager.getIcon(MMStudioMainFrame.class,
"/org/micromanager/icons/cancel.png")
: SwingResourceManager.getIcon(MMStudioMainFrame.class,
"/org/micromanager/icons/camera_go.png"));
toggleButtonLive_.setSelected(liveRunning_);
toggleButtonLive_.setText(liveRunning_ ? "Stop Live" : "Live");
}
public boolean getLiveMode() {
return liveRunning_;
}
public boolean updateImage() {
try {
if (isLiveModeOn()) {
enableLiveMode(false);
return true; // nothing to do, just show the last image
}
if (!isImageWindowOpen()) {
createImageWindow();
}
core_.snapImage();
Object img;
img = core_.getImage();
if (imageWin_.windowNeedsResizing()) {
createImageWindow();
}
if (!isCurrentImageFormatSupported()) {
return false;
}
imageWin_.newImage(img);
updateLineProfile();
} catch (Exception e) {
ReportingUtils.showError(e);
return false;
}
return true;
}
public boolean displayImage(Object pixels) {
try {
if (core_.getNumberOfCameraChannels() > 1)
checkMultiChannelWindow();
else {
if (!isImageWindowOpen() || imageWin_.windowNeedsResizing()
&& creatingImageWindow_.isFalse()) {
createImageWindow();
}
imageWin_.newImage(pixels);
updateLineProfile();
}
} catch (Exception e) {
ReportingUtils.logError(e);
return false;
}
return true;
}
public boolean displayImageWithStatusLine(Object pixels, String statusLine) {
try {
if (!isImageWindowOpen() || imageWin_.windowNeedsResizing()
&& creatingImageWindow_.isFalse()) {
createImageWindow();
}
imageWin_.newImageWithStatusLine(pixels, statusLine);
updateLineProfile();
} catch (Exception e) {
ReportingUtils.logError(e);
return false;
}
return true;
}
public void displayStatusLine(String statusLine) {
try {
if (isImageWindowOpen()) {
imageWin_.displayStatusLine(statusLine);
}
} catch (Exception e) {
ReportingUtils.logError(e);
return;
}
}
private boolean isCurrentImageFormatSupported() {
boolean ret = false;
long channels = core_.getNumberOfComponents();
long bpp = core_.getBytesPerPixel();
if (channels > 1 && channels != 4 && bpp != 1) {
handleError("Unsupported image format.");
} else {
ret = true;
}
return ret;
}
private void doSnap() {
if (core_.getNumberOfComponents() == 1) {
if(4 == core_.getBytesPerPixel()) {
doSnapFloat();
} else {
if (core_.getNumberOfCameraChannels() > 1)
{
doSnapMultiChannel();
} else {
doSnapMonochrome();
}
}
} else {
doSnapColor();
}
}
public void initializeGUI() {
try {
// establish device roles
cameraLabel_ = core_.getCameraDevice();
shutterLabel_ = core_.getShutterDevice();
zStageLabel_ = core_.getFocusDevice();
xyStageLabel_ = core_.getXYStageDevice();
engine_.setZStageDevice(zStageLabel_);
if (cameraLabel_.length() > 0) {
ActionListener[] listeners;
// binning combo
if (comboBinning_.getItemCount() > 0) {
comboBinning_.removeAllItems();
}
StrVector binSizes = core_.getAllowedPropertyValues(
cameraLabel_, MMCoreJ.getG_Keyword_Binning());
listeners = comboBinning_.getActionListeners();
for (int i = 0; i < listeners.length; i++) {
comboBinning_.removeActionListener(listeners[i]);
}
for (int i = 0; i < binSizes.size(); i++) {
comboBinning_.addItem(binSizes.get(i));
}
comboBinning_.setMaximumRowCount((int) binSizes.size());
if (binSizes.size() == 0) {
comboBinning_.setEditable(true);
} else {
comboBinning_.setEditable(false);
}
for (int i = 0; i < listeners.length; i++) {
comboBinning_.addActionListener(listeners[i]);
}
}
// active shutter combo
try {
shutters_ = core_.getLoadedDevicesOfType(DeviceType.ShutterDevice);
} catch (Exception e) {
ReportingUtils.logError(e);
}
if (shutters_ != null) {
String items[] = new String[(int) shutters_.size()];
for (int i = 0; i < shutters_.size(); i++) {
items[i] = shutters_.get(i);
}
GUIUtils.replaceComboContents(shutterComboBox_, items);
String activeShutter = core_.getShutterDevice();
if (activeShutter != null) {
shutterComboBox_.setSelectedItem(activeShutter);
} else {
shutterComboBox_.setSelectedItem("");
}
}
// Autofocus
buttonAutofocusTools_.setEnabled(afMgr_.getDevice() != null);
buttonAutofocus_.setEnabled(afMgr_.getDevice() != null);
// Rebuild stage list in XY PositinList
if (posListDlg_ != null) {
posListDlg_.rebuildAxisList();
}
// Mouse moves stage
centerAndDragListener_ = new CenterAndDragListener(core_, gui_);
if (centerAndDragMenuItem_.isSelected()) {
centerAndDragListener_.start();
}
updateGUI(true);
} catch (Exception e) {
ReportingUtils.showError(e);
}
}
public String getVersion() {
return VERSION;
}
private void addPluginToMenu(final PluginItem plugin, Class<?> cl) {
// add plugin menu items
final JMenuItem newMenuItem = new JMenuItem();
newMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
ReportingUtils.logMessage("Plugin command: "
+ e.getActionCommand());
plugin.instantiate();
plugin.plugin.show();
}
});
newMenuItem.setText(plugin.menuItem);
String toolTipDescription = "";
try {
// Get this static field from the class implementing MMPlugin.
toolTipDescription = (String) cl.getDeclaredField("tooltipDescription").get(null);
} catch (SecurityException e) {
ReportingUtils.logError(e);
toolTipDescription = "Description not available";
} catch (NoSuchFieldException e) {
toolTipDescription = "Description not available";
ReportingUtils.logError(cl.getName() + " fails to implement static String tooltipDescription.");
} catch (IllegalArgumentException e) {
ReportingUtils.logError(e);
} catch (IllegalAccessException e) {
ReportingUtils.logError(e);
}
String mrjProp = System.getProperty("mrj.version");
if (mrjProp != null && !mrjProp.equals(null)) // running on a mac
newMenuItem.setToolTipText(toolTipDescription);
else
newMenuItem.setToolTipText( TooltipTextMaker.addHTMLBreaksForTooltip(toolTipDescription) );
pluginMenu_.add(newMenuItem);
pluginMenu_.validate();
menuBar_.validate();
}
public void updateGUI(boolean updateConfigPadStructure) {
try {
// establish device roles
cameraLabel_ = core_.getCameraDevice();
shutterLabel_ = core_.getShutterDevice();
zStageLabel_ = core_.getFocusDevice();
xyStageLabel_ = core_.getXYStageDevice();
afMgr_.refresh();
// camera settings
if (isCameraAvailable()) {
double exp = core_.getExposure();
textFieldExp_.setText(NumberUtils.doubleToDisplayString(exp));
String binSize = core_.getProperty(cameraLabel_, MMCoreJ.getG_Keyword_Binning());
GUIUtils.setComboSelection(comboBinning_, binSize);
long bitDepth = 8;
if (imageWin_ != null) {
long hsz = imageWin_.getRawHistogramSize();
bitDepth = (long) Math.log(hsz);
}
bitDepth = core_.getImageBitDepth();
contrastPanel_.setPixelBitDepth((int) bitDepth, false);
}
if (liveModeTimerTask_ == null || !liveModeTimerTask_.isRunning()) {
autoShutterCheckBox_.setSelected(core_.getAutoShutter());
boolean shutterOpen = core_.getShutterOpen();
setShutterButton(shutterOpen);
if (autoShutterCheckBox_.isSelected()) {
toggleButtonShutter_.setEnabled(false);
} else {
toggleButtonShutter_.setEnabled(true);
}
autoShutterOrg_ = core_.getAutoShutter();
}
// active shutter combo
if (shutters_ != null) {
String activeShutter = core_.getShutterDevice();
if (activeShutter != null) {
shutterComboBox_.setSelectedItem(activeShutter);
} else {
shutterComboBox_.setSelectedItem("");
}
}
// state devices
if (updateConfigPadStructure && (configPad_ != null)) {
configPad_.refreshStructure();
}
// update Channel menus in Multi-dimensional acquisition dialog
updateChannelCombos();
// Needed to update read-only properties. May slow things down...
core_.updateSystemStateCache();
} catch (Exception e) {
ReportingUtils.logError(e);
}
updateStaticInfo();
updateTitle();
}
public boolean okToAcquire() {
return !isLiveModeOn();
}
public void stopAllActivity() {
enableLiveMode(false);
}
public void refreshImage() {
if (imageWin_ != null) {
imageWin_.getImagePlus().updateAndDraw();
}
}
private void cleanupOnClose() {
// NS: Save config presets if they were changed.
if (configChanged_) {
Object[] options = {"Yes", "No"};
int n = JOptionPane.showOptionDialog(null,
"Save Changed Configuration?", "Micro-Manager",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,
null, options, options[0]);
if (n == JOptionPane.YES_OPTION) {
saveConfigPresets();
}
}
if (liveModeTimerTask_ != null)
liveModeTimerTask_.cancel();
try{
if (imageWin_ != null) {
if (!imageWin_.isClosed())
imageWin_.close();
imageWin_.dispose();
imageWin_ = null;
}
}
catch( Throwable t){
ReportingUtils.logError(t, "closing ImageWin_");
}
if (profileWin_ != null) {
removeMMBackgroundListener(profileWin_);
profileWin_.dispose();
}
if (scriptPanel_ != null) {
removeMMBackgroundListener(scriptPanel_);
scriptPanel_.closePanel();
}
if (propertyBrowser_ != null) {
removeMMBackgroundListener(propertyBrowser_);
propertyBrowser_.dispose();
}
if (acqControlWin_ != null) {
removeMMBackgroundListener(acqControlWin_);
acqControlWin_.close();
}
if (engine_ != null) {
engine_.shutdown();
}
if (afMgr_ != null) {
afMgr_.closeOptionsDialog();
}
// dispose plugins
for (int i = 0; i < plugins_.size(); i++) {
MMPlugin plugin = (MMPlugin) plugins_.get(i).plugin;
if (plugin != null) {
plugin.dispose();
}
}
synchronized (shutdownLock_) {
try {
if (core_ != null){
core_.delete();
core_ = null;
}
} catch (Exception err) {
ReportingUtils.showError(err);
}
}
}
private void saveSettings() {
Rectangle r = this.getBounds();
mainPrefs_.putInt(MAIN_FRAME_X, r.x);
mainPrefs_.putInt(MAIN_FRAME_Y, r.y);
mainPrefs_.putInt(MAIN_FRAME_WIDTH, r.width);
mainPrefs_.putInt(MAIN_FRAME_HEIGHT, r.height);
mainPrefs_.putInt(MAIN_FRAME_DIVIDER_POS, this.splitPane_.getDividerLocation());
mainPrefs_.putBoolean(MAIN_STRETCH_CONTRAST, contrastPanel_.isContrastStretch());
mainPrefs_.putBoolean(MAIN_REJECT_OUTLIERS, contrastPanel_.isRejectOutliers());
mainPrefs_.putDouble(MAIN_REJECT_FRACTION, contrastPanel_.getFractionToReject());
mainPrefs_.put(OPEN_ACQ_DIR, openAcqDirectory_);
// save field values from the main window
// NOTE: automatically restoring these values on startup may cause
// problems
mainPrefs_.put(MAIN_EXPOSURE, textFieldExp_.getText());
// NOTE: do not save auto shutter state
if (afMgr_ != null && afMgr_.getDevice() != null) {
mainPrefs_.put(AUTOFOCUS_DEVICE, afMgr_.getDevice().getDeviceName());
}
}
private void loadConfiguration() {
File f = FileDialogs.openFile(this, "Load a config file",MM_CONFIG_FILE);
if (f != null) {
sysConfigFile_ = f.getAbsolutePath();
configChanged_ = false;
setConfigSaveButtonStatus(configChanged_);
mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_);
loadSystemConfiguration();
}
}
private void loadSystemState() {
File f = FileDialogs.openFile(this, "Load a system state file", MM_CONFIG_FILE);
if (f != null) {
sysStateFile_ = f.getAbsolutePath();
try {
// WaitDialog waitDlg = new
// WaitDialog("Loading saved state, please wait...");
// waitDlg.showDialog();
core_.loadSystemState(sysStateFile_);
GUIUtils.preventDisplayAdapterChangeExceptions();
// waitDlg.closeDialog();
initializeGUI();
} catch (Exception e) {
ReportingUtils.showError(e);
return;
}
}
}
private void saveSystemState() {
File f = FileDialogs.save(this,
"Save the system state to a config file", MM_CONFIG_FILE);
if (f != null) {
sysStateFile_ = f.getAbsolutePath();
try {
core_.saveSystemState(sysStateFile_);
} catch (Exception e) {
ReportingUtils.showError(e);
return;
}
}
}
public void closeSequence() {
if (!this.isRunning())
return;
if (engine_ != null && engine_.isAcquisitionRunning()) {
int result = JOptionPane.showConfirmDialog(
this,
"Acquisition in progress. Are you sure you want to exit and discard all data?",
"Micro-Manager", JOptionPane.YES_NO_OPTION,
JOptionPane.INFORMATION_MESSAGE);
if (result == JOptionPane.NO_OPTION) {
return;
}
}
stopAllActivity();
cleanupOnClose();
saveSettings();
try {
configPad_.saveSettings();
options_.saveSettings();
hotKeys_.saveSettings();
} catch (NullPointerException e) {
if (core_ != null)
this.logError(e);
}
this.dispose();
if (options_.closeOnExit_) {
if (!runsAsPlugin_) {
System.exit(0);
} else {
ImageJ ij = IJ.getInstance();
if (ij != null) {
ij.quit();
}
}
}
}
public void applyContrastSettings(ContrastSettings contrast8,
ContrastSettings contrast16) {
contrastPanel_.applyContrastSettings(contrast8, contrast16);
}
public ContrastSettings getContrastSettings() {
return contrastPanel_.getContrastSettings();
}
public boolean is16bit() {
if (isImageWindowOpen()
&& imageWin_.getImagePlus().getProcessor() instanceof ShortProcessor) {
return true;
}
return false;
}
public boolean isRunning() {
return running_;
}
/**
* Executes the beanShell script. This script instance only supports
* commands directed to the core object.
*/
private void executeStartupScript() {
// execute startup script
File f = new File(startupScriptFile_);
if (startupScriptFile_.length() > 0 && f.exists()) {
WaitDialog waitDlg = new WaitDialog(
"Executing startup script, please wait...");
waitDlg.showDialog();
Interpreter interp = new Interpreter();
try {
// insert core object only
interp.set(SCRIPT_CORE_OBJECT, core_);
interp.set(SCRIPT_ACQENG_OBJECT, engine_);
interp.set(SCRIPT_GUI_OBJECT, this);
// read text file and evaluate
interp.eval(TextUtils.readTextFile(startupScriptFile_));
} catch (IOException exc) {
ReportingUtils.showError(exc, "Unable to read the startup script (" + startupScriptFile_ + ").");
} catch (EvalError exc) {
ReportingUtils.showError(exc);
} finally {
waitDlg.closeDialog();
}
} else {
if (startupScriptFile_.length() > 0)
ReportingUtils.logMessage("Startup script file ("+startupScriptFile_+") not present.");
}
}
/**
* Loads sytem configuration from the cfg file.
*/
private boolean loadSystemConfiguration() {
boolean result = true;
saveMRUConfigFiles();
final WaitDialog waitDlg = new WaitDialog(
"Loading system configuration, please wait...");
waitDlg.setAlwaysOnTop(true);
waitDlg.showDialog();
this.setEnabled(false);
try {
if (sysConfigFile_.length() > 0) {
GUIUtils.preventDisplayAdapterChangeExceptions();
core_.waitForSystem();
core_.loadSystemConfiguration(sysConfigFile_);
GUIUtils.preventDisplayAdapterChangeExceptions();
waitDlg.closeDialog();
} else {
waitDlg.closeDialog();
}
} catch (final Exception err) {
GUIUtils.preventDisplayAdapterChangeExceptions();
waitDlg.closeDialog();
ReportingUtils.showError(err);
result = false;
}
this.setEnabled(true);
this.initializeGUI();
updateSwitchConfigurationMenu();
FileDialogs.storePath(MM_CONFIG_FILE, new File(sysConfigFile_));
return result;
}
private void saveMRUConfigFiles() {
if (0 < sysConfigFile_.length()) {
if (MRUConfigFiles_.contains(sysConfigFile_)) {
MRUConfigFiles_.remove(sysConfigFile_);
}
if (maxMRUCfgs_ <= MRUConfigFiles_.size()) {
MRUConfigFiles_.remove(maxMRUCfgs_ - 1);
}
MRUConfigFiles_.add(0, sysConfigFile_);
// save the MRU list to the preferences
for (Integer icfg = 0; icfg < MRUConfigFiles_.size(); ++icfg) {
String value = "";
if (null != MRUConfigFiles_.get(icfg)) {
value = MRUConfigFiles_.get(icfg).toString();
}
mainPrefs_.put(CFGFILE_ENTRY_BASE + icfg.toString(), value);
}
}
}
private void loadMRUConfigFiles() {
sysConfigFile_ = mainPrefs_.get(SYSTEM_CONFIG_FILE, sysConfigFile_);
// startupScriptFile_ = mainPrefs_.get(STARTUP_SCRIPT_FILE,
// startupScriptFile_);
MRUConfigFiles_ = new ArrayList<String>();
for (Integer icfg = 0; icfg < maxMRUCfgs_; ++icfg) {
String value = "";
value = mainPrefs_.get(CFGFILE_ENTRY_BASE + icfg.toString(), value);
if (0 < value.length()) {
File ruFile = new File(value);
if (ruFile.exists()) {
if (!MRUConfigFiles_.contains(value)) {
MRUConfigFiles_.add(value);
}
}
}
}
// initialize MRU list from old persistant data containing only SYSTEM_CONFIG_FILE
if (0 < sysConfigFile_.length()) {
if (!MRUConfigFiles_.contains(sysConfigFile_)) {
// in case persistant data is inconsistent
if (maxMRUCfgs_ <= MRUConfigFiles_.size()) {
MRUConfigFiles_.remove(maxMRUCfgs_ - 1);
}
MRUConfigFiles_.add(0, sysConfigFile_);
}
}
}
/**
* Opens Acquisition dialog.
*/
private void openAcqControlDialog() {
try {
if (acqControlWin_ == null) {
acqControlWin_ = new AcqControlDlg(engine_, mainPrefs_, this);
}
if (acqControlWin_.isActive()) {
acqControlWin_.setTopPosition();
}
acqControlWin_.setVisible(true);
// TODO: this call causes a strange exception the first time the
// dialog is created
// something to do with the order in which combo box creation is
// performed
// acqControlWin_.updateGroupsCombo();
} catch (Exception exc) {
ReportingUtils.showError(exc,
"\nAcquistion window failed to open due to invalid or corrupted settings.\n"
+ "Try resetting registry settings to factory defaults (Menu Tools|Options).");
}
}
* /** Opens a dialog to record stage positions
*/
@Override
public void showXYPositionList() {
if (posListDlg_ == null) {
posListDlg_ = new PositionListDlg(core_, this, posList_, options_);
}
posListDlg_.setVisible(true);
}
private void updateChannelCombos() {
if (this.acqControlWin_ != null) {
this.acqControlWin_.updateChannelAndGroupCombo();
}
}
@Override
public void setConfigChanged(boolean status) {
configChanged_ = status;
setConfigSaveButtonStatus(configChanged_);
}
/**
* Returns the current background color
* @return
*/
@Override
public Color getBackgroundColor() {
return guiColors_.background.get((options_.displayBackground_));
}
/*
* Changes background color of this window and all other MM windows
*/
@Override
public void setBackgroundStyle(String backgroundType) {
setBackground(guiColors_.background.get((backgroundType)));
paint(MMStudioMainFrame.this.getGraphics());
// sets background of all registered Components
for (Component comp:MMFrames_) {
if (comp != null)
comp.setBackground(guiColors_.background.get(backgroundType));
}
}
@Override
public String getBackgroundStyle() {
return options_.displayBackground_;
}
// Set ImageJ pixel calibration
private void setIJCal(MMImageWindow imageWin) {
if (imageWin != null) {
imageWin.setIJCal();
}
}
// Scripting interface
private class ExecuteAcq implements Runnable {
public ExecuteAcq() {
}
@Override
public void run() {
if (acqControlWin_ != null) {
acqControlWin_.runAcquisition();
}
}
}
private class LoadAcq implements Runnable {
private String filePath_;
public LoadAcq(String path) {
filePath_ = path;
}
@Override
public void run() {
// stop current acquisition if any
engine_.shutdown();
// load protocol
if (acqControlWin_ != null) {
acqControlWin_.loadAcqSettingsFromFile(filePath_);
}
}
}
private void testForAbortRequests() throws MMScriptException {
if (scriptPanel_ != null) {
if (scriptPanel_.stopRequestPending()) {
throw new MMScriptException("Script interrupted by the user!");
}
}
}
@Override
public void startAcquisition() throws MMScriptException {
testForAbortRequests();
SwingUtilities.invokeLater(new ExecuteAcq());
}
@Override
public void runAcquisition() throws MMScriptException {
testForAbortRequests();
if (acqControlWin_ != null) {
acqControlWin_.runAcquisition();
try {
while (acqControlWin_.isAcquisitionRunning()) {
Thread.sleep(50);
}
} catch (InterruptedException e) {
ReportingUtils.showError(e);
}
} else {
throw new MMScriptException(
"Acquisition window must be open for this command to work.");
}
}
@Override
public void runAcquisition(String name, String root)
throws MMScriptException {
testForAbortRequests();
if (acqControlWin_ != null) {
acqControlWin_.runAcquisition(name, root);
try {
while (acqControlWin_.isAcquisitionRunning()) {
Thread.sleep(100);
}
} catch (InterruptedException e) {
ReportingUtils.showError(e);
}
} else {
throw new MMScriptException(
"Acquisition window must be open for this command to work.");
}
}
@Override
public void runAcqusition(String name, String root) throws MMScriptException {
runAcquisition(name, root);
}
@Override
public void loadAcquisition(String path) throws MMScriptException {
testForAbortRequests();
SwingUtilities.invokeLater(new LoadAcq(path));
}
@Override
public void setPositionList(PositionList pl) throws MMScriptException {
testForAbortRequests();
// use serialization to clone the PositionList object
posList_ = pl; // PositionList.newInstance(pl);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (posListDlg_ != null) {
posListDlg_.setPositionList(posList_);
engine_.setPositionList(posList_);
}
}
});
}
@Override
public PositionList getPositionList() throws MMScriptException {
testForAbortRequests();
// use serialization to clone the PositionList object
return posList_; //PositionList.newInstance(posList_);
}
@Override
public void sleep(long ms) throws MMScriptException {
if (scriptPanel_ != null) {
if (scriptPanel_.stopRequestPending()) {
throw new MMScriptException("Script interrupted by the user!");
}
scriptPanel_.sleep(ms);
}
}
@Override
public String getUniqueAcquisitionName(String stub) {
return acqMgr_.getUniqueAcquisitionName(stub);
}
// TODO:
@Override
public MMAcquisition getCurrentAcquisition() {
return null; // if none available
}
public void openAcquisition(String name, String rootDir) throws MMScriptException {
openAcquisition(name, rootDir, true);
}
public void openAcquisition(String name, String rootDir, boolean show) throws MMScriptException {
//acqMgr_.openAcquisition(name, rootDir, show);
TaggedImageStorage imageFileManager = new TaggedImageStorageDiskDefault((new File(rootDir, name)).getAbsolutePath());
MMImageCache cache = new MMImageCache(imageFileManager);
VirtualAcquisitionDisplay display = new VirtualAcquisitionDisplay(cache, null);
display.show();
}
@Override
public void openAcquisition(String name, String rootDir, int nrFrames,
int nrChannels, int nrSlices, int nrPositions) throws MMScriptException {
this.openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices,
nrPositions, true, false);
}
@Override
public void openAcquisition(String name, String rootDir, int nrFrames,
int nrChannels, int nrSlices) throws MMScriptException {
openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, 0);
}
@Override
public void openAcquisition(String name, String rootDir, int nrFrames,
int nrChannels, int nrSlices, int nrPositions, boolean show)
throws MMScriptException {
this.openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, nrPositions, show, false);
}
@Override
public void openAcquisition(String name, String rootDir, int nrFrames,
int nrChannels, int nrSlices, boolean show)
throws MMScriptException {
this.openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, 0, show, false);
}
@Override
public void openAcquisition(String name, String rootDir, int nrFrames,
int nrChannels, int nrSlices, int nrPositions, boolean show, boolean virtual)
throws MMScriptException {
acqMgr_.openAcquisition(name, rootDir, show, virtual);
MMAcquisition acq = acqMgr_.getAcquisition(name);
acq.setDimensions(nrFrames, nrChannels, nrSlices, nrPositions);
}
@Override
public void openAcquisition(String name, String rootDir, int nrFrames,
int nrChannels, int nrSlices, boolean show, boolean virtual)
throws MMScriptException {
this.openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, 0, show, virtual);
}
private void openAcquisitionSnap(String name, String rootDir, boolean show)
throws MMScriptException {
/*
MMAcquisition acq = acqMgr_.openAcquisitionSnap(name, rootDir, this,
show);
acq.setDimensions(0, 1, 1, 1);
try {
// acq.getAcqData().setPixelSizeUm(core_.getPixelSizeUm());
acq.setProperty(SummaryKeys.IMAGE_PIXEL_SIZE_UM, String.valueOf(core_.getPixelSizeUm()));
} catch (Exception e) {
ReportingUtils.showError(e);
}
*
*/
}
@Override
public void initializeAcquisition(String name, int width, int height,
int depth) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(name);
acq.setImagePhysicalDimensions(width, height, depth);
acq.initialize();
}
@Override
public int getAcquisitionImageWidth(String acqName) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(acqName);
return acq.getWidth();
}
@Override
public int getAcquisitionImageHeight(String acqName) throws MMScriptException{
MMAcquisition acq = acqMgr_.getAcquisition(acqName);
return acq.getHeight();
}
@Override
public int getAcquisitionImageByteDepth(String acqName) throws MMScriptException{
MMAcquisition acq = acqMgr_.getAcquisition(acqName);
return acq.getDepth();
}
@Override
public Boolean acquisitionExists(String name) {
return acqMgr_.acquisitionExists(name);
}
@Override
public void closeAcquisition(String name) throws MMScriptException {
acqMgr_.closeAcquisition(name);
}
@Override
public void closeAcquisitionImage5D(String title) throws MMScriptException {
acqMgr_.closeImage5D(title);
}
/**
* Since Burst and normal acquisition are now carried out by the same engine,
* loadBurstAcquistion simply calls loadAcquisition
* t
* @param path - path to file specifying acquisition settings
*/
@Override
public void loadBurstAcquisition(String path) throws MMScriptException {
this.loadAcquisition(path);
}
@Override
public void refreshGUI() {
updateGUI(true);
}
public void setAcquisitionProperty(String acqName, String propertyName,
String value) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(acqName);
acq.setProperty(propertyName, value);
}
public void setAcquisitionSystemState(String acqName, JSONObject md) throws MMScriptException {
acqMgr_.getAcquisition(acqName).setSystemState(md);
}
public void setAcquisitionSummary(String acqName, JSONObject md) throws MMScriptException {
acqMgr_.getAcquisition(acqName).setSummaryProperties(md);
}
public void setImageProperty(String acqName, int frame, int channel,
int slice, String propName, String value) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(acqName);
acq.setProperty(frame, channel, slice, propName, value);
}
public void snapAndAddImage(String name, int frame, int channel, int slice)
throws MMScriptException {
snapAndAddImage(name, frame, channel, slice, 0);
}
public void snapAndAddImage(String name, int frame, int channel, int slice, int position)
throws MMScriptException {
Metadata md = new Metadata();
try {
Object img;
if (core_.isSequenceRunning()) {
img = core_.getLastImage();
core_.getLastImageMD(0, 0, md);
} else {
core_.snapImage();
img = core_.getImage();
}
MMAcquisition acq = acqMgr_.getAcquisition(name);
long width = core_.getImageWidth();
long height = core_.getImageHeight();
long depth = core_.getBytesPerPixel();
if (!acq.isInitialized()) {
acq.setImagePhysicalDimensions((int) width, (int) height,
(int) depth);
acq.initialize();
}
acq.insertImage(img, frame, channel, slice, position);
// Insert exposure in metadata
// acq.setProperty(frame, channel, slice, ImagePropertyKeys.EXPOSURE_MS, NumberUtils.doubleToDisplayString(core_.getExposure()));
// Add pixel size calibration
/*
double pixSizeUm = core_.getPixelSizeUm();
if (pixSizeUm > 0) {
acq.setProperty(frame, channel, slice, ImagePropertyKeys.X_UM, NumberUtils.doubleToDisplayString(pixSizeUm));
acq.setProperty(frame, channel, slice, ImagePropertyKeys.Y_UM, NumberUtils.doubleToDisplayString(pixSizeUm));
}
// generate list with system state
JSONObject state = Annotator.generateJSONMetadata(core_.getSystemStateCache());
// and insert into metadata
acq.setSystemState(frame, channel, slice, state);
*/
} catch (Exception e) {
ReportingUtils.showError(e);
}
}
public void addToSnapSeries(Object img, String acqName) {
try {
acqMgr_.getCurrentAlbum();
if (acqName == null) {
acqName = "Snap" + snapCount_;
}
Boolean newSnap = false;
core_.setExposure(NumberUtils.displayStringToDouble(textFieldExp_.getText()));
long width = core_.getImageWidth();
long height = core_.getImageHeight();
long depth = core_.getBytesPerPixel();
//MMAcquisitionSnap acq = null;
if (! acqMgr_.hasActiveImage5D(acqName)) {
newSnap = true;
}
if (newSnap) {
snapCount_++;
acqName = "Snap" + snapCount_;
this.openAcquisitionSnap(acqName, null, true); // (dir=null) ->
// keep in
// memory; don't
// save to file.
initializeAcquisition(acqName, (int) width, (int) height,
(int) depth);
}
setChannelColor(acqName, 0, Color.WHITE);
setChannelName(acqName, 0, "Snap");
// acq = (MMAcquisitionSnap) acqMgr_.getAcquisition(acqName);
// acq.appendImage(img);
// add exposure to metadata
// acq.setProperty(acq.getFrames() - 1, acq.getChannels() - 1, acq.getSlices() - 1, ImagePropertyKeys.EXPOSURE_MS, NumberUtils.doubleToDisplayString(core_.getExposure()));
// Add pixel size calibration
double pixSizeUm = core_.getPixelSizeUm();
if (pixSizeUm > 0) {
// acq.setProperty(acq.getFrames() - 1, acq.getChannels() - 1, acq.getSlices() - 1, ImagePropertyKeys.X_UM, NumberUtils.doubleToDisplayString(pixSizeUm));
// acq.setProperty(acq.getFrames() - 1, acq.getChannels() - 1, acq.getSlices() - 1, ImagePropertyKeys.Y_UM, NumberUtils.doubleToDisplayString(pixSizeUm));
}
// generate list with system state
// JSONObject state = Annotator.generateJSONMetadata(core_.getSystemStateCache());
// and insert into metadata
// acq.setSystemState(acq.getFrames() - 1, acq.getChannels() - 1, acq.getSlices() - 1, state);
// closeAcquisition(acqName);
} catch (Exception e) {
ReportingUtils.showError(e);
}
}
public String getCurrentAlbum() {
return acqMgr_.getCurrentAlbum();
}
public String createNewAlbum() {
return acqMgr_.createNewAlbum();
}
public void appendImage(String name, TaggedImage taggedImg) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(name);
int f = 1 + acq.getLastAcquiredFrame();
try {
MDUtils.setFrameIndex(taggedImg.tags, f);
} catch (JSONException e) {
throw new MMScriptException("Unable to set the frame index.");
}
acq.insertTaggedImage(taggedImg, f, 0, 0);
}
public void addToAlbum(TaggedImage taggedImg) throws MMScriptException {
acqMgr_.addToAlbum(taggedImg);
}
public void addImage(String name, Object img, int frame, int channel,
int slice) throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(name);
acq.insertImage(img, frame, channel, slice);
}
public void addImage(String name, TaggedImage taggedImg) throws MMScriptException {
acqMgr_.getAcquisition(name).insertImage(taggedImg);
}
public void addImage(String name, TaggedImage taggedImg, boolean updateDisplay) throws MMScriptException {
acqMgr_.getAcquisition(name).insertImage(taggedImg, updateDisplay);
}
public void closeAllAcquisitions() {
acqMgr_.closeAll();
}
public String[] getAcquisitionNames()
{
return acqMgr_.getAcqusitionNames();
}
public MMAcquisition getAcquisition(String name) throws MMScriptException {
return acqMgr_.getAcquisition(name);
}
private class ScriptConsoleMessage implements Runnable {
String msg_;
public ScriptConsoleMessage(String text) {
msg_ = text;
}
public void run() {
if (scriptPanel_ != null)
scriptPanel_.message(msg_);
}
}
public void message(String text) throws MMScriptException {
if (scriptPanel_ != null) {
if (scriptPanel_.stopRequestPending()) {
throw new MMScriptException("Script interrupted by the user!");
}
SwingUtilities.invokeLater(new ScriptConsoleMessage(text));
}
}
public void clearMessageWindow() throws MMScriptException {
if (scriptPanel_ != null) {
if (scriptPanel_.stopRequestPending()) {
throw new MMScriptException("Script interrupted by the user!");
}
scriptPanel_.clearOutput();
}
}
public void clearOutput() throws MMScriptException {
clearMessageWindow();
}
public void clear() throws MMScriptException {
clearMessageWindow();
}
public void setChannelContrast(String title, int channel, int min, int max)
throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(title);
acq.setChannelContrast(channel, min, max);
}
public void setChannelName(String title, int channel, String name)
throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(title);
acq.setChannelName(channel, name);
}
public void setChannelColor(String title, int channel, Color color)
throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(title);
acq.setChannelColor(channel, color.getRGB());
}
public void setContrastBasedOnFrame(String title, int frame, int slice)
throws MMScriptException {
MMAcquisition acq = acqMgr_.getAcquisition(title);
acq.setContrastBasedOnFrame(frame, slice);
}
public void setStagePosition(double z) throws MMScriptException {
try {
core_.setPosition(core_.getFocusDevice(),z);
core_.waitForDevice(core_.getFocusDevice());
} catch (Exception e) {
throw new MMScriptException(e.getMessage());
}
}
public void setRelativeStagePosition(double z) throws MMScriptException {
try {
core_.setRelativePosition(core_.getFocusDevice(), z);
core_.waitForDevice(core_.getFocusDevice());
} catch (Exception e) {
throw new MMScriptException(e.getMessage());
}
}
public void setXYStagePosition(double x, double y) throws MMScriptException {
try {
core_.setXYPosition(core_.getXYStageDevice(), x, y);
core_.waitForDevice(core_.getXYStageDevice());
} catch (Exception e) {
throw new MMScriptException(e.getMessage());
}
}
public void setRelativeXYStagePosition(double x, double y) throws MMScriptException {
try {
core_.setRelativeXYPosition(core_.getXYStageDevice(), x, y);
core_.waitForDevice(core_.getXYStageDevice());
} catch (Exception e) {
throw new MMScriptException(e.getMessage());
}
}
public Point2D.Double getXYStagePosition() throws MMScriptException {
String stage = core_.getXYStageDevice();
if (stage.length() == 0) {
throw new MMScriptException("XY Stage device is not available");
}
double x[] = new double[1];
double y[] = new double[1];
try {
core_.getXYPosition(stage, x, y);
Point2D.Double pt = new Point2D.Double(x[0], y[0]);
return pt;
} catch (Exception e) {
throw new MMScriptException(e.getMessage());
}
}
public String getXYStageName() {
return core_.getXYStageDevice();
}
public void setXYOrigin(double x, double y) throws MMScriptException {
String xyStage = core_.getXYStageDevice();
try {
core_.setAdapterOriginXY(xyStage, x, y);
} catch (Exception e) {
throw new MMScriptException(e);
}
}
public AcquisitionEngine getAcquisitionEngine() {
return engine_;
}
public String installPlugin(Class<?> cl) {
String className = cl.getSimpleName();
String msg = className + " module loaded.";
try {
for (PluginItem plugin : plugins_) {
if (plugin.className.contentEquals(className)) {
return className + " already loaded.";
}
}
PluginItem pi = new PluginItem();
pi.className = className;
try {
// Get this static field from the class implementing MMPlugin.
pi.menuItem = (String) cl.getDeclaredField("menuName").get(null);
} catch (SecurityException e) {
ReportingUtils.logError(e);
pi.menuItem = className;
} catch (NoSuchFieldException e) {
pi.menuItem = className;
ReportingUtils.logError(className + " fails to implement static String menuName.");
} catch (IllegalArgumentException e) {
ReportingUtils.logError(e);
} catch (IllegalAccessException e) {
ReportingUtils.logError(e);
}
if (pi.menuItem == null) {
pi.menuItem = className;
//core_.logMessage(className + " fails to implement static String menuName.");
}
pi.menuItem = pi.menuItem.replace("_", " ");
pi.pluginClass = cl;
plugins_.add(pi);
final PluginItem pi2 = pi;
final Class<?> cl2 = cl;
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
addPluginToMenu(pi2, cl2);
}
});
} catch (NoClassDefFoundError e) {
msg = className + " class definition not found.";
ReportingUtils.logError(e, msg);
}
return msg;
}
public String installPlugin(String className, String menuName) {
String msg = "installPlugin(String className, String menuName) is deprecated. Use installPlugin(String className) instead.";
core_.logMessage(msg);
installPlugin(className);
return msg;
}
public String installPlugin(String className) {
String msg = "";
try {
Class clazz = Class.forName(className);
return installPlugin(clazz);
} catch (ClassNotFoundException e) {
msg = className + " plugin not found.";
ReportingUtils.logError(e, msg);
return msg;
}
}
public String installAutofocusPlugin(String className) {
try {
return installAutofocusPlugin(Class.forName(className));
} catch (ClassNotFoundException e) {
String msg = "Internal error: AF manager not instantiated.";
ReportingUtils.logError(e, msg);
return msg;
}
}
public String installAutofocusPlugin(Class<?> autofocus) {
String msg = autofocus.getSimpleName() + " module loaded.";
if (afMgr_ != null) {
try {
afMgr_.refresh();
} catch (MMException e) {
msg = e.getMessage();
ReportingUtils.logError(e);
}
afMgr_.setAFPluginClassName(autofocus.getSimpleName());
} else {
msg = "Internal error: AF manager not instantiated.";
}
return msg;
}
public CMMCore getCore() {
return core_;
}
public Pipeline getPipeline() {
try {
pipelineClassLoadingThread_.join();
if (acquirePipeline_ == null) {
acquirePipeline_ = (Pipeline) pipelineClass_.newInstance();
}
return acquirePipeline_;
} catch (Exception e) {
ReportingUtils.logError(e);
return null;
}
}
public void snapAndAddToImage5D() {
try {
getPipeline().acquireSingle();
} catch (Exception ex) {
ReportingUtils.logError(ex);
}
}
public void setAcquisitionEngine(AcquisitionEngine eng) {
engine_ = eng;
}
public void suspendLiveMode() {
liveModeSuspended_ = isLiveModeOn();
enableLiveMode(false);
}
public void resumeLiveMode() {
if (liveModeSuspended_) {
enableLiveMode(true);
}
}
public Autofocus getAutofocus() {
return afMgr_.getDevice();
}
public void showAutofocusDialog() {
if (afMgr_.getDevice() != null) {
afMgr_.showOptionsDialog();
}
}
public AutofocusManager getAutofocusManager() {
return afMgr_;
}
public void selectConfigGroup(String groupName) {
configPad_.setGroup(groupName);
}
public String regenerateDeviceList() {
Cursor oldc = Cursor.getDefaultCursor();
Cursor waitc = new Cursor(Cursor.WAIT_CURSOR);
setCursor(waitc);
StringBuffer resultFile = new StringBuffer();
MicroscopeModel.generateDeviceListFile(resultFile, core_);
//MicroscopeModel.generateDeviceListFile();
setCursor(oldc);
return resultFile.toString();
}
private void loadPlugins() {
afMgr_ = new AutofocusManager(this);
ArrayList<Class<?>> pluginClasses = new ArrayList<Class<?>>();
ArrayList<Class<?>> autofocusClasses = new ArrayList<Class<?>>();
List<Class<?>> classes;
try {
long t1 = System.currentTimeMillis();
classes = JavaUtils.findClasses(new File("mmplugins"), 2);
//System.out.println("findClasses: " + (System.currentTimeMillis() - t1));
//System.out.println(classes.size());
for (Class<?> clazz : classes) {
for (Class<?> iface : clazz.getInterfaces()) {
//core_.logMessage("interface found: " + iface.getName());
if (iface == MMPlugin.class) {
pluginClasses.add(clazz);
}
}
}
classes = JavaUtils.findClasses(new File("mmautofocus"), 2);
for (Class<?> clazz : classes) {
for (Class<?> iface : clazz.getInterfaces()) {
//core_.logMessage("interface found: " + iface.getName());
if (iface == Autofocus.class) {
autofocusClasses.add(clazz);
}
}
}
} catch (ClassNotFoundException e1) {
ReportingUtils.logError(e1);
}
for (Class<?> plugin : pluginClasses) {
try {
ReportingUtils.logMessage("Attempting to install plugin " + plugin.getName());
installPlugin(plugin);
} catch (Exception e) {
ReportingUtils.logError(e, "Failed to install the \"" + plugin.getName() + "\" plugin .");
}
}
for (Class<?> autofocus : autofocusClasses) {
try {
ReportingUtils.logMessage("Attempting to install autofocus plugin " + autofocus.getName());
installAutofocusPlugin(autofocus.getName());
} catch (Exception e) {
ReportingUtils.logError("Failed to install the \"" + autofocus.getName() + "\" autofocus plugin.");
}
}
}
private void setLiveModeInterval() {
double interval = 33.0;
try {
if (core_.getExposure() > 33.0) {
interval = core_.getExposure();
}
} catch (Exception ex) {
ReportingUtils.showError(ex);
}
liveModeInterval_ = interval;
//liveModeTimer_.setDelay((int) liveModeInterval_);
//liveModeTimer_.setInitialDelay(liveModeTimer_.getDelay());
}
public void logMessage(String msg) {
ReportingUtils.logMessage(msg);
}
public void showMessage(String msg) {
ReportingUtils.showMessage(msg);
}
public void logError(Exception e, String msg) {
ReportingUtils.logError(e, msg);
}
public void logError(Exception e) {
ReportingUtils.logError(e);
}
public void logError(String msg) {
ReportingUtils.logError(msg);
}
public void showError(Exception e, String msg) {
ReportingUtils.showError(e, msg);
}
public void showError(Exception e) {
ReportingUtils.showError(e);
}
public void showError(String msg) {
ReportingUtils.showError(msg);
}
}
class BooleanLock extends Object {
private boolean value;
public BooleanLock(boolean initialValue) {
value = initialValue;
}
public BooleanLock() {
this(false);
}
public synchronized void setValue(boolean newValue) {
if (newValue != value) {
value = newValue;
notifyAll();
}
}
public synchronized boolean waitToSetTrue(long msTimeout)
throws InterruptedException {
boolean success = waitUntilFalse(msTimeout);
if (success) {
setValue(true);
}
return success;
}
public synchronized boolean waitToSetFalse(long msTimeout)
throws InterruptedException {
boolean success = waitUntilTrue(msTimeout);
if (success) {
setValue(false);
}
return success;
}
public synchronized boolean isTrue() {
return value;
}
public synchronized boolean isFalse() {
return !value;
}
public synchronized boolean waitUntilTrue(long msTimeout)
throws InterruptedException {
return waitUntilStateIs(true, msTimeout);
}
public synchronized boolean waitUntilFalse(long msTimeout)
throws InterruptedException {
return waitUntilStateIs(false, msTimeout);
}
public synchronized boolean waitUntilStateIs(
boolean state,
long msTimeout) throws InterruptedException {
if (msTimeout == 0L) {
while (value != state) {
wait();
}
return true;
}
long endTime = System.currentTimeMillis() + msTimeout;
long msRemaining = msTimeout;
while ((value != state) && (msRemaining > 0L)) {
wait(msRemaining);
msRemaining = endTime - System.currentTimeMillis();
}
return (value == state);
}
}
|
package org.beanmaker.util;
import org.dbbeans.util.Strings;
import org.jcodegen.html.ButtonTag;
import org.jcodegen.html.InputTag;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HFHParameters {
// Base: inputs & textareas
private String field;
private long idBean = -1;
private String value;
private String fieldLabel;
private InputTag.InputType inputType;
private boolean required;
private boolean disabled;
private String placeholder;
private String helpText;
private boolean readonly;
private boolean autocomplete = true;
// selects
private String selected;
private List<IdNamePair> selectPairs;
// checkboxes
private boolean checked;
private String idNameSuffix;
private String checkboxValue;
// file inputs
private String currentFile;
// buttons
private ButtonTag.ButtonType buttonType;
private String beanName;
private String functionName;
private String cssClasses;
private String buttonLabel;
// yes/no radio buttons
private String yesLabel;
private String noLabel;
private String yesValue;
private String noValue;
// labels
private boolean asTextArea;
// extra parameters
private Map<String, String> extraParams;
// extra CSS classes
private String groupExtraCssClasses;
private String labelExtraCssClasses;
private String tagExtraCssClasses;
public HFHParameters() { }
public HFHParameters(final HFHParameters params) {
field = params.field;
idBean = params.idBean;
value = params.value;
fieldLabel = params.fieldLabel;
inputType = params.inputType;
required = params.required;
disabled = params.disabled;
placeholder = params.placeholder;
helpText = params.helpText;
readonly = params.readonly;
autocomplete = params.autocomplete;
// selects
selected = params.selected;
if (params.selectPairs != null)
selectPairs = new ArrayList<IdNamePair>(params.selectPairs);
// checkboxes
checked = params.checked;
idNameSuffix = params.idNameSuffix;
checkboxValue = params.checkboxValue;
// file inputs
currentFile = params.currentFile;
// buttons
buttonType = params.buttonType;
beanName = params.beanName;
functionName = params.functionName;
cssClasses = params.cssClasses;
buttonLabel = params.buttonLabel;
// yes/no radio buttons
yesLabel = params.yesLabel;
noLabel = params.noLabel;
yesValue = params.yesValue;
noValue = params.noValue;
// labels
asTextArea = params.asTextArea;
if (params.extraParams != null) {
initExtraParamMap();
extraParams.putAll(params.extraParams);
}
groupExtraCssClasses = params.groupExtraCssClasses;
labelExtraCssClasses = params.labelExtraCssClasses;
tagExtraCssClasses = params.tagExtraCssClasses;
}
private synchronized void initExtraParamMap() {
if (extraParams == null)
extraParams = new HashMap<String, String>();
}
// TODO: change return type into HFHParameters for fluent interface / will requires all client to recompile
public HFHParameters setExtra(final String name, final String value) {
if (extraParams == null)
initExtraParamMap();
extraParams.put(name, value);
return this;
}
public String getExtra(final String name) {
if (extraParams == null)
return null;
return extraParams.get(name);
}
public String getField() {
if (field == null)
throw new HFHParameterMissingException("field");
return field;
}
public HFHParameters setField(final String field) {
this.field = field;
return this;
}
public long getIdBean() {
if (idBean == -1)
throw new HFHParameterMissingException("idBean");
return idBean;
}
public HFHParameters setIdBean(final long idBean) {
this.idBean = idBean;
return this;
}
public String getValue() {
if (value == null)
return "";
return value;
}
public HFHParameters setValue(final String value) {
this.value = value;
return this;
}
public String getFieldLabel() {
if (fieldLabel == null)
throw new HFHParameterMissingException("fieldLabel");
return fieldLabel;
}
public HFHParameters setFieldLabel(final String fieldLabel) {
this.fieldLabel = fieldLabel;
return this;
}
public InputTag.InputType getInputType() {
if (inputType == null)
throw new HFHParameterMissingException("inputType");
return inputType;
}
public HFHParameters setInputType(final InputTag.InputType inputType) {
this.inputType = inputType;
return this;
}
public boolean isRequired() {
return required;
}
public HFHParameters setRequired(final boolean required) {
this.required = required;
return this;
}
public boolean isDisabled() {
return disabled;
}
public HFHParameters setDisabled(final boolean disabled) {
this.disabled = disabled;
return this;
}
public String getPlaceholder() {
return placeholder;
}
public HFHParameters setPlaceholder(final String placeholder) {
this.placeholder = placeholder;
return this;
}
public String getHelpText() {
return helpText;
}
public HFHParameters setHelpText(final String helpText) {
this.helpText = helpText;
return this;
}
public boolean isReadonly() {
return readonly;
}
// TODO: change return type into HFHParameters for fluent interface / will requires all client to recompile
public void setReadonly(final boolean readonly) {
this.readonly = readonly;
}
public boolean isAutocomplete() {
return autocomplete;
}
public HFHParameters setAutocomplete(final boolean autocomplete) {
this.autocomplete = autocomplete;
return this;
}
public String getSelected() {
if (selected == null)
throw new HFHParameterMissingException("selected");
return selected;
}
public HFHParameters setSelected(final String selected) {
this.selected = selected;
return this;
}
public HFHParameters setSelected(final long selected) {
this.selected = Long.toString(selected);
return this;
}
public List<IdNamePair> getSelectPairs() {
if (selectPairs == null)
throw new HFHParameterMissingException("selectPairs");
return selectPairs;
}
public HFHParameters setSelectPairs(final List<IdNamePair> selectPairs) {
this.selectPairs = selectPairs;
return this;
}
public boolean isChecked() {
return checked;
}
public HFHParameters setChecked(final boolean checked) {
this.checked = checked;
return this;
}
public String getIdNameSuffix() {
return idNameSuffix;
}
public HFHParameters setIdNameSuffix(final String idNameSuffix) {
this.idNameSuffix = idNameSuffix;
return this;
}
public String getCheckboxValue() {
return checkboxValue;
}
public HFHParameters setCheckboxValue(final String checkboxValue) {
this.checkboxValue = checkboxValue;
return this;
}
public String getCurrentFile() {
return currentFile;
}
public HFHParameters setCurrentFile(final String currentFile) {
this.currentFile = currentFile;
return this;
}
public boolean hasCurrentFile() {
return !Strings.isEmpty(currentFile);
}
public ButtonTag.ButtonType getButtonType() {
if (buttonType == null)
throw new HFHParameterMissingException("buttonType");
return buttonType;
}
public HFHParameters setButtonType(final ButtonTag.ButtonType buttonType) {
this.buttonType = buttonType;
return this;
}
public String getBeanName() {
return beanName;
}
public HFHParameters setBeanName(final String beanName) {
this.beanName = beanName;
return this;
}
public String getFunctionName() {
return functionName;
}
public HFHParameters setFunctionName(final String functionName) {
this.functionName = functionName;
return this;
}
public String getCssClasses() {
return cssClasses;
}
public HFHParameters setCssClasses(final String cssClasses) {
this.cssClasses = cssClasses;
return this;
}
public String getButtonLabel() {
return buttonLabel;
}
public HFHParameters setButtonLabel(final String buttonLabel) {
this.buttonLabel = buttonLabel;
return this;
}
public String getYesLabel() {
if (yesLabel == null)
throw new HFHParameterMissingException("yesLabel");
return yesLabel;
}
public HFHParameters setYesLabel(String yesLabel) {
this.yesLabel = yesLabel;
return this;
}
public String getNoLabel() {
if (noLabel == null)
throw new HFHParameterMissingException("noLabel");
return noLabel;
}
public HFHParameters setNoLabel(String noLabel) {
this.noLabel = noLabel;
return this;
}
public String getYesValue() {
if (yesValue == null)
return "true";
return yesValue;
}
public HFHParameters setYesValue(String yesValue) {
this.yesValue = yesValue;
return this;
}
public String getNoValue() {
if (noValue == null)
return "false";
return noValue;
}
public HFHParameters setNoValue(String noValue) {
this.noValue = noValue;
return this;
}
public HFHParameters setAsTextArea(boolean forceTextArea) {
this.asTextArea = forceTextArea;
return this;
}
public boolean isAsTextArea() {
return asTextArea;
}
public String getGroupExtraCssClasses() {
return groupExtraCssClasses;
}
public HFHParameters setGroupExtraCssClasses(String groupExtraCssClasses) {
this.groupExtraCssClasses = groupExtraCssClasses;
return this;
}
public boolean hasGroupExtraCssClasses() {
return !Strings.isEmpty(groupExtraCssClasses);
}
public String getLabelExtraCssClasses() {
return labelExtraCssClasses;
}
public HFHParameters setLabelExtraCssClasses(String labelExtraCssClasses) {
this.labelExtraCssClasses = labelExtraCssClasses;
return this;
}
public boolean hasLabelExtraCssClasses() {
return !Strings.isEmpty(labelExtraCssClasses);
}
public String getTagExtraCssClasses() {
return tagExtraCssClasses;
}
public HFHParameters setTagExtraCssClasses(String tagExtraCssClasses) {
this.tagExtraCssClasses = tagExtraCssClasses;
return this;
}
public boolean hasTagExtraCssClasses() {
return !Strings.isEmpty(tagExtraCssClasses);
}
}
|
package ch.unizh.ini.jaer.projects.minliu;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.beans.PropertyChangeEvent;
import java.util.Arrays;
import java.util.Observable;
import java.util.Observer;
import java.util.logging.Level;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import com.jogamp.opengl.GL;
import com.jogamp.opengl.GL2;
import com.jogamp.opengl.GL2ES3;
import com.jogamp.opengl.GLAutoDrawable;
import com.jogamp.opengl.util.awt.TextRenderer;
import ch.unizh.ini.jaer.projects.rbodo.opticalflow.AbstractMotionFlow;
import com.jogamp.opengl.GLException;
import java.util.Iterator;
import java.util.StringTokenizer;
import java.util.Timer;
import java.util.TimerTask;
import net.sf.jaer.Description;
import net.sf.jaer.DevelopmentStatus;
import net.sf.jaer.chip.AEChip;
import net.sf.jaer.event.ApsDvsEvent;
import net.sf.jaer.event.ApsDvsEventPacket;
import net.sf.jaer.event.EventPacket;
import net.sf.jaer.event.PolarityEvent;
import net.sf.jaer.eventio.AEInputStream;
import net.sf.jaer.eventprocessing.TimeLimiter;
import net.sf.jaer.graphics.AEViewer;
import net.sf.jaer.graphics.FrameAnnotater;
import net.sf.jaer.graphics.ImageDisplay;
import net.sf.jaer.graphics.ImageDisplay.Legend;
import net.sf.jaer.util.DrawGL;
import net.sf.jaer.util.EngineeringFormat;
import net.sf.jaer.util.TobiLogger;
import net.sf.jaer.util.filter.LowpassFilter;
/**
* Uses patch matching to measureTT local optical flow. <b>Not</b> gradient
* based, but rather matches local features backwards in time.
*
* @author Tobi and Min, Jan 2016
*/
@Description("Computes optical flow with vector direction using block matching")
@DevelopmentStatus(DevelopmentStatus.Status.Experimental)
public class PatchMatchFlow extends AbstractMotionFlow implements Observer, FrameAnnotater {
/* LDSP is Large Diamond Search Pattern, and SDSP mens Small Diamond Search Pattern.
LDSP has 9 points and SDSP consists of 5 points.
*/
private static final int LDSP[][] = {{0, -2}, {-1, -1}, {1, -1}, {-2, 0}, {0, 0},
{2, 0}, {-1, 1}, {1, 1}, {0, 2}};
private static final int SDSP[][] = {{0, -1}, {-1, 0}, {0, 0}, {1, 0}, {0, 1}};
// private int[][][] histograms = null;
private int numSlices = 3; //getInt("numSlices", 3); // fix to 4 slices to compute error sign from min SAD result from t-2d to t-3d
volatile private int numScales = getInt("numScales", 3); //getInt("numSlices", 3); // fix to 4 slices to compute error sign from min SAD result from t-2d to t-3d
private String scalesToCompute = getString("scalesToCompute", ""); //getInt("numSlices", 3); // fix to 4 slices to compute error sign from min SAD result from t-2d to t-3d
private int[] scalesToComputeArray = null; // holds array of scales to actually compute, for debugging
private int[] scaleResultCounts = new int[numScales]; // holds counts at each scale for min SAD results
/**
* The computed average possible match distance from 0 motion
*/
protected float avgPossibleMatchDistance;
private static final int MIN_SLICE_EVENT_COUNT_FULL_FRAME = 50;
private static final int MAX_SLICE_EVENT_COUNT_FULL_FRAME = 100000;
// private int sx, sy;
private int currentSliceIdx = 0; // the slice we are currently filling with events
/**
* time slice 2d histograms of (maybe signed) event counts slices = new
* byte[numSlices][numScales][subSizeX][subSizeY] [slice][scale][x][y]
*/
private byte[][][][] slices = null;
private float[] sliceSummedSADValues = null; // tracks the total summed SAD differences between reference and past slices, to adjust the slice duration
private int[] sliceSummedSADCounts = null; // tracks the total summed SAD differences between reference and past slices, to adjust the slice duration
private int[] sliceStartTimeUs; // holds the time interval between reference slice and this slice
private int[] sliceEndTimeUs; // holds the time interval between reference slice and this slice
private byte[][][] currentSlice;
private SADResult lastGoodSadResult = new SADResult(0, 0, 0, 0); // used for consistency check
private int blockDimension = getInt("blockDimension", 23);
// private float cost = getFloat("cost", 0.001f);
private float maxAllowedSadDistance = getFloat("maxAllowedSadDistance", .5f);
private float validPixOccupancy = getFloat("validPixOccupancy", 0.01f); // threshold for valid pixel percent for one block
private float weightDistance = getFloat("weightDistance", 0.95f); // confidence value consists of the distance and the dispersion, this value set the distance value
private static final int MAX_SKIP_COUNT = 1000;
private int skipProcessingEventsCount = getInt("skipProcessingEventsCount", 0); // skip this many events for processing (but not for accumulating to bitmaps)
private int skipCounter = 0;
private boolean adaptiveEventSkipping = getBoolean("adaptiveEventSkipping", true);
private float skipChangeFactor = (float) Math.sqrt(2); // by what factor to change the skip count if too slow or too fast
private boolean outputSearchErrorInfo = false; // make user choose this slow down every time
private boolean adaptiveSliceDuration = getBoolean("adaptiveSliceDuration", true);
private boolean adaptiveSliceDurationLogging = false; // for debugging and analyzing control of slice event number/duration
private TobiLogger adaptiveSliceDurationLogger = null;
private int adaptiveSliceDurationPacketCount = 0;
private boolean useSubsampling = getBoolean("useSubsampling", false);
private int adaptiveSliceDurationMinVectorsToControl = getInt("adaptiveSliceDurationMinVectorsToControl", 10);
private boolean showSliceBitMap = false; // Display the bitmaps
private float adapativeSliceDurationProportionalErrorGain = 0.05f; // factor by which an error signal on match distance changes slice duration
private int processingTimeLimitMs = getInt("processingTimeLimitMs", 100); // time limit for processing packet in ms to process OF events (events still accumulate). Overrides the system EventPacket timelimiter, which cannot be used here because we still need to accumulate and render the events.
private int sliceMaxValue = getInt("sliceMaxValue", 7);
private boolean rectifyPolarties = getBoolean("rectifyPolarties", false);
private TimeLimiter timeLimiter = new TimeLimiter(); // private instance used to accumulate events to slices even if packet has timed out
// results histogram for each packet
// private int ANGLE_HISTOGRAM_COUNT = 16;
// private int[] resultAngleHistogram = new int[ANGLE_HISTOGRAM_COUNT + 1];
private int[][] resultHistogram = null;
// private int resultAngleHistogramCount = 0, resultAngleHistogramMax = 0;
private int resultHistogramCount;
private volatile float avgMatchDistance = 0; // stores average match distance for rendering it
private float histStdDev = 0, lastHistStdDev = 0;
private float FSCnt = 0, DSCorrectCnt = 0;
float DSAverageNum = 0, DSAveError[] = {0, 0}; // Evaluate DS cost average number and the error.
// private float lastErrSign = Math.signum(1);
// private final String outputFilename;
private int sliceDeltaT; // The time difference between two slices used for velocity caluction. For constantDuration, this one is equal to the duration. For constantEventNumber, this value will change.
private int MIN_SLICE_DURATION_US = 100;
private int MAX_SLICE_DURATION_US = 300000;
private boolean enableImuTimesliceLogging = false;
private TobiLogger imuTimesliceLogger = null;
private volatile boolean resetOFHistogramFlag; // signals to reset the OF histogram after it is rendered
public enum PatchCompareMethod {
/*JaccardDistance,*/ /*HammingDistance*/
SAD/*, EventSqeDistance*/
};
private PatchCompareMethod patchCompareMethod = null;
public enum SearchMethod {
FullSearch, DiamondSearch, CrossDiamondSearch
};
private SearchMethod searchMethod = SearchMethod.valueOf(getString("searchMethod", SearchMethod.DiamondSearch.toString()));
private int sliceDurationUs = getInt("sliceDurationUs", 20000);
private int sliceEventCount = getInt("sliceEventCount", 1000);
private boolean rewindFlg = false; // The flag to indicate the rewind event.
private boolean displayResultHistogram = getBoolean("displayResultHistogram", true);
public enum SliceMethod {
ConstantDuration, ConstantEventNumber, AreaEventNumber, ConstantIntegratedFlow
};
private SliceMethod sliceMethod = SliceMethod.valueOf(getString("sliceMethod", SliceMethod.AreaEventNumber.toString()));
// counting events into subsampled areas, when count exceeds the threshold in any area, the slices are rotated
private int areaEventNumberSubsampling = getInt("areaEventNumberSubsampling", 5);
private int[][] areaCounts = null;
private boolean areaCountExceeded = false;
// nongreedy flow evaluation
// the entire scene is subdivided into regions, and a bitmap of these regions distributed flow computation more fairly
// by only servicing a region when sufficient fraction of other regions have been serviced first
private boolean nonGreedyFlowComputingEnabled = getBoolean("nonGreedyFlowComputingEnabled", false);
private boolean[][] nonGreedyRegions = null;
private int nonGreedyRegionsNumberOfRegions, nonGreedyRegionsCount;
/**
* This fraction of the regions must be serviced for computing flow before
* we reset the nonGreedyRegions map
*/
private float nonGreedyFractionToBeServiced = getFloat("nonGreedyFractionToBeServiced", .5f);
// timers and flags for showing filter properties temporarily
private final int SHOW_STUFF_DURATION_MS = 4000;
private volatile TimerTask stopShowingStuffTask = null;
private boolean showBlockSizeAndSearchAreaTemporarily = false;
private volatile boolean showAreaCountAreasTemporarily = false;
private int eventCounter = 0;
private int sliceLastTs = Integer.MAX_VALUE;
private ImageDisplay sliceBitmapImageDisplay; // makde a new ImageDisplay GLCanvas with default OpenGL capabilities
private JFrame sliceBitMapFrame = null;
private Legend sliceBitmapLegend;
/**
* A PropertyChangeEvent with this value is fired when the slices has been
* rotated. The oldValue is t-2d slice. The newValue is the t-d slice.
*/
public static final String EVENT_NEW_SLICES = "eventNewSlices";
TobiLogger sadValueLogger = new TobiLogger("sadvalues", "sadvalue,scale"); // TODO debug
public PatchMatchFlow(AEChip chip) {
super(chip);
setSliceDurationUs(getSliceDurationUs()); // 40ms is good for the start of the slice duration adatative since 4ms is too fast and 500ms is too slow.
setDefaultScalesToCompute();
// // Save the result to the file
// Format formatter = new SimpleDateFormat("YYYY-MM-dd_hh-mm-ss");
// // Instantiate a Date object
// Date date = new Date();
// Log file for the OF distribution's statistics
// outputFilename = "PMF_HistStdDev" + formatter.format(date) + ".txt";
String patchTT = "0a: Block matching";
// String eventSqeMatching = "Event squence matching";
// String preProcess = "Denoise";
String metricConfid = "Confidence of current metric";
try {
patchCompareMethod = PatchCompareMethod.valueOf(getString("patchCompareMethod", PatchCompareMethod.SAD.toString()));
} catch (IllegalArgumentException e) {
patchCompareMethod = PatchCompareMethod.SAD;
}
chip.addObserver(this); // to allocate memory once chip size is known
setPropertyTooltip(metricConfid, "maxAllowedSadDistance", "<html>SAD distance threshold for rejecting unresonable block matching result; <br> events with SAD distance larger than this value are rejected. <p>Lower value means it is harder to accept the event.");
setPropertyTooltip(metricConfid, "validPixOccupancy", "<html>Threshold for valid pixel percent for each block; Range from 0 to 1. <p>If either matching block is less occupied than this fraction, no motion vector will be calculated.");
setPropertyTooltip(metricConfid, "weightDistance", "<html>The confidence value consists of the distance and the dispersion; <br>weightDistance sets the weighting of the distance value compared with the dispersion value; Range from 0 to 1. <p>To count only e.g. hamming distance, set weighting to 1. <p> To count only dispersion, set to 0.");
setPropertyTooltip(patchTT, "blockDimension", "linear dimenion of patches to match, in pixels");
setPropertyTooltip(patchTT, "searchDistance", "search distance for matching patches, in pixels");
setPropertyTooltip(patchTT, "patchCompareMethod", "method to compare two patches; SAD=sum of absolute differences, HammingDistance is same as SAD for binary bitmaps");
setPropertyTooltip(patchTT, "searchMethod", "method to search patches");
setPropertyTooltip(patchTT, "sliceDurationUs", "duration of bitmaps in us, also called sample interval, when ConstantDuration method is used");
setPropertyTooltip(patchTT, "sliceEventCount", "number of events collected to fill a slice, when ConstantEventNumber method is used");
setPropertyTooltip(patchTT, "sliceMethod", "<html>Method for determining time slice duration for block matching<ul>"
+ "<li>ConstantDuration: slices are fixed time duration"
+ "<li>ConstantEventNumber: slices are fixed event number"
+ "<li>AreaEventNumber: slices are fixed event number in any subsampled area defined by areaEventNumberSubsampling"
+ "<li>ConstantIntegratedFlow: slices are rotated when average speeds times delta time exceeds half the search distance");
setPropertyTooltip(patchTT, "areaEventNumberSubsampling", "<html>how to subsample total area to count events per unit subsampling blocks for AreaEventNumber method. <p>For example, if areaEventNumberSubsampling=5, <br> then events falling into 32x32 blocks of pixels are counted <br>to determine when they exceed sliceEventCount to make new slice");
setPropertyTooltip(patchTT, "skipProcessingEventsCount", "skip this many events for processing (but not for accumulating to bitmaps)");
setPropertyTooltip(patchTT, "adaptiveEventSkipping", "enables adaptive event skipping depending on free time left in AEViewer animation loop");
setPropertyTooltip(patchTT, "adaptiveSliceDuration", "<html>Enables adaptive slice duration using feedback control, <br> based on average match search distance compared with total search distance. <p>If the match distance is too small, increaes duration or event count, and if too far, decreases duration or event count.<p>If using <i>AreaEventNumber</i> slice rotation method, don't increase count if actual duration is already longer than <i>sliceDurationUs</i>");
setPropertyTooltip(patchTT, "nonGreedyFlowComputingEnabled", "<html>Enables fairer distribution of computing flow by areas; an area is only serviced after " + nonGreedyFractionToBeServiced + " fraction of areas have been serviced. <p> Areas are defined by the the area subsubsampling bit shift.<p>Enabling this option ignores event skipping, so use <i>processingTimeLimitMs</i> to ensure minimum frame rate");
setPropertyTooltip(patchTT, "nonGreedyFractionToBeServiced", "An area is only serviced after " + nonGreedyFractionToBeServiced + " fraction of areas have been serviced. <p> Areas are defined by the the area subsubsampling bit shift.<p>Enabling this option ignores event skipping, so use the timeLimiter to ensure minimum frame rate");
setPropertyTooltip(patchTT, "useSubsampling", "<html>Enables using both full and subsampled block matching; <p>when using adaptiveSliceDuration, enables adaptive slice duration using feedback controlusing difference between full and subsampled resolution slice matching");
setPropertyTooltip(patchTT, "adaptiveSliceDurationMinVectorsToControl", "<html>Min flow vectors computed in packet to control slice duration, increase to reject control during idle periods");
setPropertyTooltip(patchTT, "processingTimeLimitMs", "<html>time limit for processing packet in ms to process OF events (events still accumulate). <br> Set to 0 to disable. <p>Alternative to the system EventPacket timelimiter, which cannot be used here because we still need to accumulate and render the events");
setPropertyTooltip(patchTT, "outputSearchErrorInfo", "enables displaying the search method error information");
setPropertyTooltip(patchTT, "outlierMotionFilteringEnabled", "(Currently has no effect) discards first optical flow event that points in opposite direction as previous one (dot product is negative)");
setPropertyTooltip(patchTT, "numSlices", "<html>Number of bitmaps to use. <p>At least 3: 1 to collect on, and two more to match on. <br>If >3, then best match is found between last slice reference block and all previous slices.");
setPropertyTooltip(patchTT, "numScales", "<html>Number of scales to search over for minimum SAD value; 1 for single full resolution scale, 2 for full + 2x2 subsampling, etc.");
setPropertyTooltip(patchTT, "sliceMaxValue", "<html> the maximum value used to represent each pixel in the time slice:<br>1 for binary or signed binary slice, (in conjunction with rectifyEventPolarities==true), etc, <br>up to 127 by these byte values");
setPropertyTooltip(patchTT, "rectifyPolarties", "<html> whether to rectify ON and OFF polarities to unsigned counts; true ignores polarity for block matching, false uses polarity with sliceNumBits>1");
setPropertyTooltip(patchTT, "scalesToCompute", "Scales to compute, e.g. 1,2; blank for all scales. 0 is full resolution, 1 is subsampled 2x2, etc");
setPropertyTooltip(patchTT, "showSlice", "Scales to compute, e.g. 1,2; blank for all scales. 0 is full resolution, 1 is subsampled 2x2, etc");
setPropertyTooltip(patchTT, "defaults", "Sets reasonable defaults");
setPropertyTooltip(patchTT, "enableImuTimesliceLogging", "Logs IMU and rate gyro");
String patchDispTT = "0b: Block matching display";
setPropertyTooltip(patchDispTT, "showSliceBitMap", "enables displaying the slices' bitmap");
setPropertyTooltip(patchDispTT, "ppsScale", "scale of pixels per second to draw local motion vectors; global vectors are scaled up by an additional factor of " + GLOBAL_MOTION_DRAWING_SCALE);
setPropertyTooltip(patchDispTT, "displayOutputVectors", "display the output motion vectors or not");
setPropertyTooltip(patchDispTT, "displayResultHistogram", "display the output motion vectors histogram to show disribution of results for each packet. Only implemented for HammingDistance");
getSupport().addPropertyChangeListener(AEViewer.EVENT_TIMESTAMPS_RESET, this);
getSupport().addPropertyChangeListener(AEViewer.EVENT_FILEOPEN, this);
getSupport().addPropertyChangeListener(AEInputStream.EVENT_REWIND, this);
getSupport().addPropertyChangeListener(AEInputStream.EVENT_NON_MONOTONIC_TIMESTAMP, this);
computeAveragePossibleMatchDistance();
}
// TODO debug
public void doStartLogSadValues() {
sadValueLogger.setEnabled(true);
}
// TODO debug
public void doStopLogSadValues() {
sadValueLogger.setEnabled(false);
}
@Override
synchronized public EventPacket filterPacket(EventPacket in) {
if (cameraCalibration != null && cameraCalibration.isFilterEnabled()) {
in = cameraCalibration.filterPacket(in);
}
setupFilter(in);
checkArrays();
if (processingTimeLimitMs > 0) {
timeLimiter.setTimeLimitMs(processingTimeLimitMs);
timeLimiter.restart();
} else {
timeLimiter.setEnabled(false);
}
int minDistScale = 0;
// following awkward block needed to deal with DVS/DAVIS and IMU/APS events
// block STARTS
Iterator i = null;
if (in instanceof ApsDvsEventPacket) {
i = ((ApsDvsEventPacket) in).fullIterator();
} else {
i = ((EventPacket) in).inputIterator();
}
nSkipped = 0;
nProcessed = 0;
while (i.hasNext()) {
Object o = i.next();
if (o == null) {
log.warning("null event passed in, returning input packet");
return in;
}
if ((o instanceof ApsDvsEvent) && ((ApsDvsEvent) o).isApsData()) {
continue;
}
PolarityEvent ein = (PolarityEvent) o;
if (!extractEventInfo(o)) {
continue;
}
if (measureAccuracy || discardOutliersForStatisticalMeasurementEnabled) {
if (imuFlowEstimator.calculateImuFlow(o)) {
continue;
}
}
// block ENDS
if (xyFilter()) {
continue;
}
countIn++;
// compute flow
SADResult result = null;
float[] sadVals = new float[numScales]; // TODO debug
switch (patchCompareMethod) {
case SAD:
boolean rotated = maybeRotateSlices();
if (rotated) {
adaptSliceDuration();
setResetOFHistogramFlag();
}
// if (ein.x >= subSizeX || ein.y > subSizeY) {
// log.warning("event out of range");
// continue;
if (!accumulateEvent(ein)) { // maybe skip events here
break;
}
SADResult sliceResult;
minDistScale = 0;
for (int scale : scalesToComputeArray) {
if (scale >= numScales) {
log.warning("scale " + scale + " is out of range of " + numScales + "; fix scalesToCompute for example by clearing it");
break;
}
sliceResult = minSADDistance(ein.x, ein.y, slices[sliceIndex(1)], slices[sliceIndex(2)], scale); // from ref slice to past slice k+1, using scale 0,1,....
// sliceSummedSADValues[sliceIndex(scale + 2)] += sliceResult.sadValue; // accumulate SAD for this past slice
// sliceSummedSADCounts[sliceIndex(scale + 2)]++; // accumulate SAD count for this past slice
// sliceSummedSADValues should end up filling 2 values for 4 slices
if ((result == null) || (sliceResult.sadValue < result.sadValue)) {
result = sliceResult; // result holds the overall min sad result
minDistScale = scale;
}
sadVals[scale] = sliceResult.sadValue; // TODO debug
}
scaleResultCounts[minDistScale]++;
float dt = (sliceDeltaTimeUs(2) * 1e-6f);
if (result != null) {
result.vx = result.dx / dt; // hack, convert to pix/second
result.vy = result.dy / dt; // TODO clean up, make time for each slice, since could be different when const num events
}
break;
// case JaccardDistance:
// maybeRotateSlices();
// if (!accumulateEvent(in)) {
// break;
// result = minJaccardDistance(x, y, bitmaps[sliceIndex(2)], bitmaps[sliceIndex(1)]);
// float dtj=(sliceDeltaTimeUs(2) * 1e-6f);
// result.dx = result.dx / dtj;
// result.dy = result.dy / dtj;
// break;
}
if (result == null /*|| result.sadValue == Float.MAX_VALUE*/) {
continue; // maybe some property change caused this
}
// reject values that are unreasonable
if (isNotSufficientlyAccurate(result)) {
continue;
}
vx = result.vx;
vy = result.vy;
v = (float) Math.sqrt((vx * vx) + (vy * vy));
// TODO debug
StringBuilder sadValsString = new StringBuilder();
for (int k = 0; k < sadVals.length - 1; k++) {
sadValsString.append(String.format("%f,", sadVals[k]));
}
sadValsString.append(String.format("%f", sadVals[sadVals.length - 1])); // very awkward to prevent trailing ,
if (sadValueLogger.isEnabled()) { // TODO debug
sadValueLogger.log(sadValsString.toString());
}
if (showSliceBitMap) {
// TODO danger, drawing outside AWT thread
drawMatching(result, ein, slices); // ein.x >> result.scale, ein.y >> result.scale, (int) result.dx >> result.scale, (int) result.dy >> result.scale, slices[sliceIndex(1)][result.scale], slices[sliceIndex(2)][result.scale], result.scale);
}
// if (filterOutInconsistentEvent(result)) {
// continue;
if (resultHistogram != null) {
resultHistogram[result.xidx][result.yidx]++;
resultHistogramCount++;
}
// if (result.dx != 0 || result.dy != 0) {
// final int bin = (int) Math.round(ANGLE_HISTOGRAM_COUNT * (Math.atan2(result.dy, result.dx) + Math.PI) / (2 * Math.PI));
// int v = ++resultAngleHistogram[bin];
// resultAngleHistogramCount++;
// if (v > resultAngleHistogramMax) {
// resultAngleHistogramMax = v;
processGoodEvent();
lastGoodSadResult.set(result);
}
motionFlowStatistics.updatePacket(countIn, countOut);
adaptEventSkipping();
if (rewindFlg) {
rewindFlg = false;
sliceLastTs = Integer.MAX_VALUE;
}
return isDisplayRawInput() ? in : dirPacket;
}
public void doDefaults() {
setSearchMethod(SearchMethod.DiamondSearch);
setBlockDimension(21);
setNumScales(2);
setSearchDistance(4);
setAdaptiveEventSkipping(true);
setAdaptiveSliceDuration(true);
setMaxAllowedSadDistance(.5f);
setDisplayVectorsEnabled(true);
setPpsScaleDisplayRelativeOFLength(true);
setDisplayGlobalMotion(true);
setPpsScale(.1f);
setSliceMaxValue(7);
setRectifyPolarties(true); // rectify to better handle cases of steadicam where pan/tilt flips event polarities
setValidPixOccupancy(.01f); // at least this fraction of pixels from each block must both have nonzero values
setSliceMethod(SliceMethod.AreaEventNumber);
// compute nearest power of two over block dimension
int ss = (int) (Math.log(blockDimension - 1) / Math.log(2));
setAreaEventNumberSubsampling(ss);
// set event count so that count=block area * sliceMaxValue/4;
// i.e. set count to roll over when slice pixels from most subsampled scale are half full if they are half stimulated
final int eventCount = (((blockDimension * blockDimension) * sliceMaxValue) / 2) >> (numScales - 1);
setSliceEventCount(eventCount);
setSliceDurationUs(50000); // set a bit smaller max duration in us to avoid instability where count gets too high with sparse input
}
private void adaptSliceDuration() {
// measure last hist to get control signal on slice duration
// measures avg match distance. weights the average so that long distances with more pixels in hist are not overcounted, simply
// by having more pixels.
if (rewindFlg) {
return; // don't adapt during rewind or delay before playing again
}
float radiusSum = 0;
int countSum = 0;
// int maxRadius = (int) Math.ceil(Math.sqrt(2 * searchDistance * searchDistance));
// int countSum = 0;
final int totSD = searchDistance << (numScales - 1);
for (int xx = -totSD; xx <= totSD; xx++) {
for (int yy = -totSD; yy <= totSD; yy++) {
int count = resultHistogram[xx + totSD][yy + totSD];
if (count > 0) {
final float radius = (float) Math.sqrt((xx * xx) + (yy * yy));
countSum += count;
radiusSum += radius * count;
}
}
}
if (countSum > 0) {
avgMatchDistance = radiusSum / (countSum); // compute average match distance from reference block
}
if (adaptiveSliceDuration && (countSum > adaptiveSliceDurationMinVectorsToControl)) {
// if (resultHistogramCount > 0) {
// following stats not currently used
// double[] rstHist1D = new double[resultHistogram.length * resultHistogram.length];
// int index = 0;
//// int rstHistMax = 0;
// for (int[] resultHistogram1 : resultHistogram) {
// for (int element : resultHistogram1) {
// rstHist1D[index++] = element;
// Statistics histStats = new Statistics(rstHist1D);
// // double histMax = Collections.max(Arrays.asList(ArrayUtils.toObject(rstHist1D)));
// double histMax = histStats.getMax();
// for (int m = 0; m < rstHist1D.length; m++) {
// rstHist1D[m] = rstHist1D[m] / histMax;
// lastHistStdDev = histStdDev;
// histStdDev = (float) histStats.getStdDev();
// try (FileWriter outFile = new FileWriter(outputFilename,true)) {
// outFile.write(String.format(in.getFirstEvent().getTimestamp() + " " + histStdDev + "\r\n"));
// outFile.close();
// } catch (IOException ex) {
// Logger.getLogger(PatchMatchFlow.class.getName()).log(Level.SEVERE, null, ex);
// } catch (Exception e) {
// log.warning("Caught " + e + ". See following stack trace.");
// e.printStackTrace();
// float histMean = (float) histStats.getMean();
// compute error signal.
// If err<0 it means the average match distance is larger than target avg match distance, so we need to reduce slice duration
// If err>0, it means the avg match distance is too short, so increse time slice
final float err = avgPossibleMatchDistance / 2 - avgMatchDistance; // use target that is smaller than average possible to bound excursions to large slices better
// final float err = ((searchDistance << (numScales - 1)) / 2) - avgMatchDistance;
// final float lastErr = searchDistance / 2 - lastHistStdDev;
// final double err = histMean - 1/ (rstHist1D.length * rstHist1D.length);
float errSign = Math.signum(err);
// float avgSad2 = sliceSummedSADValues[sliceIndex(4)] / sliceSummedSADCounts[sliceIndex(4)];
// float avgSad3 = sliceSummedSADValues[sliceIndex(3)] / sliceSummedSADCounts[sliceIndex(3)];
// float errSign = avgSad2 <= avgSad3 ? 1 : -1;
// if(Math.abs(err) > Math.abs(lastErr)) {
// errSign = -errSign;
// if(histStdDev >= 0.14) {
// if(lastHistStdDev > histStdDev) {
// errSign = -lastErrSign;
// } else {
// errSign = lastErrSign;
// errSign = 1;
// } else {
// errSign = (float) Math.signum(err);
// lastErrSign = errSign;
// problem with following is that if sliceDurationUs gets really big, then of course the avgMatchDistance becomes small because
// of the biased-towards-zero search policy that selects the closest match
switch (sliceMethod) {
case ConstantDuration:
int durChange = (int) (errSign * adapativeSliceDurationProportionalErrorGain * sliceDurationUs);
setSliceDurationUs(sliceDurationUs + durChange);
break;
case ConstantEventNumber:
case AreaEventNumber:
if (errSign > 0 && sliceDeltaTimeUs(2) < getSliceDurationUs()) { // don't increase slice past the sliceDurationUs limit
// match too short, increase count
setSliceEventCount(Math.round(sliceEventCount * (1 + adapativeSliceDurationProportionalErrorGain)));
} else {
setSliceEventCount(Math.round(sliceEventCount * (1 - adapativeSliceDurationProportionalErrorGain)));
}
break;
case ConstantIntegratedFlow:
setSliceEventCount(eventCounter);
}
if (adaptiveSliceDurationLogger != null && adaptiveSliceDurationLogger.isEnabled()) {
if (!isDisplayGlobalMotion()) {
setDisplayGlobalMotion(true);
}
adaptiveSliceDurationLogger.log(String.format("%d\t%f\t%f\t%f\t%d\t%d", adaptiveSliceDurationPacketCount++, avgMatchDistance, err, motionFlowStatistics.getGlobalMotion().getGlobalSpeed().getMean(), sliceDurationUs, sliceEventCount));
}
}
}
private void setResetOFHistogramFlag() {
resetOFHistogramFlag = true;
}
private void clearResetOFHistogramFlag() {
resetOFHistogramFlag = false;
}
private void resetOFHistogram() {
if (!resetOFHistogramFlag || resultHistogram == null) {
return;
}
for (int[] h : resultHistogram) {
Arrays.fill(h, 0);
}
resultHistogramCount = 0;
// Arrays.fill(resultAngleHistogram, 0);
// resultAngleHistogramCount = 0;
// resultAngleHistogramMax = Integer.MIN_VALUE;
Arrays.fill(scaleResultCounts, 0);
clearResetOFHistogramFlag();
}
private EngineeringFormat engFmt = new EngineeringFormat();
private TextRenderer textRenderer = null;
@Override
synchronized public void annotate(GLAutoDrawable drawable) {
super.annotate(drawable);
GL2 gl = drawable.getGL().getGL2();
try {
gl.glEnable(GL.GL_BLEND);
gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA);
gl.glBlendEquation(GL.GL_FUNC_ADD);
} catch (GLException e) {
e.printStackTrace();
}
if (displayResultHistogram && (resultHistogram != null)) {
// draw histogram as shaded in 2d hist above color wheel
// normalize hist
int rhDim = resultHistogram.length; // 2*(searchDistance<<numScales)+1
gl.glPushMatrix();
final float scale = 30f / rhDim; // size same as the color wheel
gl.glTranslatef(-35, .65f * chip.getSizeY(), 0); // center above color wheel
gl.glScalef(scale, scale, 1);
gl.glColor3f(0, 0, 1);
gl.glLineWidth(2f);
gl.glBegin(GL.GL_LINE_LOOP);
gl.glVertex2f(0, 0);
gl.glVertex2f(rhDim, 0);
gl.glVertex2f(rhDim, rhDim);
gl.glVertex2f(0, rhDim);
gl.glEnd();
if (textRenderer == null) {
textRenderer = new TextRenderer(new Font("SansSerif", Font.PLAIN, 64));
}
int max = 0;
for (int[] h : resultHistogram) {
for (int vv : h) {
if (vv > max) {
max = vv;
}
}
}
if (max == 0) {
gl.glTranslatef(0, rhDim / 2, 0); // translate to UL corner of histogram
textRenderer.begin3DRendering();
textRenderer.draw3D("No data", 0, 0, 0, .07f);
textRenderer.end3DRendering();
gl.glPopMatrix();
} else {
final float maxRecip = 2f / max;
gl.glPushMatrix();
// draw hist values
for (int xx = 0; xx < rhDim; xx++) {
for (int yy = 0; yy < rhDim; yy++) {
float g = maxRecip * resultHistogram[xx][yy];
gl.glColor3f(g, g, g);
gl.glBegin(GL2ES3.GL_QUADS);
gl.glVertex2f(xx, yy);
gl.glVertex2f(xx + 1, yy);
gl.glVertex2f(xx + 1, yy + 1);
gl.glVertex2f(xx, yy + 1);
gl.glEnd();
}
}
final int tsd = searchDistance << (numScales - 1);
if (avgMatchDistance > 0) {
gl.glPushMatrix();
gl.glColor4f(1f, 0, 0, .5f);
gl.glLineWidth(5f);
DrawGL.drawCircle(gl, tsd + .5f, tsd + .5f, avgMatchDistance, 16);
gl.glPopMatrix();
}
if (avgPossibleMatchDistance > 0) {
gl.glPushMatrix();
gl.glColor4f(0, 1f, 0, .5f);
gl.glLineWidth(5f);
DrawGL.drawCircle(gl, tsd + .5f, tsd + .5f, avgPossibleMatchDistance / 2, 16); // draw circle at target match distance
gl.glPopMatrix();
}
// a bunch of cryptic crap to draw a string the same width as the histogram...
gl.glPopMatrix();
gl.glPopMatrix(); // back to original chip coordinates
gl.glPushMatrix();
textRenderer.begin3DRendering();
String s = String.format("d=%.1f ms", 1e-3f * sliceDeltaT);
// final float sc = TextRendererScale.draw3dScale(textRenderer, s, chip.getCanvas().getScale(), chip.getWidth(), .1f);
// determine width of string in pixels and scale accordingly
FontRenderContext frc = textRenderer.getFontRenderContext();
Rectangle2D r = textRenderer.getBounds(s); // bounds in java2d coordinates, downwards more positive
Rectangle2D rt = frc.getTransform().createTransformedShape(r).getBounds2D(); // get bounds in textrenderer coordinates
// float ps = chip.getCanvas().getScale();
float w = (float) rt.getWidth(); // width of text in textrenderer, i.e. histogram cell coordinates (1 unit = 1 histogram cell)
float sc = subSizeX / w / 6; // scale to histogram width
gl.glTranslatef(0, .65f * subSizeY, 0); // translate to UL corner of histogram
textRenderer.draw3D(s, 0, 0, 0, sc);
String s2 = String.format("Skip: %d", skipProcessingEventsCount);
textRenderer.draw3D(s2, 0, (float) (rt.getHeight()) * sc, 0, sc);
String s3 = String.format("Slice events: %d", sliceEventCount);
textRenderer.draw3D(s3, 0, 2 * (float) (rt.getHeight()) * sc, 0, sc);
StringBuilder sb = new StringBuilder("Scale counts: ");
for (int c : scaleResultCounts) {
sb.append(String.format("%d ", c));
}
textRenderer.draw3D(sb.toString(), 0, (float) (3 * rt.getHeight()) * sc, 0, sc);
if (timeLimiter.isTimedOut()) {
String s4 = String.format("Timed out: skipped %d events", nSkipped);
textRenderer.draw3D(s4, 0, 4 * (float) (rt.getHeight()) * sc, 0, sc);
}
textRenderer.end3DRendering();
gl.glPopMatrix(); // back to original chip coordinates
// log.info(String.format("processed %.1f%% (%d/%d)", 100 * (float) nProcessed / (nSkipped + nProcessed), nProcessed, (nProcessed + nSkipped)));
// // draw histogram of angles around center of image
// if (resultAngleHistogramCount > 0) {
// gl.glPushMatrix();
// gl.glTranslatef(subSizeX / 2, subSizeY / 2, 0);
// gl.glLineWidth(getMotionVectorLineWidthPixels());
// gl.glColor3f(1, 1, 1);
// gl.glBegin(GL.GL_LINES);
// for (int i = 0; i < ANGLE_HISTOGRAM_COUNT; i++) {
// float l = ((float) resultAngleHistogram[i] / resultAngleHistogramMax) * chip.getMinSize() / 2; // bin 0 is angle -PI
// double angle = ((2 * Math.PI * i) / ANGLE_HISTOGRAM_COUNT) - Math.PI;
// float dx = (float) Math.cos(angle) * l, dy = (float) Math.sin(angle) * l;
// gl.glVertex2f(0, 0);
// gl.glVertex2f(dx, dy);
// gl.glEnd();
// gl.glPopMatrix();
resetOFHistogram(); // clears OF histogram if slices have been rotated
}
} else {
resetOFHistogram(); // clears OF histogram if slices have been rotated and we are not displaying the histogram
}
if (sliceMethod == SliceMethod.AreaEventNumber && showAreaCountAreasTemporarily) {
int d = 1 << areaEventNumberSubsampling;
gl.glLineWidth(2f);
gl.glColor3f(1, 1, 1);
gl.glBegin(GL.GL_LINES);
for (int x = 0; x <= subSizeX; x += d) {
gl.glVertex2f(x, 0);
gl.glVertex2f(x, subSizeY);
}
for (int y = 0; y <= subSizeY; y += d) {
gl.glVertex2f(0, y);
gl.glVertex2f(subSizeX, y);
}
gl.glEnd();
}
if (sliceMethod == SliceMethod.ConstantIntegratedFlow && showAreaCountAreasTemporarily) {
// TODO fill in what to draw
}
if (showBlockSizeAndSearchAreaTemporarily) {
gl.glLineWidth(2f);
gl.glColor3f(1, 0, 0);
// show block size
final int xx = subSizeX / 2, yy = subSizeY / 2, d = blockDimension / 2;
gl.glBegin(GL.GL_LINE_LOOP);
gl.glVertex2f(xx - d, yy - d);
gl.glVertex2f(xx + d, yy - d);
gl.glVertex2f(xx + d, yy + d);
gl.glVertex2f(xx - d, yy + d);
gl.glEnd();
// show search area
gl.glColor3f(0, 1, 0);
final int sd = d + (searchDistance << (numScales - 1));
gl.glBegin(GL.GL_LINE_LOOP);
gl.glVertex2f(xx - sd, yy - sd);
gl.glVertex2f(xx + sd, yy - sd);
gl.glVertex2f(xx + sd, yy + sd);
gl.glVertex2f(xx - sd, yy + sd);
gl.glEnd();
}
}
@Override
public synchronized void resetFilter() {
setSubSampleShift(0); // filter breaks with super's bit shift subsampling
super.resetFilter();
eventCounter = 0;
// lastTs = Integer.MIN_VALUE;
checkArrays();
if (slices == null) {
return; // on reset maybe chip is not set yet
}
for (byte[][][] b : slices) {
clearSlice(b);
}
currentSliceIdx = 0; // start by filling slice 0
currentSlice = slices[currentSliceIdx];
sliceLastTs = Integer.MAX_VALUE;
rewindFlg = true;
if (adaptiveEventSkippingUpdateCounterLPFilter != null) {
adaptiveEventSkippingUpdateCounterLPFilter.reset();
}
clearAreaCounts();
clearNonGreedyRegions();
}
@Override
public void update(Observable o, Object arg) {
if (!isFilterEnabled()) {
return;
}
super.update(o, arg);
if ((o instanceof AEChip) && (chip.getNumPixels() > 0)) {
resetFilter();
}
}
private LowpassFilter speedFilter = new LowpassFilter();
/**
* uses the current event to maybe rotate the slices
*
* @return true if slices were rotated
*/
private boolean maybeRotateSlices() {
int dt = ts - sliceLastTs;
if (dt < 0 || rewindFlg) { // handle timestamp wrapping
// System.out.println("rotated slices at ");
// System.out.println("rotated slices with dt= "+dt);
rotateSlices();
eventCounter = 0;
sliceDeltaT = dt;
sliceLastTs = ts;
return true;
}
switch (sliceMethod) {
case ConstantDuration:
if ((dt < sliceDurationUs)) {
return false;
}
break;
case ConstantEventNumber:
if (eventCounter < sliceEventCount) {
return false;
}
break;
case AreaEventNumber:
if (!areaCountExceeded && dt < MAX_SLICE_DURATION_US) {
return false;
}
break;
case ConstantIntegratedFlow:
speedFilter.setTauMs(sliceDeltaTimeUs(2) >> 10);
final float meanGlobalSpeed = motionFlowStatistics.getGlobalMotion().meanGlobalSpeed;
if (!Float.isNaN(meanGlobalSpeed)) {
speedFilter.filter(meanGlobalSpeed, ts);
}
final float filteredMeanGlobalSpeed = speedFilter.getValue();
final float totalMovement = filteredMeanGlobalSpeed * dt * 1e-6f;
if (Float.isNaN(meanGlobalSpeed)) { // we need to rotate slices somwhow even if there is no motion computed yet
if (eventCounter < sliceEventCount) {
return false;
}
if ((dt < sliceDurationUs)) {
return false;
}
break;
}
if (totalMovement < searchDistance / 2 && dt < sliceDurationUs) {
return false;
}
break;
}
rotateSlices();
/* Slices have been rotated */
getSupport().firePropertyChange(PatchMatchFlow.EVENT_NEW_SLICES, slices[sliceIndex(1)], slices[sliceIndex(2)]);
return true;
}
/**
* Rotates slices by incrementing the slice pointer with rollover back to
* zero, and sets currentSliceIdx and currentBitmap. Clears the new
* currentBitmap. Thus the slice pointer increments. 0,1,2,0,1,2
*
*/
private void rotateSlices() {
if (e != null) {
sliceEndTimeUs[currentSliceIdx] = e.timestamp;
}
/*Thus if 0 is current index for current filling slice, then sliceIndex returns 1,2 for pointer =1,2.
* Then if NUM_SLICES=3, after rotateSlices(),
currentSliceIdx=NUM_SLICES-1=2, and sliceIndex(0)=2, sliceIndex(1)=0, sliceIndex(2)=1.
*/
sliceSummedSADValues[currentSliceIdx] = 0; // clear out current collecting slice which becomes the oldest slice after rotation
sliceSummedSADCounts[currentSliceIdx] = 0; // clear out current collecting slice which becomes the oldest slice after rotation
currentSliceIdx
if (currentSliceIdx < 0) {
currentSliceIdx = numSlices - 1;
}
currentSlice = slices[currentSliceIdx];
//sliceStartTimeUs[currentSliceIdx] = ts; // current event timestamp; set on first event to slice
clearSlice(currentSlice);
clearAreaCounts();
eventCounter = 0;
sliceDeltaT = ts - sliceLastTs;
sliceLastTs = ts;
if (imuTimesliceLogger != null && imuTimesliceLogger.isEnabled()) {
imuTimesliceLogger.log(String.format("%d %d %.3f", ts, sliceDeltaT, imuFlowEstimator.getPanRateDps()));
}
}
/**
* Returns index to slice given pointer, with zero as current filling slice
* pointer.
*
*
* @param pointer how many slices in the past to index for. I.e.. 0 for
* current slice (one being currently filled), 1 for next oldest, 2 for
* oldest (when using NUM_SLICES=3).
* @return index into bitmaps[]
*/
private int sliceIndex(int pointer) {
return (currentSliceIdx + pointer) % numSlices;
}
/**
* returns slice delta time in us from reference slice
*
* @param pointer how many slices in the past to index for. I.e.. 0 for
* current slice (one being currently filled), 1 for next oldest, 2 for
* oldest (when using NUM_SLICES=3). Only meaningful for pointer>=2,
* currently exactly only pointer==2 since we are using only 3 slices.
*
* Modified to compute the delta time using the average of start and end
* timestamps of each slices, i.e. the slice time "midpoint" where midpoint
* is defined by average of first and last timestamp.
*
*/
private int sliceDeltaTimeUs(int pointer) {
// System.out.println("dt(" + pointer + ")=" + (sliceStartTimeUs[sliceIndex(1)] - sliceStartTimeUs[sliceIndex(pointer)]));
int idxOlder = sliceIndex(pointer), idxYounger = sliceIndex(1);
int tOlder = (sliceStartTimeUs[idxOlder] + sliceEndTimeUs[idxOlder]) / 2;
int tYounger = (sliceStartTimeUs[idxYounger] + sliceEndTimeUs[idxYounger]) / 2;
int dt = tYounger - tOlder;
return dt;
}
private int nSkipped = 0, nProcessed = 0;
/**
* Accumulates the current event to the current slice
*
* @return true if subsequent processing should done, false if it should be
* skipped for efficiency
*/
synchronized private boolean accumulateEvent(PolarityEvent e) {
if (eventCounter++ == 0) {
sliceStartTimeUs[currentSliceIdx] = e.timestamp; // current event timestamp
}
for (int s = 0; s < numScales; s++) {
final int xx = e.x >> s;
final int yy = e.y >> s;
// if (xx >= currentSlice[s].length || yy > currentSlice[s][xx].length) {
// log.warning("event out of range");
// return false;
int cv = currentSlice[s][xx][yy];
cv += rectifyPolarties ? 1 : (e.polarity == PolarityEvent.Polarity.On ? 1 : -1);
if (cv > sliceMaxValue) {
cv = sliceMaxValue;
} else if (cv < -sliceMaxValue) {
cv = -sliceMaxValue;
}
currentSlice[s][xx][yy] = (byte) cv;
}
if (sliceMethod == SliceMethod.AreaEventNumber) {
if (areaCounts == null) {
clearAreaCounts();
}
int c = ++areaCounts[e.x >> areaEventNumberSubsampling][e.y >> areaEventNumberSubsampling];
if (c >= sliceEventCount) {
areaCountExceeded = true;
// int count=0, sum=0, sum2=0;
// StringBuilder sb=new StringBuilder("Area counts:\n");
// for(int[] i:areaCounts){
// for(int j:i){
// count++;
// sum+=j;
// sum2+=j*j;
// sb.append(String.format("%6d ",j));
// sb.append("\n");
// float m=(float)sum/count;
// float s=(float)Math.sqrt((float)sum2/count-m*m);
// sb.append(String.format("mean=%.1f, std=%.1f",m,s));
// log.info("area count stats "+sb.toString());
}
}
if (timeLimiter.isTimedOut()) {
nSkipped++;
return false;
}
if (nonGreedyFlowComputingEnabled) {
// only process the event for flow if most of the other regions have already been processed
int xx = e.x >> areaEventNumberSubsampling, yy = e.y >> areaEventNumberSubsampling;
boolean didArea = nonGreedyRegions[xx][yy];
if (!didArea) {
nonGreedyRegions[xx][yy] = true;
nonGreedyRegionsCount++;
if (nonGreedyRegionsCount >= (int) (nonGreedyFractionToBeServiced * nonGreedyRegionsNumberOfRegions)) {
clearNonGreedyRegions();
}
nProcessed++;
return true; // skip counter is ignored
} else {
nSkipped++;
return false;
}
}
if (skipProcessingEventsCount == 0) {
nProcessed++;
return true;
}
if (skipCounter++ < skipProcessingEventsCount) {
nSkipped++;
return false;
}
nProcessed++;
skipCounter = 0;
return true;
}
// private void clearSlice(int idx) {
// for (int[] a : histograms[idx]) {
// Arrays.fill(a, 0);
private float sumArray[][] = null;
/**
* Computes block matching image difference best match around point x,y
* using blockDimension and searchDistance and scale
*
* @param x coordinate in subsampled space
* @param y
* @param prevSlice the slice over which we search for best match
* @param curSlice the slice from which we get the reference block
* @param subSampleBy the scale to compute this SAD on, 0 for full
* resolution, 1 for 2x2 subsampled block bitmap, etc
* @return SADResult that provides the shift and SAD value
*/
// private SADResult minHammingDistance(int x, int y, BitSet prevSlice, BitSet curSlice) {
private SADResult minSADDistance(int x, int y, byte[][][] curSlice, byte[][][] prevSlice, int subSampleBy) {
SADResult result = new SADResult();
float minSum = Float.MAX_VALUE, sum;
float FSDx = 0, FSDy = 0, DSDx = 0, DSDy = 0; // This is for testing the DS search accuracy.
final int searchRange = (2 * searchDistance) + 1; // The maximum search distance in this subSampleBy slice
if ((sumArray == null) || (sumArray.length != searchRange)) {
sumArray = new float[searchRange][searchRange];
} else {
for (float[] row : sumArray) {
Arrays.fill(row, Float.MAX_VALUE);
}
}
if (outputSearchErrorInfo) {
searchMethod = SearchMethod.FullSearch;
} else {
searchMethod = getSearchMethod();
}
final int xsub = x >> subSampleBy;
final int ysub = y >> subSampleBy;
final int r = ((blockDimension) / 2);
int w = subSizeX >> subSampleBy, h = subSizeY >> subSampleBy;
// Make sure both ref block and past slice block are in bounds on all sides or there'll be arrayIndexOutOfBoundary exception.
// Also we don't want to match ref block only on inner sides or there will be a bias towards motion towards middle
if (xsub - r - searchDistance < 0 || xsub + r + searchDistance >= w
|| ysub - r - searchDistance < 0 || ysub + r + searchDistance >= h) {
result.sadValue = Float.MAX_VALUE; // return very large distance for this match so it is not selected
return result;
}
switch (searchMethod) {
case DiamondSearch:
// SD = small diamond, LD=large diamond SP=search process
/* The center of the LDSP or SDSP could change in the iteration process,
so we need to use a variable to represent it.
In the first interation, it's the Zero Motion Potion (ZMP).
*/
int xCenter = x,
yCenter = y;
/* x offset of center point relative to ZMP, y offset of center point to ZMP.
x offset of center pointin positive number to ZMP, y offset of center point in positive number to ZMP.
*/
int dx,
dy,
xidx,
yidx; // x and y best match offsets in pixels, indices of these in 2d hist
int minPointIdx = 0; // Store the minimum point index.
boolean SDSPFlg = false; // If this flag is set true, then it means LDSP search is finished and SDSP search could start.
/* If one block has been already calculated, the computedFlg will be set so we don't to do
the calculation again.
*/
boolean computedFlg[][] = new boolean[searchRange][searchRange];
for (boolean[] row : computedFlg) {
Arrays.fill(row, false);
}
if (searchDistance == 1) { // LDSP search can only be applied for search distance >= 2.
SDSPFlg = true;
}
int iterationsLeft = searchRange * searchRange;
while (!SDSPFlg) {
/* 1. LDSP search */
for (int pointIdx = 0; pointIdx < LDSP.length; pointIdx++) {
dx = (LDSP[pointIdx][0] + xCenter) - x;
dy = (LDSP[pointIdx][1] + yCenter) - y;
xidx = dx + searchDistance;
yidx = dy + searchDistance;
// Point to be searched is out of search area, skip it.
if ((xidx >= searchRange) || (yidx >= searchRange) || (xidx < 0) || (yidx < 0)) {
continue;
}
/* We just calculate the blocks that haven't been calculated before */
if (computedFlg[xidx][yidx] == false) {
sumArray[xidx][yidx] = sadDistance(x, y, dx, dy, curSlice, prevSlice, subSampleBy);
computedFlg[xidx][yidx] = true;
if (outputSearchErrorInfo) {
DSAverageNum++;
}
if (outputSearchErrorInfo) {
if (sumArray[xidx][yidx] != sumArray[xidx][yidx]) { // TODO huh? this is never true, compares to itself
log.warning("It seems that there're some bugs in the DS algorithm.");
}
}
}
if (sumArray[xidx][yidx] <= minSum) {
minSum = sumArray[xidx][yidx];
minPointIdx = pointIdx;
}
}
/* 2. Check the minimum value position is in the center or not. */
xCenter = xCenter + LDSP[minPointIdx][0];
yCenter = yCenter + LDSP[minPointIdx][1];
if (minPointIdx == 4) { // It means it's in the center, so we should break the loop and go to SDSP search.
SDSPFlg = true;
}
if (--iterationsLeft < 0) {
log.warning("something is wrong with diamond search; did not find min in SDSP search");
SDSPFlg = true;
}
}
/* 3. SDSP Search */
for (int[] element : SDSP) {
dx = (element[0] + xCenter) - x;
dy = (element[1] + yCenter) - y;
xidx = dx + searchDistance;
yidx = dy + searchDistance;
// Point to be searched is out of search area, skip it.
if ((xidx >= searchRange) || (yidx >= searchRange) || (xidx < 0) || (yidx < 0)) {
continue;
}
/* We just calculate the blocks that haven't been calculated before */
if (computedFlg[xidx][yidx] == false) {
sumArray[xidx][yidx] = sadDistance(x, y, dx, dy, curSlice, prevSlice, subSampleBy);
computedFlg[xidx][yidx] = true;
if (outputSearchErrorInfo) {
DSAverageNum++;
}
if (outputSearchErrorInfo) {
if (sumArray[xidx][yidx] != sumArray[xidx][yidx]) {
log.warning("It seems that there're some bugs in the DS algorithm.");
}
}
}
if (sumArray[xidx][yidx] <= minSum) {
minSum = sumArray[xidx][yidx];
result.dx = -dx; // minus is because result points to the past slice and motion is in the other direction
result.dy = -dy;
result.sadValue = minSum;
}
// // debug
// if(result.dx==-searchDistance && result.dy==-searchDistance){
// System.out.println(result);
}
if (outputSearchErrorInfo) {
DSDx = result.dx;
DSDy = result.dy;
}
break;
case FullSearch:
for (dx = -searchDistance; dx <= searchDistance; dx++) {
for (dy = -searchDistance; dy <= searchDistance; dy++) {
sum = sadDistance(x, y, dx, dy, curSlice, prevSlice, subSampleBy);
sumArray[dx + searchDistance][dy + searchDistance] = sum;
if (sum < minSum) {
minSum = sum;
result.dx = -dx; // minus is because result points to the past slice and motion is in the other direction
result.dy = -dy;
result.sadValue = minSum;
}
}
}
if (outputSearchErrorInfo) {
FSCnt += 1;
FSDx = result.dx;
FSDy = result.dy;
} else {
break;
}
case CrossDiamondSearch:
break;
}
// compute the indices into 2d histogram of all motion vector results.
// It's a bit complicated because of multiple scales.
// Also, we want the indexes to be centered in the histogram array so that searches at full scale appear at the middle
// of the array and not at 0,0 corner.
// Suppose searchDistance=1 and numScales=2. Then the histogram has size 2*2+1=5.
// Therefore the scale 0 results need to have offset added to them to center results in histogram that
// shows results over all scales.
result.scale = subSampleBy;
// convert dx in search steps to dx in pixels including subsampling
// compute index assuming no subsampling or centering
result.xidx = result.dx + searchDistance;
result.yidx = result.dy + searchDistance;
// compute final dx and dy including subsampling
result.dx = result.dx << subSampleBy;
result.dy = result.dy << subSampleBy;
// compute final index including subsampling and centering
// idxCentering is shift needed to be applyed to store this result finally into the hist,
final int idxCentering = (searchDistance << (numScales - 1)) - ((searchDistance) << subSampleBy); // i.e. for subSampleBy=0 and numScales=2, shift=1 so that full scale search is centered in 5x5 hist
result.xidx = (result.xidx << subSampleBy) + idxCentering;
result.yidx = (result.yidx << subSampleBy) + idxCentering;
// if (result.xidx < 0 || result.yidx < 0 || result.xidx > maxIdx || result.yidx > maxIdx) {
// log.warning("something wrong with result=" + result);
// return null;
if (outputSearchErrorInfo) {
if ((DSDx == FSDx) && (DSDy == FSDy)) {
DSCorrectCnt += 1;
} else {
DSAveError[0] += Math.abs(DSDx - FSDx);
DSAveError[1] += Math.abs(DSDy - FSDy);
}
if (0 == (FSCnt % 10000)) {
log.log(Level.INFO, "Correct Diamond Search times are {0}, Full Search times are {1}, accuracy is {2}, averageNumberPercent is {3}, averageError is ({4}, {5})",
new Object[]{DSCorrectCnt, FSCnt, DSCorrectCnt / FSCnt, DSAverageNum / (searchRange * searchRange * FSCnt), DSAveError[0] / FSCnt, DSAveError[1] / (FSCnt - DSCorrectCnt)});
}
}
// if (tmpSadResult.xidx == searchRange-1 && tmpSadResult.yidx == searchRange-1) {
// tmpSadResult.sadValue = 1; // reject results to top right that are likely result of ambiguous search
return result;
}
/**
* computes Hamming distance centered on x,y with patch of patchSize for
* prevSliceIdx relative to curSliceIdx patch.
*
* @param xfull coordinate x in full resolution
* @param yfull coordinate y in full resolution
* @param dx the offset in pixels in the subsampled space of the past slice.
* The motion vector is then *from* this position *to* the current slice.
* @param dy
* @param prevSlice
* @param curSlice
* @param subsampleBy the scale to search over
* @return Distance value, max 1 when all pixels differ, min 0 when all the
* same
*/
private float sadDistance(final int xfull, final int yfull,
final int dx, final int dy,
final byte[][][] curSlice,
final byte[][][] prevSlice,
final int subsampleBy) {
final int x = xfull >> subsampleBy;
final int y = yfull >> subsampleBy;
final int r = ((blockDimension) / 2);
// int w = subSizeX >> subsampleBy, h = subSizeY >> subsampleBy;
// int adx = dx > 0 ? dx : -dx; // abs val of dx and dy, to compute limits
// int ady = dy > 0 ? dy : -dy;
// // Make sure both ref block and past slice block are in bounds on all sides or there'll be arrayIndexOutOfBoundary exception.
// // Also we don't want to match ref block only on inner sides or there will be a bias towards motion towards middle
// if (x - r - adx < 0 || x + r + adx >= w
// || y - r - ady < 0 || y + r + ady >= h) {
// return 1; // tobi changed to 1 again // Float.MAX_VALUE; // return very large distance for this match so it is not selected
int validPixNumCurSlice = 0, validPixNumPrevSlice = 0; // The valid pixel number in the current block
int nonZeroMatchCount = 0;
// int saturatedPixNumCurSlice = 0, saturatedPixNumPrevSlice = 0; // The valid pixel number in the current block
int sumDist = 0;
// try {
for (int xx = x - r; xx <= (x + r); xx++) {
for (int yy = y - r; yy <= (y + r); yy++) {
// if (xx < 0 || yy < 0 || xx >= w || yy >= h
// || xx + dx < 0 || yy + dy < 0 || xx + dx >= w || yy + dy >= h) {
//// log.warning("out of bounds slice access; something wrong"); // TODO fix this check above
// continue;
int currSliceVal = curSlice[subsampleBy][xx][yy]; // binary value on (xx, yy) for current slice
int prevSliceVal = prevSlice[subsampleBy][xx + dx][yy + dy]; // binary value on (xx, yy) for previous slice at offset dx,dy in (possibly subsampled) slice
int dist = (currSliceVal - prevSliceVal);
if (dist < 0) {
dist = (-dist);
}
sumDist += dist;
// if (currSlicePol != prevSlicePol) {
// hd += 1;
// if (currSliceVal == sliceMaxValue || currSliceVal == -sliceMaxValue) {
// saturatedPixNumCurSlice++; // pixels that are not saturated
// if (prevSliceVal == sliceMaxValue || prevSliceVal == -sliceMaxValue) {
// saturatedPixNumPrevSlice++;
if (currSliceVal != 0) {
validPixNumCurSlice++; // pixels that are not saturated
}
if (prevSliceVal != 0) {
validPixNumPrevSlice++;
}
if (currSliceVal != 0 && prevSliceVal != 0) {
nonZeroMatchCount++; // pixels that both have events in them
}
}
}
// } catch (ArrayIndexOutOfBoundsException ex) {
// log.warning(ex.toString());
// debug
// if(dx==-1 && dy==-1) return 0; else return Float.MAX_VALUE;
// normalize by dimesion of subsampling, with idea that subsampling increases SAD
//by sqrt(area) because of Gaussian distribution of SAD values
sumDist = sumDist >> (subsampleBy << 1);
final int blockDim = (2 * r) + 1;
final int blockArea = (blockDim) * (blockDim); // TODO check math here for fraction correct with subsampling
// TODD: NEXT WORK IS TO DO THE RESEARCH ON WEIGHTED HAMMING DISTANCE
// Calculate the metric confidence value
final int minValidPixNum = (int) (this.validPixOccupancy * blockArea);
// final int maxSaturatedPixNum = (int) ((1 - this.validPixOccupancy) * blockArea);
final float sadNormalizer = 1f / (blockArea * (rectifyPolarties ? 2 : 1) * sliceMaxValue);
// if current or previous block has insufficient pixels with values or if all the pixels are filled up, then reject match
if ((validPixNumCurSlice < minValidPixNum)
|| (validPixNumPrevSlice < minValidPixNum)
|| (nonZeroMatchCount < minValidPixNum) // || (saturatedPixNumCurSlice >= maxSaturatedPixNum) || (saturatedPixNumPrevSlice >= maxSaturatedPixNum)
) { // If valid pixel number of any slice is 0, then we set the distance to very big value so we can exclude it.
return 1; // tobi changed to 1 to represent max distance // Float.MAX_VALUE;
} else {
/*
retVal consists of the distance and the dispersion. dispersion is used to describe the spatial relationship within one block.
Here we use the difference between validPixNumCurrSli and validPixNumPrevSli to calculate the dispersion.
Inspired by paper "Measuring the spatial dispersion of evolutionist search process: application to Walksat" by Alain Sidaner.
*/
final float finalDistance = sadNormalizer * ((sumDist * weightDistance) + (Math.abs(validPixNumCurSlice - validPixNumPrevSlice) * (1 - weightDistance)));
return finalDistance;
}
}
/**
* Computes hamming weight around point x,y using blockDimension and
* searchDistance
*
* @param x coordinate in subsampled space
* @param y
* @param prevSlice
* @param curSlice
* @return SADResult that provides the shift and SAD value
*/
// private SADResult minJaccardDistance(int x, int y, BitSet prevSlice, BitSet curSlice) {
// private SADResult minJaccardDistance(int x, int y, byte[][] prevSlice, byte[][] curSlice) {
// float minSum = Integer.MAX_VALUE, sum = 0;
// SADResult sadResult = new SADResult(0, 0, 0);
// for (int dx = -searchDistance; dx <= searchDistance; dx++) {
// for (int dy = -searchDistance; dy <= searchDistance; dy++) {
// sum = jaccardDistance(x, y, dx, dy, prevSlice, curSlice);
// if (sum <= minSum) {
// minSum = sum;
// sadResult.dx = dx;
// sadResult.dy = dy;
// sadResult.sadValue = minSum;
// return sadResult;
/**
* computes Hamming distance centered on x,y with patch of patchSize for
* prevSliceIdx relative to curSliceIdx patch.
*
* @param x coordinate in subSampled space
* @param y
* @param patchSize
* @param prevSlice
* @param curSlice
* @return SAD value
*/
// private float jaccardDistance(int x, int y, int dx, int dy, BitSet prevSlice, BitSet curSlice) {
private float jaccardDistance(int x, int y, int dx, int dy, boolean[][] prevSlice, boolean[][] curSlice) {
float M01 = 0, M10 = 0, M11 = 0;
int blockRadius = blockDimension / 2;
// Make sure 0<=xx+dx<subSizeX, 0<=xx<subSizeX and 0<=yy+dy<subSizeY, 0<=yy<subSizeY, or there'll be arrayIndexOutOfBoundary exception.
if ((x < (blockRadius + dx)) || (x >= ((subSizeX - blockRadius) + dx)) || (x < blockRadius) || (x >= (subSizeX - blockRadius))
|| (y < (blockRadius + dy)) || (y >= ((subSizeY - blockRadius) + dy)) || (y < blockRadius) || (y >= (subSizeY - blockRadius))) {
return 1; // changed back to 1 // Float.MAX_VALUE;
}
for (int xx = x - blockRadius; xx <= (x + blockRadius); xx++) {
for (int yy = y - blockRadius; yy <= (y + blockRadius); yy++) {
final boolean c = curSlice[xx][yy], p = prevSlice[xx - dx][yy - dy];
if ((c == true) && (p == true)) {
M11 += 1;
}
if ((c == true) && (p == false)) {
M01 += 1;
}
if ((c == false) && (p == true)) {
M10 += 1;
}
// if ((curSlice.get((xx + 1) + ((yy) * subSizeX)) == true) && (prevSlice.get(((xx + 1) - dx) + ((yy - dy) * subSizeX)) == true)) {
// M11 += 1;
// if ((curSlice.get((xx + 1) + ((yy) * subSizeX)) == true) && (prevSlice.get(((xx + 1) - dx) + ((yy - dy) * subSizeX)) == false)) {
// M01 += 1;
// if ((curSlice.get((xx + 1) + ((yy) * subSizeX)) == false) && (prevSlice.get(((xx + 1) - dx) + ((yy - dy) * subSizeX)) == true)) {
// M10 += 1;
}
}
float retVal;
if (0 == (M01 + M10 + M11)) {
retVal = 0;
} else {
retVal = M11 / (M01 + M10 + M11);
}
retVal = 1 - retVal;
return retVal;
}
// private SADResult minVicPurDistance(int blockX, int blockY) {
// ArrayList<Integer[]> seq1 = new ArrayList(1);
// SADResult sadResult = new SADResult(0, 0, 0);
// int size = spikeTrains[blockX][blockY].size();
// int lastTs = spikeTrains[blockX][blockY].get(size - forwardEventNum)[0];
// for (int i = size - forwardEventNum; i < size; i++) {
// seq1.add(spikeTrains[blockX][blockY].get(i));
//// if(seq1.get(2)[0] - seq1.get(0)[0] > thresholdTime) {
//// return sadResult;
// double minium = Integer.MAX_VALUE;
// for (int i = -1; i < 2; i++) {
// for (int j = -1; j < 2; j++) {
// // Remove the seq1 itself
// if ((0 == i) && (0 == j)) {
// continue;
// ArrayList<Integer[]> seq2 = new ArrayList(1);
// if ((blockX >= 2) && (blockY >= 2)) {
// ArrayList<Integer[]> tmpSpikes = spikeTrains[blockX + i][blockY + j];
// if (tmpSpikes != null) {
// for (int index = 0; index < tmpSpikes.size(); index++) {
// if (tmpSpikes.get(index)[0] >= lastTs) {
// seq2.add(tmpSpikes.get(index));
// double dis = vicPurDistance(seq1, seq2);
// if (dis < minium) {
// minium = dis;
// sadResult.dx = -i;
// sadResult.dy = -j;
// lastFireIndex[blockX][blockY] = spikeTrains[blockX][blockY].size() - 1;
// if ((sadResult.dx != 1) || (sadResult.dy != 0)) {
// // sadResult = new SADResult(0, 0, 0);
// return sadResult;
// private double vicPurDistance(ArrayList<Integer[]> seq1, ArrayList<Integer[]> seq2) {
// int sum1Plus = 0, sum1Minus = 0, sum2Plus = 0, sum2Minus = 0;
// Iterator itr1 = seq1.iterator();
// Iterator itr2 = seq2.iterator();
// int length1 = seq1.size();
// int length2 = seq2.size();
// double[][] distanceMatrix = new double[length1 + 1][length2 + 1];
// for (int h = 0; h <= length1; h++) {
// for (int k = 0; k <= length2; k++) {
// if (h == 0) {
// distanceMatrix[h][k] = k;
// continue;
// if (k == 0) {
// distanceMatrix[h][k] = h;
// continue;
// double tmpMin = Math.min(distanceMatrix[h][k - 1] + 1, distanceMatrix[h - 1][k] + 1);
// double event1 = seq1.get(h - 1)[0] - seq1.get(0)[0];
// double event2 = seq2.get(k - 1)[0] - seq2.get(0)[0];
// distanceMatrix[h][k] = Math.min(tmpMin, distanceMatrix[h - 1][k - 1] + (cost * Math.abs(event1 - event2)));
// while (itr1.hasNext()) {
// Integer[] ii = (Integer[]) itr1.next();
// if (ii[1] == 1) {
// sum1Plus += 1;
// } else {
// sum1Minus += 1;
// while (itr2.hasNext()) {
// Integer[] ii = (Integer[]) itr2.next();
// if (ii[1] == 1) {
// sum2Plus += 1;
// } else {
// sum2Minus += 1;
// // return Math.abs(sum1Plus - sum2Plus) + Math.abs(sum1Minus - sum2Minus);
// return distanceMatrix[length1][length2];
// /**
// * Computes min SAD shift around point x,y using blockDimension and
// * searchDistance
// *
// * @param x coordinate in subsampled space
// * @param y
// * @param prevSlice
// * @param curSlice
// * @return SADResult that provides the shift and SAD value
// */
// private SADResult minSad(int x, int y, BitSet prevSlice, BitSet curSlice) {
// // for now just do exhaustive search over all shifts up to +/-searchDistance
// SADResult sadResult = new SADResult(0, 0, 0);
// float minSad = 1;
// for (int dx = -searchDistance; dx <= searchDistance; dx++) {
// for (int dy = -searchDistance; dy <= searchDistance; dy++) {
// float sad = sad(x, y, dx, dy, prevSlice, curSlice);
// if (sad <= minSad) {
// minSad = sad;
// sadResult.dx = dx;
// sadResult.dy = dy;
// sadResult.sadValue = minSad;
// return sadResult;
// /**
// * computes SAD centered on x,y with shift of dx,dy for prevSliceIdx
// * relative to curSliceIdx patch.
// *
// * @param x coordinate x in subSampled space
// * @param y coordinate y in subSampled space
// * @param dx block shift of x
// * @param dy block shift of y
// * @param prevSliceIdx
// * @param curSliceIdx
// * @return SAD value
// */
// private float sad(int x, int y, int dx, int dy, BitSet prevSlice, BitSet curSlice) {
// int blockRadius = blockDimension / 2;
// // Make sure 0<=xx+dx<subSizeX, 0<=xx<subSizeX and 0<=yy+dy<subSizeY, 0<=yy<subSizeY, or there'll be arrayIndexOutOfBoundary exception.
// if ((x < (blockRadius + dx)) || (x >= ((subSizeX - blockRadius) + dx)) || (x < blockRadius) || (x >= (subSizeX - blockRadius))
// || (y < (blockRadius + dy)) || (y >= ((subSizeY - blockRadius) + dy)) || (y < blockRadius) || (y >= (subSizeY - blockRadius))) {
// return Float.MAX_VALUE;
// float sad = 0, retVal = 0;
// float validPixNumCurrSli = 0, validPixNumPrevSli = 0; // The valid pixel number in the current block
// for (int xx = x - blockRadius; xx <= (x + blockRadius); xx++) {
// for (int yy = y - blockRadius; yy <= (y + blockRadius); yy++) {
// boolean currSlicePol = curSlice.get((xx + 1) + ((yy) * subSizeX)); // binary value on (xx, yy) for current slice
// boolean prevSlicePol = prevSlice.get(((xx + 1) - dx) + ((yy - dy) * subSizeX)); // binary value on (xx, yy) for previous slice
// int imuWarningDialog = (currSlicePol ? 1 : 0) - (prevSlicePol ? 1 : 0);
// if (currSlicePol == true) {
// validPixNumCurrSli += 1;
// if (prevSlicePol == true) {
// validPixNumPrevSli += 1;
// if (imuWarningDialog <= 0) {
// imuWarningDialog = -imuWarningDialog;
// sad += imuWarningDialog;
// // Calculate the metric confidence value
// float validPixNum = this.validPixOccupancy * (((2 * blockRadius) + 1) * ((2 * blockRadius) + 1));
// if ((validPixNumCurrSli <= validPixNum) || (validPixNumPrevSli <= validPixNum)) { // If valid pixel number of any slice is 0, then we set the distance to very big value so we can exclude it.
// retVal = 1;
// } else {
// /*
// retVal is consisted of the distance and the dispersion, dispersion is used to describe the spatial relationship within one block.
// Here we use the difference between validPixNumCurrSli and validPixNumPrevSli to calculate the dispersion.
// Inspired by paper "Measuring the spatial dispersion of evolutionist search process: application to Walksat" by Alain Sidaner.
// */
// retVal = ((sad * weightDistance) + (Math.abs(validPixNumCurrSli - validPixNumPrevSli) * (1 - weightDistance))) / (((2 * blockRadius) + 1) * ((2 * blockRadius) + 1));
// return retVal;
private class SADResult {
int dx, dy; // best match offset in pixels to reference block from past slice block, i.e. motion vector points in this direction
float vx, vy; // optical flow in pixels/second corresponding to this match
float sadValue; // sum of absolute differences for this best match normalized by number of pixels in reference area
int xidx, yidx; // x and y indices into 2d matrix of result. 0,0 corresponds to motion SW. dx, dy may be negative, like (-1, -1) represents SW.
// However, for histgram index, it's not possible to use negative number. That's the reason for intrducing xidx and yidx.
// boolean minSearchedFlg = false; // The flag indicates that this minimum have been already searched before.
int scale;
/**
* Allocates new results initialized to zero
*/
public SADResult() {
this(0, 0, 0, 0);
}
public SADResult(int dx, int dy, float sadValue, int scale) {
this.dx = dx;
this.dy = dy;
this.sadValue = sadValue;
}
public void set(SADResult s) {
this.dx = s.dx;
this.dy = s.dy;
this.sadValue = s.sadValue;
this.xidx = s.xidx;
this.yidx = s.yidx;
this.scale = s.scale;
}
@Override
public String toString() {
return String.format("(dx,dy=%5d,%5d), (vx,vy=%.1f,%.1f pps), SAD=%f, scale=%d", dx, dy, vx, vy, sadValue, scale);
}
}
private class Statistics {
double[] data;
int size;
public Statistics(double[] data) {
this.data = data;
size = data.length;
}
double getMean() {
double sum = 0.0;
for (double a : data) {
sum += a;
}
return sum / size;
}
double getVariance() {
double mean = getMean();
double temp = 0;
for (double a : data) {
temp += (a - mean) * (a - mean);
}
return temp / size;
}
double getStdDev() {
return Math.sqrt(getVariance());
}
public double median() {
Arrays.sort(data);
if ((data.length % 2) == 0) {
return (data[(data.length / 2) - 1] + data[data.length / 2]) / 2.0;
}
return data[data.length / 2];
}
public double getMin() {
Arrays.sort(data);
return data[0];
}
public double getMax() {
Arrays.sort(data);
return data[data.length - 1];
}
}
/**
* @return the blockDimension
*/
public int getBlockDimension() {
return blockDimension;
}
/**
* @param blockDimension the blockDimension to set
*/
synchronized public void setBlockDimension(int blockDimension) {
int old = this.blockDimension;
// enforce odd value
if ((blockDimension & 1) == 0) { // even
if (blockDimension > old) {
blockDimension++;
} else {
blockDimension
}
}
// clip final value
if (blockDimension < 1) {
blockDimension = 1;
} else if (blockDimension > 63) {
blockDimension = 63;
}
this.blockDimension = blockDimension;
getSupport().firePropertyChange("blockDimension", old, blockDimension);
putInt("blockDimension", blockDimension);
showBlockSizeAndSearchAreaTemporarily();
}
/**
* @return the sliceMethod
*/
public SliceMethod getSliceMethod() {
return sliceMethod;
}
/**
* @param sliceMethod the sliceMethod to set
*/
synchronized public void setSliceMethod(SliceMethod sliceMethod) {
SliceMethod old = this.sliceMethod;
this.sliceMethod = sliceMethod;
putString("sliceMethod", sliceMethod.toString());
if (sliceMethod == SliceMethod.AreaEventNumber || sliceMethod == SliceMethod.ConstantIntegratedFlow) {
showAreasForAreaCountsTemporarily();
}
// if(sliceMethod==SliceMethod.ConstantIntegratedFlow){
// setDisplayGlobalMotion(true);
getSupport().firePropertyChange("sliceMethod", old, this.sliceMethod);
}
public PatchCompareMethod getPatchCompareMethod() {
return patchCompareMethod;
}
synchronized public void setPatchCompareMethod(PatchCompareMethod patchCompareMethod) {
this.patchCompareMethod = patchCompareMethod;
putString("patchCompareMethod", patchCompareMethod.toString());
}
/**
*
* @return the search method
*/
public SearchMethod getSearchMethod() {
return searchMethod;
}
/**
*
* @param searchMethod the method to be used for searching
*/
synchronized public void setSearchMethod(SearchMethod searchMethod) {
SearchMethod old = this.searchMethod;
this.searchMethod = searchMethod;
putString("searchMethod", searchMethod.toString());
getSupport().firePropertyChange("searchMethod", old, this.searchMethod);
}
private void computeAveragePossibleMatchDistance() {
int n = 0;
double s = 0;
for (int xx = -searchDistance; xx <= searchDistance; xx++) {
for (int yy = -searchDistance; yy <= searchDistance; yy++) {
n++;
s += Math.sqrt((xx * xx) + (yy * yy));
}
}
double d = s / n; // avg for one scale
double s2 = 0;
for (int i = 0; i < numScales; i++) {
s2 += d * (1 << i);
}
double d2 = s2 / numScales;
log.info(String.format("searchDistance=%d numScales=%d: avgPossibleMatchDistance=%.1f", searchDistance, numScales, avgPossibleMatchDistance));
avgPossibleMatchDistance = (float) d2;
}
@Override
synchronized public void setSearchDistance(int searchDistance) {
int old = this.searchDistance;
if (searchDistance > 12) {
searchDistance = 12;
} else if (searchDistance < 1) {
searchDistance = 1; // limit size
}
this.searchDistance = searchDistance;
putInt("searchDistance", searchDistance);
getSupport().firePropertyChange("searchDistance", old, searchDistance);
resetFilter();
showBlockSizeAndSearchAreaTemporarily();
computeAveragePossibleMatchDistance();
}
/**
* @return the sliceDurationUs
*/
public int getSliceDurationUs() {
return sliceDurationUs;
}
/**
* @param sliceDurationUs the sliceDurationUs to set
*/
public void setSliceDurationUs(int sliceDurationUs) {
int old = this.sliceDurationUs;
if (sliceDurationUs < MIN_SLICE_DURATION_US) {
sliceDurationUs = MIN_SLICE_DURATION_US;
} else if (sliceDurationUs > MAX_SLICE_DURATION_US) {
sliceDurationUs = MAX_SLICE_DURATION_US; // limit it to one second
}
this.sliceDurationUs = sliceDurationUs;
/* If the slice duration is changed, reset FSCnt and DScorrect so we can get more accurate evaluation result */
FSCnt = 0;
DSCorrectCnt = 0;
putInt("sliceDurationUs", sliceDurationUs);
getSupport().firePropertyChange("sliceDurationUs", old, this.sliceDurationUs);
}
/**
* @return the sliceEventCount
*/
public int getSliceEventCount() {
return sliceEventCount;
}
/**
* @param sliceEventCount the sliceEventCount to set
*/
public void setSliceEventCount(int sliceEventCount) {
int old = this.sliceEventCount;
if (sliceEventCount < MIN_SLICE_EVENT_COUNT_FULL_FRAME) {
sliceEventCount = MIN_SLICE_EVENT_COUNT_FULL_FRAME;
} else if (sliceEventCount > MAX_SLICE_EVENT_COUNT_FULL_FRAME) {
sliceEventCount = MAX_SLICE_EVENT_COUNT_FULL_FRAME;
}
this.sliceEventCount = sliceEventCount;
putInt("sliceEventCount", sliceEventCount);
getSupport().firePropertyChange("sliceEventCount", old, this.sliceEventCount);
}
public float getMaxAllowedSadDistance() {
return maxAllowedSadDistance;
}
public void setMaxAllowedSadDistance(float maxAllowedSadDistance) {
float old = this.maxAllowedSadDistance;
if (maxAllowedSadDistance < 0) {
maxAllowedSadDistance = 0;
} else if (maxAllowedSadDistance > 1) {
maxAllowedSadDistance = 1;
}
this.maxAllowedSadDistance = maxAllowedSadDistance;
putFloat("maxAllowedSadDistance", maxAllowedSadDistance);
getSupport().firePropertyChange("maxAllowedSadDistance", old, this.maxAllowedSadDistance);
}
public float getValidPixOccupancy() {
return validPixOccupancy;
}
public void setValidPixOccupancy(float validPixOccupancy) {
float old = this.validPixOccupancy;
if (validPixOccupancy < 0) {
validPixOccupancy = 0;
} else if (validPixOccupancy > 1) {
validPixOccupancy = 1;
}
this.validPixOccupancy = validPixOccupancy;
putFloat("validPixOccupancy", validPixOccupancy);
getSupport().firePropertyChange("validPixOccupancy", old, this.validPixOccupancy);
}
public float getWeightDistance() {
return weightDistance;
}
public void setWeightDistance(float weightDistance) {
if (weightDistance < 0) {
weightDistance = 0;
} else if (weightDistance > 1) {
weightDistance = 1;
}
this.weightDistance = weightDistance;
putFloat("weightDistance", weightDistance);
}
// private int totalFlowEvents=0, filteredOutFlowEvents=0;
// private boolean filterOutInconsistentEvent(SADResult result) {
// if (!isOutlierMotionFilteringEnabled()) {
// return false;
// totalFlowEvents++;
// if (lastGoodSadResult == null) {
// return false;
// if (result.dx * lastGoodSadResult.dx + result.dy * lastGoodSadResult.dy >= 0) {
// return false;
// filteredOutFlowEvents++;
// return true;
synchronized private void checkArrays() {
if (subSizeX == 0 || subSizeY == 0) {
return; // don't do on init when chip is not known yet
}
// numSlices = getInt("numSlices", 3); // since resetFilter is called in super before numSlices is even initialized
if (slices == null || slices.length != numSlices
|| slices[0] == null || slices[0].length != numScales) {
if (numScales > 0 && numSlices > 0) { // deal with filter reconstruction where these fields are not set
slices = new byte[numSlices][numScales][][];
for (int n = 0; n < numSlices; n++) {
for (int s = 0; s < numScales; s++) {
int nx = (subSizeX >> s) + 1, ny = (subSizeY >> s) + 1;
if (slices[n][s] == null || slices[n][s].length != nx
|| slices[n][s][0] == null || slices[n][s][0].length != ny) {
slices[n][s] = new byte[nx][ny];
}
}
}
currentSliceIdx = 0; // start by filling slice 0
currentSlice = slices[currentSliceIdx];
sliceLastTs = Integer.MAX_VALUE;
sliceStartTimeUs = new int[numSlices];
sliceEndTimeUs = new int[numSlices];
sliceSummedSADValues = new float[numSlices];
sliceSummedSADCounts = new int[numSlices];
}
// log.info("allocated slice memory");
}
if (lastTimesMap != null) {
lastTimesMap = null; // save memory
}
int rhDim = (2 * (searchDistance << (numScales - 1))) + 1; // e.g. search distance 1, dim=3, 3x3 possibilties (including zero motion)
if ((resultHistogram == null) || (resultHistogram.length != rhDim)) {
resultHistogram = new int[rhDim][rhDim];
resultHistogramCount = 0;
}
checkNonGreedyRegionsAllocated();
}
/**
*
* @param distResult
* @return the confidence of the result. True means it's not good and should
* be rejected, false means we should accept it.
*/
private synchronized boolean isNotSufficientlyAccurate(SADResult distResult) {
boolean retVal = super.accuracyTests(); // check accuracy in super, if reject returns true
// additional test, normalized blaock distance must be small enough
// distance has max value 1
if (distResult.sadValue >= maxAllowedSadDistance) {
retVal = true;
}
return retVal;
}
/**
* @return the skipProcessingEventsCount
*/
public int getSkipProcessingEventsCount() {
return skipProcessingEventsCount;
}
/**
* @param skipProcessingEventsCount the skipProcessingEventsCount to set
*/
public void setSkipProcessingEventsCount(int skipProcessingEventsCount) {
int old = this.skipProcessingEventsCount;
if (skipProcessingEventsCount < 0) {
skipProcessingEventsCount = 0;
}
if (skipProcessingEventsCount > MAX_SKIP_COUNT) {
skipProcessingEventsCount = MAX_SKIP_COUNT;
}
this.skipProcessingEventsCount = skipProcessingEventsCount;
getSupport().firePropertyChange("skipProcessingEventsCount", old, this.skipProcessingEventsCount);
putInt("skipProcessingEventsCount", skipProcessingEventsCount);
}
/**
* @return the displayResultHistogram
*/
public boolean isDisplayResultHistogram() {
return displayResultHistogram;
}
/**
* @param displayResultHistogram the displayResultHistogram to set
*/
public void setDisplayResultHistogram(boolean displayResultHistogram) {
this.displayResultHistogram = displayResultHistogram;
putBoolean("displayResultHistogram", displayResultHistogram);
}
/**
* @return the adaptiveEventSkipping
*/
public boolean isAdaptiveEventSkipping() {
return adaptiveEventSkipping;
}
/**
* @param adaptiveEventSkipping the adaptiveEventSkipping to set
*/
synchronized public void setAdaptiveEventSkipping(boolean adaptiveEventSkipping) {
boolean old = this.adaptiveEventSkipping;
this.adaptiveEventSkipping = adaptiveEventSkipping;
putBoolean("adaptiveEventSkipping", adaptiveEventSkipping);
if (adaptiveEventSkipping && adaptiveEventSkippingUpdateCounterLPFilter != null) {
adaptiveEventSkippingUpdateCounterLPFilter.reset();
}
getSupport().firePropertyChange("adaptiveEventSkipping", old, this.adaptiveEventSkipping);
}
public boolean isOutputSearchErrorInfo() {
return outputSearchErrorInfo;
}
public boolean isShowSliceBitMap() {
return showSliceBitMap;
}
/**
* @param showSliceBitMap
* @param showSliceBitMap the option of displaying bitmap
*/
synchronized public void setShowSliceBitMap(boolean showSliceBitMap) {
boolean old = this.showSliceBitMap;
this.showSliceBitMap = showSliceBitMap;
getSupport().firePropertyChange("showSliceBitMap", old, this.showSliceBitMap);
}
synchronized public void setOutputSearchErrorInfo(boolean outputSearchErrorInfo) {
this.outputSearchErrorInfo = outputSearchErrorInfo;
if (!outputSearchErrorInfo) {
searchMethod = SearchMethod.valueOf(getString("searchMethod", SearchMethod.FullSearch.toString())); // make sure method is reset
}
}
private LowpassFilter adaptiveEventSkippingUpdateCounterLPFilter = null;
private int adaptiveEventSkippingUpdateCounter = 0;
private void adaptEventSkipping() {
if (!adaptiveEventSkipping) {
return;
}
if (chip.getAeViewer() == null) {
return;
}
int old = skipProcessingEventsCount;
if (chip.getAeViewer().isPaused() || chip.getAeViewer().isSingleStep()) {
skipProcessingEventsCount = 0;
getSupport().firePropertyChange("skipProcessingEventsCount", old, this.skipProcessingEventsCount);
}
if (adaptiveEventSkippingUpdateCounterLPFilter == null) {
adaptiveEventSkippingUpdateCounterLPFilter = new LowpassFilter(chip.getAeViewer().getFrameRater().FPS_LOWPASS_FILTER_TIMECONSTANT_MS);
}
final float averageFPS = chip.getAeViewer().getFrameRater().getAverageFPS();
final int frameRate = chip.getAeViewer().getDesiredFrameRate();
boolean skipMore = averageFPS < (int) (0.75f * frameRate);
boolean skipLess = averageFPS > (int) (0.25f * frameRate);
float newSkipCount = skipProcessingEventsCount;
if (skipMore) {
newSkipCount = adaptiveEventSkippingUpdateCounterLPFilter.filter(1 + (skipChangeFactor * skipProcessingEventsCount), 1000 * (int) System.currentTimeMillis());
} else if (skipLess) {
newSkipCount = adaptiveEventSkippingUpdateCounterLPFilter.filter((skipProcessingEventsCount / skipChangeFactor) - 1, 1000 * (int) System.currentTimeMillis());
}
skipProcessingEventsCount = Math.round(newSkipCount);
if (skipProcessingEventsCount > MAX_SKIP_COUNT) {
skipProcessingEventsCount = MAX_SKIP_COUNT;
} else if (skipProcessingEventsCount < 0) {
skipProcessingEventsCount = 0;
}
getSupport().firePropertyChange("skipProcessingEventsCount", old, this.skipProcessingEventsCount);
}
/**
* @return the adaptiveSliceDuration
*/
public boolean isAdaptiveSliceDuration() {
return adaptiveSliceDuration;
}
/**
* @param adaptiveSliceDuration the adaptiveSliceDuration to set
*/
synchronized public void setAdaptiveSliceDuration(boolean adaptiveSliceDuration) {
boolean old = this.adaptiveSliceDuration;
this.adaptiveSliceDuration = adaptiveSliceDuration;
putBoolean("adaptiveSliceDuration", adaptiveSliceDuration);
if (adaptiveSliceDurationLogging) {
if (adaptiveSliceDurationLogger == null) {
adaptiveSliceDurationLogger = new TobiLogger("PatchMatchFlow-SliceDurationControl", "slice duration or event count control logging");
adaptiveSliceDurationLogger.setHeaderLine("systemTimeMs\tpacketNumber\tavgMatchDistance\tmatchRadiusError\tglobalTranslationSpeedPPS\tsliceDurationUs\tsliceEventCount");
}
adaptiveSliceDurationLogger.setEnabled(adaptiveSliceDuration);
}
getSupport().firePropertyChange("adaptiveSliceDuration", old, this.adaptiveSliceDuration);
}
/**
* @return the processingTimeLimitMs
*/
public int getProcessingTimeLimitMs() {
return processingTimeLimitMs;
}
/**
* @param processingTimeLimitMs the processingTimeLimitMs to set
*/
public void setProcessingTimeLimitMs(int processingTimeLimitMs) {
this.processingTimeLimitMs = processingTimeLimitMs;
putInt("processingTimeLimitMs", processingTimeLimitMs);
}
/**
* clears all scales for a particular time slice
*
* @param slice [scale][x][y]
*/
private void clearSlice(byte[][][] slice) {
for (byte[][] scale : slice) { // for each scale
for (byte[] row : scale) { // for each col
Arrays.fill(row, (byte) 0); // fill col
}
}
}
private int dim = blockDimension + (2 * searchDistance);
protected static final String G_SEARCH_AREA_R_REF_BLOCK_AREA_B_BEST_MATCH = "G: search area\nR: ref block area\nB: best match";
/**
* Draws the block matching bitmap
*
* @param x
* @param y
* @param dx
* @param dy
* @param refBlock
* @param searchBlock
* @param subSampleBy
*/
synchronized private void drawMatching(SADResult result, PolarityEvent ein, byte[][][][] slices) {
// synchronized private void drawMatching(int x, int y, int dx, int dy, byte[][] refBlock, byte[][] searchBlock, int subSampleBy) {
int x = ein.x >> result.scale, y = ein.y >> result.scale;
int dx = (int) result.dx >> result.scale, dy = (int) result.dy >> result.scale;
byte[][] refBlock = slices[sliceIndex(1)][result.scale], searchBlock = slices[sliceIndex(2)][result.scale];
int subSampleBy = result.scale;
Legend sadLegend = null;
int dimNew = blockDimension + (2 * (searchDistance));
if (sliceBitMapFrame == null) {
String windowName = "Slice bitmaps";
sliceBitMapFrame = new JFrame(windowName);
sliceBitMapFrame.setLayout(new BoxLayout(sliceBitMapFrame.getContentPane(), BoxLayout.Y_AXIS));
sliceBitMapFrame.setPreferredSize(new Dimension(600, 600));
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
sliceBitmapImageDisplay = ImageDisplay.createOpenGLCanvas();
sliceBitmapImageDisplay.setBorderSpacePixels(10);
sliceBitmapImageDisplay.setImageSize(dimNew, dimNew);
sliceBitmapImageDisplay.setSize(200, 200);
sliceBitmapImageDisplay.setGrayValue(0);
sliceBitmapLegend = sliceBitmapImageDisplay.addLegend(G_SEARCH_AREA_R_REF_BLOCK_AREA_B_BEST_MATCH, 0, dim);
panel.add(sliceBitmapImageDisplay);
sliceBitMapFrame.getContentPane().add(panel);
sliceBitMapFrame.pack();
sliceBitMapFrame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
setShowSliceBitMap(false);
}
});
}
if (!sliceBitMapFrame.isVisible()) {
sliceBitMapFrame.setVisible(true);
}
final int radius = (blockDimension / 2) + searchDistance;
float scale = 1f / getSliceMaxValue();
try {
if ((x >= radius) && ((x + radius) < subSizeX)
&& (y >= radius) && ((y + radius) < subSizeY)) {
if (dimNew != sliceBitmapImageDisplay.getWidth()) {
dim = dimNew;
sliceBitmapImageDisplay.setImageSize(dimNew, dimNew);
sliceBitmapImageDisplay.clearLegends();
sliceBitmapLegend = sliceBitmapImageDisplay.addLegend(G_SEARCH_AREA_R_REF_BLOCK_AREA_B_BEST_MATCH, 0, dim);
}
// TextRenderer textRenderer = new TextRenderer(new Font("SansSerif", Font.PLAIN, 12));
/* Reset the image first */
sliceBitmapImageDisplay.clearImage();
/* Rendering the reference patch in t-imuWarningDialog slice, it's on the center with color red */
for (int i = searchDistance; i < (blockDimension + searchDistance); i++) {
for (int j = searchDistance; j < (blockDimension + searchDistance); j++) {
float[] f = sliceBitmapImageDisplay.getPixmapRGB(i, j);
f[0] = scale * Math.abs(refBlock[((x - (blockDimension / 2)) + i) - searchDistance][((y - (blockDimension / 2)) + j) - searchDistance]);
sliceBitmapImageDisplay.setPixmapRGB(i, j, f);
}
}
/* Rendering the area within search distance in t-2d slice, it's full of the whole search area with color green */
for (int i = 0; i < ((2 * radius) + 1); i++) {
for (int j = 0; j < ((2 * radius) + 1); j++) {
float[] f = sliceBitmapImageDisplay.getPixmapRGB(i, j);
f[1] = scale * Math.abs(searchBlock[(x - radius) + i][(y - radius) + j]);
sliceBitmapImageDisplay.setPixmapRGB(i, j, f);
}
}
/* Rendering the best matching patch in t-2d slice, it's on the shifted position related to the center location with color blue */
for (int i = searchDistance + dx; i < (blockDimension + searchDistance + dx); i++) {
for (int j = searchDistance + dy; j < (blockDimension + searchDistance + dy); j++) {
float[] f = sliceBitmapImageDisplay.getPixmapRGB(i, j);
f[2] = scale * Math.abs(searchBlock[((x - (blockDimension / 2)) + i) - searchDistance][((y - (blockDimension / 2)) + j) - searchDistance]);
sliceBitmapImageDisplay.setPixmapRGB(i, j, f);
}
}
if (sliceBitmapLegend != null) {
sliceBitmapLegend.s
= G_SEARCH_AREA_R_REF_BLOCK_AREA_B_BEST_MATCH
+ "\nScale: "
+ subSampleBy
+ "\nSAD: "
+ engFmt.format(result.sadValue);
}
}
} catch (ArrayIndexOutOfBoundsException e) {
}
sliceBitmapImageDisplay.repaint();
}
// /**
// * @return the numSlices
// */
// public int getNumSlices() {
// return numSlices;
// /**
// * @param numSlices the numSlices to set
// */
// synchronized public void setNumSlices(int numSlices) {
// if (numSlices < 3) {
// numSlices = 3;
// } else if (numSlices > 8) {
// numSlices = 8;
// this.numSlices = numSlices;
// putInt("numSlices", numSlices);
/**
* @return the sliceNumBits
*/
public int getSliceMaxValue() {
return sliceMaxValue;
}
/**
* @param sliceMaxValue the sliceMaxValue to set
*/
public void setSliceMaxValue(int sliceMaxValue) {
int old = this.sliceMaxValue;
if (sliceMaxValue < 1) {
sliceMaxValue = 1;
} else if (sliceMaxValue > 127) {
sliceMaxValue = 127;
}
this.sliceMaxValue = sliceMaxValue;
putInt("sliceMaxValue", sliceMaxValue);
getSupport().firePropertyChange("sliceMaxValue", old, this.sliceMaxValue);
}
/**
* @return the rectifyPolarties
*/
public boolean isRectifyPolarties() {
return rectifyPolarties;
}
/**
* @param rectifyPolarties the rectifyPolarties to set
*/
public void setRectifyPolarties(boolean rectifyPolarties) {
boolean old = this.rectifyPolarties;
this.rectifyPolarties = rectifyPolarties;
putBoolean("rectifyPolarties", rectifyPolarties);
getSupport().firePropertyChange("rectifyPolarties", old, this.rectifyPolarties);
}
/**
* @return the useSubsampling
*/
public boolean isUseSubsampling() {
return useSubsampling;
}
/**
* @param useSubsampling the useSubsampling to set
*/
public void setUseSubsampling(boolean useSubsampling) {
this.useSubsampling = useSubsampling;
}
/**
* @return the numScales
*/
public int getNumScales() {
return numScales;
}
/**
* @param numScales the numScales to set
*/
synchronized public void setNumScales(int numScales) {
int old = this.numScales;
if (numScales < 1) {
numScales = 1;
} else if (numScales > 4) {
numScales = 4;
}
this.numScales = numScales;
putInt("numScales", numScales);
setDefaultScalesToCompute();
scaleResultCounts = new int[numScales];
showBlockSizeAndSearchAreaTemporarily();
computeAveragePossibleMatchDistance();
getSupport().firePropertyChange("numScales", old, this.numScales);
}
/**
* Computes pooled (summed) value of slice at location xx, yy, in subsampled
* region around this point
*
* @param slice
* @param x
* @param y
* @param subsampleBy pool over 1<<subsampleBy by 1<<subsampleBy area to sum
* up the slice values @return
*/
private int pool(byte[][] slice, int x, int y, int subsampleBy) {
if (subsampleBy == 0) {
return slice[x][y];
} else {
int n = 1 << subsampleBy;
int sum = 0;
for (int xx = x; xx < x + n + n; xx++) {
for (int yy = y; yy < y + n + n; yy++) {
if (xx >= subSizeX || yy >= subSizeY) {
// log.warning("should not happen that xx="+xx+" or yy="+yy);
continue; // TODO remove this check when iteration avoids this sum explictly
}
sum += slice[xx][yy];
}
}
return sum;
}
}
/**
* @return the scalesToCompute
*/
public String getScalesToCompute() {
return scalesToCompute;
}
/**
* @param scalesToCompute the scalesToCompute to set
*/
synchronized public void setScalesToCompute(String scalesToCompute) {
this.scalesToCompute = scalesToCompute;
if (scalesToCompute == null || scalesToCompute.isEmpty()) {
setDefaultScalesToCompute();
} else {
StringTokenizer st = new StringTokenizer(scalesToCompute, ", ", false);
int n = st.countTokens();
if (n == 0) {
setDefaultScalesToCompute();
} else {
scalesToComputeArray = new int[n];
int i = 0;
while (st.hasMoreTokens()) {
try {
int scale = Integer.parseInt(st.nextToken());
scalesToComputeArray[i++] = scale;
} catch (NumberFormatException e) {
log.warning("bad string in scalesToCompute field, use blank or 0,2 for example");
setDefaultScalesToCompute();
}
}
}
}
}
private void setDefaultScalesToCompute() {
scalesToComputeArray = new int[numScales];
for (int i = 0; i < numScales; i++) {
scalesToComputeArray[i] = i;
}
}
/**
* @return the areaEventNumberSubsampling
*/
public int getAreaEventNumberSubsampling() {
return areaEventNumberSubsampling;
}
/**
* @param areaEventNumberSubsampling the areaEventNumberSubsampling to set
*/
synchronized public void setAreaEventNumberSubsampling(int areaEventNumberSubsampling) {
int old = this.areaEventNumberSubsampling;
if (areaEventNumberSubsampling < 3) {
areaEventNumberSubsampling = 3;
} else if (areaEventNumberSubsampling > 7) {
areaEventNumberSubsampling = 7;
}
this.areaEventNumberSubsampling = areaEventNumberSubsampling;
putInt("areaEventNumberSubsampling", areaEventNumberSubsampling);
showAreasForAreaCountsTemporarily();
clearAreaCounts();
if (sliceMethod != SliceMethod.AreaEventNumber) {
log.warning("AreaEventNumber method is not currently selected as sliceMethod");
}
getSupport().firePropertyChange("areaEventNumberSubsampling", old, this.areaEventNumberSubsampling);
}
private void showAreasForAreaCountsTemporarily() {
if (stopShowingStuffTask != null) {
stopShowingStuffTask.cancel();
}
stopShowingStuffTask = new TimerTask() {
@Override
public void run() {
showBlockSizeAndSearchAreaTemporarily = false; // in case we are canceling a task that would clear this
showAreaCountAreasTemporarily = false;
}
};
Timer showAreaCountsAreasTimer = new Timer();
showAreaCountAreasTemporarily = true;
showAreaCountsAreasTimer.schedule(stopShowingStuffTask, SHOW_STUFF_DURATION_MS);
}
private void showBlockSizeAndSearchAreaTemporarily() {
if (stopShowingStuffTask != null) {
stopShowingStuffTask.cancel();
}
stopShowingStuffTask = new TimerTask() {
@Override
public void run() {
showAreaCountAreasTemporarily = false; // in case we are canceling a task that would clear this
showBlockSizeAndSearchAreaTemporarily = false;
}
};
Timer showBlockSizeAndSearchAreaTimer = new Timer();
showBlockSizeAndSearchAreaTemporarily = true;
showBlockSizeAndSearchAreaTimer.schedule(stopShowingStuffTask, SHOW_STUFF_DURATION_MS);
}
private void clearAreaCounts() {
if (sliceMethod != SliceMethod.AreaEventNumber) {
return;
}
if (areaCounts == null || areaCounts.length != 1 + (subSizeX >> areaEventNumberSubsampling)) {
areaCounts = new int[1 + (subSizeX >> areaEventNumberSubsampling)][1 + (subSizeY >> areaEventNumberSubsampling)];
} else {
for (int[] i : areaCounts) {
Arrays.fill(i, 0);
}
}
areaCountExceeded = false;
}
private void clearNonGreedyRegions() {
if (!nonGreedyFlowComputingEnabled) {
return;
}
checkNonGreedyRegionsAllocated();
nonGreedyRegionsCount = 0;
for (boolean[] i : nonGreedyRegions) {
Arrays.fill(i, false);
}
}
private void checkNonGreedyRegionsAllocated() {
if (nonGreedyRegions == null || nonGreedyRegions.length != 1 + (subSizeX >> areaEventNumberSubsampling)) {
nonGreedyRegionsNumberOfRegions = (1 + (subSizeX >> areaEventNumberSubsampling)) * (1 + (subSizeY >> areaEventNumberSubsampling));
nonGreedyRegions = new boolean[1 + (subSizeX >> areaEventNumberSubsampling)][1 + (subSizeY >> areaEventNumberSubsampling)];
nonGreedyRegionsNumberOfRegions = (1 + (subSizeX >> areaEventNumberSubsampling)) * (1 + (subSizeY >> areaEventNumberSubsampling));
}
}
public int getSliceDeltaT() {
return sliceDeltaT;
}
/**
* @return the enableImuTimesliceLogging
*/
public boolean isEnableImuTimesliceLogging() {
return enableImuTimesliceLogging;
}
/**
* @param enableImuTimesliceLogging the enableImuTimesliceLogging to set
*/
public void setEnableImuTimesliceLogging(boolean enableImuTimesliceLogging) {
this.enableImuTimesliceLogging = enableImuTimesliceLogging;
if (enableImuTimesliceLogging) {
if (imuTimesliceLogger == null) {
imuTimesliceLogger = new TobiLogger("imuTimeslice.txt", "IMU rate gyro deg/s and patchmatch timeslice duration in ms");
imuTimesliceLogger.setHeaderLine("systemtime(ms) timestamp(us) timeslice(us) rate(deg/s)");
}
}
imuTimesliceLogger.setEnabled(enableImuTimesliceLogging);
}
/**
* @return the nonGreedyFlowComputingEnabled
*/
public boolean isNonGreedyFlowComputingEnabled() {
return nonGreedyFlowComputingEnabled;
}
/**
* @param nonGreedyFlowComputingEnabled the nonGreedyFlowComputingEnabled to
* set
*/
synchronized public void setNonGreedyFlowComputingEnabled(boolean nonGreedyFlowComputingEnabled) {
boolean old = this.nonGreedyFlowComputingEnabled;
this.nonGreedyFlowComputingEnabled = nonGreedyFlowComputingEnabled;
putBoolean("nonGreedyFlowComputingEnabled", nonGreedyFlowComputingEnabled);
if (nonGreedyFlowComputingEnabled) {
clearNonGreedyRegions();
}
getSupport().firePropertyChange("nonGreedyFlowComputingEnabled", old, nonGreedyFlowComputingEnabled);
}
/**
* @return the nonGreedyFractionToBeServiced
*/
public float getNonGreedyFractionToBeServiced() {
return nonGreedyFractionToBeServiced;
}
/**
* @param nonGreedyFractionToBeServiced the nonGreedyFractionToBeServiced to
* set
*/
public void setNonGreedyFractionToBeServiced(float nonGreedyFractionToBeServiced) {
this.nonGreedyFractionToBeServiced = nonGreedyFractionToBeServiced;
putFloat("nonGreedyFractionToBeServiced", nonGreedyFractionToBeServiced);
}
}
|
//FILE: DataProcessor.java
//PROJECT: Micro-Manager
//SUBSYSTEM: mmstudio
// This file is distributed in the hope that it will be useful,
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.
package org.micromanager.api;
import java.util.Collection;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import org.micromanager.events.EventManager;
import org.micromanager.events.ProcessorEnabledEvent;
import org.micromanager.utils.ReportingUtils;
/**
* A DataProcessor thread allows for on-the-fly modification of image
* data during acquisition.
*
* Inherit from this class and use the AcquisitionEngine functions
* addImageProcessor and removeImageProcessor to insert your code into the
* acquisition pipeline
*
* Note that this code will be invoked through its default (null) constructor
* If you use your own constructor, make sure that it accepts no arguments.
* If you need to initialize variables, do this in the makeConfigurationGUI
* method instead. That method is the first to be called.
*/
public abstract class DataProcessor<E> extends Thread {
private BlockingQueue<E> input_;
private BlockingQueue<E> output_;
private boolean stopRequested_ = false;
private boolean started_ = false;
// This boolean controls whether or not this DataProcessor will receive
// images.
private boolean isEnabled_ = true;
/**
* The scripting interface (commonly known as the "gui" object).
*/
protected ScriptInterface gui_;
/**
* The process method should be overridden by classes implementing
* DataProcessor, to provide a processing function.
*
* For example, an "Identity" DataProcessor (where nothing is
* done to the data) would override process() thus:
*
* <pre><code>
* @Override
* public void process() {
* produce(poll());
* }
* </code></pre>
*
* TaggedImageQueue.POISON will be the last object
* received by polling -- the process method should pass this
* object on unchanged.
*/
protected abstract void process();
/**
* Generate and show the GUI needed to configure the DataProcessor.
*/
public void makeConfigurationGUI() {};
/**
* Remove all GUI elements generated by makeConfigurationGUI(). If you
* override makeConfigurationGUI(), then you should also override this
* function.
*/
public void dispose() {};
/**
* Receive the ScriptInterface object.
*
* Normally, it is not necessary to override this method. If overriding,
* make sure to call super.setApp().
*/
public void setApp(ScriptInterface gui) {
gui_ = gui;
}
/**
* The run method that causes images to be processed. As DataProcessor
* extends <code>java.lang.Thread</code>, this method will be executed
* whenever DataProcessor.start() is called.
*
* Do not override this method (it should have been final).
*/
@Override
public void run() {
setStarted(true);
while (!stopRequested_) {
process();
}
}
/**
* Request that the data processor stop processing. The current
* processing event will continue, but no others will be started.
*
* Do not override this method (it should have been final). Do not call
* this method from DataProcessor subclasses.
*/
public synchronized void requestStop() {
stopRequested_ = true;
}
/*
* Private method for tracking when processing has started.
*/
private synchronized void setStarted(boolean started) {
started_ = started;
}
/**
* Returns true if the DataProcessor has started up and objects
* are being processed as they arrive.
*
* Do not override this method (it should have been final).
*/
public synchronized boolean isStarted() {
return started_;
}
/**
* Sets the input queue where objects to be processed
* are received by the DataProcessor.
*
* Do not override this method (it should have been final). This method is
* automatically called by the system to set up data processors.
*/
public synchronized void setInput(BlockingQueue<E> input) {
input_ = input;
}
/**
* Sets the output queue where objects that have been processed
* exit the DataProcessor.
*
* Do not override this method (it should have been final). This methods is
* automatically called by the system to set up data processors.
*/
public void setOutput(BlockingQueue<E> output) {
output_ = output;
}
/**
* A protected method that reads the next object from the input
* queue.
*
* This is the method that process() implementations should call to
* receive the image to process.
*
* Do not override this method (it should have been final).
*/
protected E poll() {
while (!stopRequested()) {
try {
// Ensure that input_ doesn't change between checking nullness
// and polling.
BlockingQueue<E> tmpQueue;
synchronized(this) {
tmpQueue = input_;
}
if (tmpQueue != null) {
E datum = tmpQueue.poll(100, TimeUnit.MILLISECONDS);
if (datum != null) {
return datum;
}
}
if (tmpQueue == null) {
// Sleep to avoid busywaiting.
Thread.sleep(100);
}
} catch (InterruptedException ex) {
ReportingUtils.logError(ex);
}
}
return null;
}
/**
* A convenience method for draining all available data objects
* on the input queue to a collection.
*
* Do not override this method (it should have been final).
*/
protected void drainTo(Collection<E> data) {
input_.drainTo(data);
}
/**
* A convenience method for posting a data object to the output queue.
*
* This is the method that process() implementations should call to
* send out the processed image(s).
*
* Do not override this method (it should have been final).
*/
protected void produce(E datum) {
try {
output_.put(datum);
} catch (InterruptedException ex) {
ReportingUtils.logError(ex);
}
};
/**
* Returns true if stop has been requested.
*
* Usually, subclasses need not care about stop requests, as they are
* handled automatically.
*/
protected synchronized boolean stopRequested() {
return stopRequested_;
}
/**
* Turn the Processor on or off.
*
* Enabling and disabling the processor is handled automatically by the
* system.
*
* It is usually not necessary to override this method. If overriding, make
* sure to call super.setEnabled(isEnabled).
*/
public void setEnabled(boolean isEnabled) {
isEnabled_ = isEnabled;
EventManager.post(new ProcessorEnabledEvent(this, isEnabled));
}
/**
* Get whether or not this Processor is enabled.
*
* Do not override this method (it should have been final).
*/
public boolean getIsEnabled() {
return isEnabled_;
}
}
|
package org.broad.igv.track;
import com.google.common.eventbus.Subscribe;
import org.apache.log4j.Logger;
import org.broad.igv.Globals;
import org.broad.igv.cli_plugin.PluginFeatureSource;
import org.broad.igv.cli_plugin.PluginSource;
import org.broad.igv.feature.*;
import org.broad.igv.feature.genome.Genome;
import org.broad.igv.feature.genome.GenomeManager;
import org.broad.igv.renderer.*;
import org.broad.igv.session.IGVSessionReader;
import org.broad.igv.session.SubtlyImportant;
import org.broad.igv.tools.FeatureSearcher;
import org.broad.igv.tools.motiffinder.MotifFinderSource;
import org.broad.igv.ui.IGV;
import org.broad.igv.ui.UIConstants;
import org.broad.igv.ui.event.DataLoadedEvent;
import org.broad.igv.ui.panel.ReferenceFrame;
import org.broad.igv.ui.util.MessageUtils;
import org.broad.igv.util.*;
import org.broad.igv.variant.VariantTrack;
import org.broad.tribble.Feature;
import org.broad.tribble.TribbleException;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.swing.*;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.MarshalException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlType;
import javax.xml.namespace.QName;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.util.*;
import java.util.List;
/**
* Track which displays features, typically showing regions of the genome
* in a qualitative way. Features are rendered using the specified FeatureRenderer.
* The gene track is an example of a feature track.
*
* @author jrobinso
*/
@XmlType(factoryMethod = "getNextTrack")
@XmlSeeAlso({VariantTrack.class, PluginFeatureSource.class, MotifFinderSource.class})
public class FeatureTrack extends AbstractTrack {
private static Logger log = Logger.getLogger(FeatureTrack.class);
//All tracks have label "Track", we need to specify the type sometimes
//but still preserve backwards compatibility
@XmlAttribute
private Class clazz = FeatureTrack.class;
public static final int MINIMUM_FEATURE_SPACING = 5;
public static final int DEFAULT_MARGIN = 5;
public static final int NO_FEATURE_ROW_SELECTED = -1;
protected static final Color SELECTED_FEATURE_ROW_COLOR = new Color(100, 100, 100, 30);
private static final int DEFAULT_EXPANDED_HEIGHT = 35;
private static final int DEFAULT_SQUISHED_HEIGHT = 12;
private int expandedRowHeight = DEFAULT_EXPANDED_HEIGHT;
private int squishedRowHeight = DEFAULT_SQUISHED_HEIGHT;
boolean fatalLoadError = false;
Track.DisplayMode lastFeatureMode = null; // Keeps track of the feature display mode before an auto-switch to COLLAPSE
protected List<Rectangle> levelRects = new ArrayList();
// TODO -- this is a memory leak, this cache needs cleared when the reference frame collection (gene list) changes
/**
* Map of reference frame name -> packed features
*/
protected Map<String, PackedFeatures<IGVFeature>> packedFeaturesMap = Collections.synchronizedMap(new HashMap<String, PackedFeatures<IGVFeature>>());
private FeatureRenderer renderer;
private DataRenderer coverageRenderer;
// true == features, false = coverage
private boolean showFeatures = true;
protected FeatureSource source;
protected boolean featuresLoading = false;
//track which row of the expanded track is selected by the user.
//Selection goes away if tracks are collpased
protected int selectedFeatureRowIndex = NO_FEATURE_ROW_SELECTED;
//Feature selected by the user. This is repopulated on each handleDataClick() call.
protected IGVFeature selectedFeature = null;
int margin = DEFAULT_MARGIN;
private static boolean drawBorder = true;
private boolean alternateExonColor = false;
private static final String PLUGIN_SOURCE = "PluginSource";
private static final String SEQUENCE_MATCH_SOURCE = "SequenceMatchSource";
// TODO -- there are WAY too many constructors for this class
/**
* Construct with no feature source. Currently this is only used for the SpliceJunctionFinderTrack subclass.
*
* @param id
* @param name
*/
public FeatureTrack(String id, String name) {
super(id, name);
setSortable(false);
}
public FeatureTrack(ResourceLocator locator, String id, String name) {
super(locator, id, name);
setSortable(false);
}
/**
* Constructor with no ResourceLocator. Note: tracks using this constructor will not be recorded in the
* "Resources" section of session files.
*
* @param id
* @param name
* @param source
* @api
*/
public FeatureTrack(String id, String name, FeatureSource source) {
super(id, name);
init(source, null);
setSortable(false);
}
/**
* Constructor specifically for BigWig data source
*
* @param locator
* @param id
* @param name
* @param source
*/
public FeatureTrack(ResourceLocator locator, String id, String name, FeatureSource source) {
super(locator, id, name);
init(source, locator.getPath());
setSortable(false);
}
public FeatureTrack(ResourceLocator locator, FeatureSource source) {
super(locator);
init(source, locator.getPath());
setSortable(false);
}
public FeatureTrack(ResourceLocator locator, String id, FeatureSource source) {
super(locator, id);
init(source, locator.getPath());
}
/**
* Create a new track which is a shallow copy of this one
*
* @param featureTrack
*/
public FeatureTrack(FeatureTrack featureTrack) {
this(featureTrack.getId(), featureTrack.getName(), featureTrack.source);
}
protected void init(FeatureSource source, String path) {
this.source = source;
setMinimumHeight(10);
setColor(Color.blue.darker());
coverageRenderer = new BarChartRenderer();
if (source.getFeatureWindowSize() > 0) {
visibilityWindow = source.getFeatureWindowSize();
}
this.renderer = path != null && path.endsWith("junctions.bed") ?
new SpliceJunctionRenderer() : new IGVFeatureRenderer();
}
@Override
public boolean isFilterable() {
return false; // Don't filter "feature" tracks
}
@Override
public int getHeight() {
if (!isVisible()) {
return 0;
}
int rowHeight = getDisplayMode() == DisplayMode.SQUISHED ? squishedRowHeight : expandedRowHeight;
int minHeight = rowHeight * Math.max(1, getNumberOfFeatureLevels());
return Math.max(minHeight, super.getHeight());
}
public int getExpandedRowHeight() {
return expandedRowHeight;
}
public void setExpandedRowHeight(int expandedRowHeight) {
this.expandedRowHeight = expandedRowHeight;
}
public int getSquishedRowHeight() {
return squishedRowHeight;
}
public void setSquishedRowHeight(int squishedRowHeight) {
this.squishedRowHeight = squishedRowHeight;
}
public int getFeatureWindowSize() {
return source.getFeatureWindowSize();
}
public void setRendererClass(Class rc) {
try {
renderer = (FeatureRenderer) rc.newInstance();
} catch (Exception ex) {
log.error("Error instatiating renderer ", ex);
}
}
public void setMargin(int margin) {
this.margin = margin;
}
@Override
public void setProperties(TrackProperties trackProperties) {
super.setProperties(trackProperties);
if (trackProperties.getFeatureVisibilityWindow() >= 0) {
setVisibilityWindow(trackProperties.getFeatureVisibilityWindow());
}
alternateExonColor = trackProperties.isAlternateExonColor();
}
public void setWindowFunction(WindowFunction type) {
// Ignored for feature tracks
}
/**
* Return the maximum number of features for any panel in this track. In whole genome view there is a single panel,
* but there are multiple in gene list view (one for each gene list).
*
* @return
*/
public int getNumberOfFeatureLevels() {
if (areFeaturesStacked() && packedFeaturesMap.size() > 0) {
int n = 0;
synchronized (packedFeaturesMap){
for (PackedFeatures pf : packedFeaturesMap.values()) {
//dhmay adding null check. To my mind this shouldn't be necessary, but we're encountering
//it intermittently. Food for future thought
if (pf != null){
n = Math.max(n, pf.getRowCount());
}
}
}
return n;
}
return 1;
}
/**
* @return Whether features are displayed stacked on top of one another, rather than overlapping
*/
protected boolean areFeaturesStacked() {
return getDisplayMode() != DisplayMode.COLLAPSED;
}
/**
* Return a score over the interval. This is required by the track interface to support sorting.
*/
public float getRegionScore(String chr, int start, int end, int zoom, RegionScoreType scoreType, String frameName) {
try {
if (scoreType == RegionScoreType.MUTATION_COUNT && this.getTrackType() == TrackType.MUTATION) {
Iterator<Feature> features = source.getFeatures(chr, start, end);
int count = 0;
if (features != null) {
while (features.hasNext()) {
Feature f = features.next();
if (f.getStart() > end) {
break;
}
if (f.getEnd() >= start) {
count++;
}
}
}
return count;
}
} catch (IOException e) {
log.error("Error counting features.", e);
}
return -Float.MAX_VALUE;
}
public FeatureRenderer getRenderer() {
if (renderer == null) {
setRendererClass(IGVFeatureRenderer.class);
}
return renderer;
}
/**
* Return a string for popup text.
*
* @param chr
* @param position in genomic coordinates
* @param y - pixel position in panel coordinates (i.e. not track coordinates)
* @return
*/
public String getValueStringAt(String chr, double position, int y, ReferenceFrame frame) {
if (showFeatures) {
List<Feature> allFeatures = getAllFeatureAt(position, y, frame);
if (allFeatures == null) {
return null;
}
StringBuffer buf = new StringBuffer();
boolean firstFeature = true;
int maxNumber = 10;
int n = 1;
for (Feature feature : allFeatures) {
if (feature != null && feature instanceof IGVFeature) {
if (!firstFeature) {
buf.append("<br/>
}
IGVFeature igvFeature = (IGVFeature) feature;
String vs = igvFeature.getValueString(position, null);
buf.append(vs);
if (IGV.getInstance().isShowDetailsOnClick()) {
// URL
String url = getFeatureURL(igvFeature);
if (url != null) {
buf.append("<br/><a href=\"" + url + "\">" + url + "</a>");
}
}
firstFeature = false;
if (n > maxNumber) {
buf.append("...");
break;
}
}
n++;
}
return buf.toString();
} else {
int zoom = Math.max(0, frame.getZoom());
if (source == null) {
return null;
}
List<LocusScore> scores = source.getCoverageScores(chr, (int) position - 10, (int) position + 10, zoom);
if (scores == null) {
return "";
} else {
// give a +/- 2 pixel buffer, otherwise very narrow features will be missed.
double bpPerPixel = frame.getScale();
int minWidth = (int) (2 * bpPerPixel);
LocusScore score = (LocusScore) FeatureUtils.getFeatureAt(position, minWidth, scores);
return score == null ? null : "Mean count: " + score.getScore();
}
}
}
private String getFeatureURL(IGVFeature igvFeature) {
String url = igvFeature.getURL();
if (url == null) {
String trackURL = getUrl();
if (trackURL != null && igvFeature.getIdentifier() != null) {
String encodedID = StringUtils.encodeURL(igvFeature.getIdentifier());
url = trackURL.replaceAll("\\$\\$", encodedID);
}
}
return url;
}
/**
* Get all features which overlap the specified locus
*
* @return
*/
public List<Feature> getFeatures(String chr, int start, int end) {
List<Feature> features = new ArrayList<Feature>();
try {
Iterator<Feature> iter = source.getFeatures(chr, start, end);
while (iter.hasNext()) {
features.add(iter.next());
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return features;
}
/**
* @param position in genomic coordinates
* @param y pixel location in panel coordinates. // TODO offset by track origin before getting here?
* @param frame
* @return
*/
private List<Feature> getAllFeatureAt(double position, int y, ReferenceFrame frame) {
// Determine the level number (for expanded tracks)
int featureRow = getFeatureRow(y);
return getFeaturesAtPositionInFeatureRow(position, featureRow, frame);
}
/**
* Determine which row the user clicked in and return the appropriate feature
*
* @param y
* @return
*/
private int getFeatureRow(int y) {
// Determine the level number (for expanded tracks).
int featureRow = 0;
if (levelRects != null) {
for (int i = 0; i < levelRects.size(); i++) {
Rectangle r = levelRects.get(i);
if ((y >= r.y) && (y <= r.getMaxY())) {
featureRow = i;
break;
}
}
}
return featureRow;
}
/**
* Knowing the feature row, figure out which feature is at position position. If not expanded,
* featureRow is ignored
*
* @param position
* @param featureRow
* @param frame
* @return
*/
public List<Feature> getFeaturesAtPositionInFeatureRow(double position, int featureRow, ReferenceFrame frame) {
PackedFeatures<IGVFeature> packedFeatures = packedFeaturesMap.get(frame.getName());
if (packedFeatures == null) {
return null;
}
int nLevels = packedFeatures.getRowCount();
List<IGVFeature> possFeatures = null;
if ((nLevels > 1) && (featureRow < nLevels)) {
possFeatures = packedFeatures.getRows().get(featureRow).getFeatures();
} else {
possFeatures = packedFeatures.getFeatures();
}
List<Feature> featureList = null;
if (possFeatures != null) {
// give a 2 pixel window, otherwise very narrow features will be missed.
double bpPerPixel = frame.getScale();
double minWidth = MINIMUM_FEATURE_SPACING * bpPerPixel;
int maxFeatureLength = packedFeatures.getMaxFeatureLength();
featureList = FeatureUtils.getAllFeaturesAt(position, maxFeatureLength, minWidth, possFeatures);
}
return featureList;
}
public WindowFunction getWindowFunction() {
return WindowFunction.count;
}
@Override
public boolean handleDataClick(TrackClickEvent te) {
MouseEvent e = te.getMouseEvent();
//Selection of an expanded feature row
if (areFeaturesStacked()) {
if (levelRects != null) {
for (int i = 0; i < levelRects.size(); i++) {
Rectangle rect = levelRects.get(i);
if (rect.contains(e.getPoint())) {
if (i == selectedFeatureRowIndex)
setSelectedFeatureRowIndex(FeatureTrack.NO_FEATURE_ROW_SELECTED);
else {
//make this track selected
setSelected(true);
//select the appropriate row
setSelectedFeatureRowIndex(i);
}
IGV.getInstance().doRefresh();
break;
}
}
}
}
//For feature selection
selectedFeature = null;
Feature f = getFeatureAtMousePosition(te);
if (f != null && f instanceof IGVFeature) {
IGVFeature igvFeature = (IGVFeature) f;
if (selectedFeature != null && igvFeature.contains(selectedFeature) && (selectedFeature.contains(igvFeature))) {
//If something already selected, then if it's the same as this feature, deselect, otherwise, select
//this feature.
//todo: contains() might not do everything I want it to.
selectedFeature = null;
} else {
//if nothing already selected, or something else selected,
// select this feature
selectedFeature = igvFeature;
}
if (IGV.getInstance().isShowDetailsOnClick()) {
openTooltipWindow(te);
} else {
String url = getFeatureURL(igvFeature);
if (url != null) {
try {
BrowserLauncher.openURL(url);
} catch (IOException e1) {
log.error("Error launching url: " + url);
}
e.consume();
return true;
}
}
}
return false;
}
public Feature getFeatureAtMousePosition(TrackClickEvent te) {
MouseEvent e = te.getMouseEvent();
final ReferenceFrame referenceFrame = te.getFrame();
if (referenceFrame != null) {
double location = referenceFrame.getChromosomePosition(e.getX());
List<Feature> features = getAllFeatureAt(location, e.getY(), referenceFrame);
return (features != null && features.size() > 0) ? features.get(0) : null;
} else {
return null;
}
}
/**
* Required by the interface, really not applicable to feature tracks
*/
public boolean isLogNormalized() {
return true;
}
public void overlay(RenderContext context, Rectangle rect) {
renderFeatures(context, rect);
}
@Override
public void setDisplayMode(DisplayMode mode) {
// Explicity setting the display mode overrides the automatic switch
lastFeatureMode = null;
super.setDisplayMode(mode);
}
@Override
public void preload(RenderContext context) {
ReferenceFrame frame = context.getReferenceFrame();
PackedFeatures packedFeatures = packedFeaturesMap.get(frame.getName());
String chr = context.getChr();
int start = (int) context.getOrigin();
int end = (int) context.getEndLocation();
if (packedFeatures == null || !packedFeatures.containsInterval(chr, start, end)) {
try {
context.getReferenceFrame().getEventBus().unregister(FeatureTrack.this);
} catch (IllegalArgumentException e) {
//Don't care
}
loadFeatures(frame.getChrName(), (int) frame.getOrigin(), (int) frame.getEnd(), context);
}
}
@Override
public void render(RenderContext context, Rectangle rect) {
Rectangle renderRect = new Rectangle(rect);
renderRect.y = renderRect.y + margin;
renderRect.height -= margin;
showFeatures = isShowFeatures(context);
if (showFeatures) {
if (lastFeatureMode != null) {
super.setDisplayMode(lastFeatureMode);
lastFeatureMode = null;
}
renderFeatures(context, renderRect);
} else {
if (getDisplayMode() != DisplayMode.COLLAPSED) {
// An ugly hack, but we want to prevent this for vcf tracks
if (!(this instanceof VariantTrack)) {
lastFeatureMode = getDisplayMode();
super.setDisplayMode(DisplayMode.COLLAPSED);
}
}
renderCoverage(context, renderRect);
}
if (FeatureTrack.drawBorder) {
Graphics2D borderGraphics = context.getGraphic2DForColor(UIConstants.TRACK_BORDER_GRAY);
borderGraphics.drawLine(rect.x, rect.y, rect.x + rect.width, rect.y);
//TODO Fix height for variant track
borderGraphics.drawLine(rect.x, rect.y + rect.height, rect.x + rect.width, rect.y + rect.height);
}
}
protected boolean isShowFeatures(RenderContext context) {
double windowSize = context.getEndLocation() - context.getOrigin();
int vw = getVisibilityWindow();
return (vw <= 0 && !context.getChr().equals(Globals.CHR_ALL) ||
windowSize <= vw && !context.getChr().equals(Globals.CHR_ALL));
}
protected void renderCoverage(RenderContext context, Rectangle inputRect) {
if (source == null) {
return;
}
List<LocusScore> scores = source.getCoverageScores(context.getChr(), (int) context.getOrigin(),
(int) context.getEndLocation(), context.getZoom());
if (scores == null) {
Graphics2D g = context.getGraphic2DForColor(Color.gray);
Rectangle textRect = new Rectangle(inputRect);
// Keep text near the top of the track rectangle
textRect.height = Math.min(inputRect.height, 20);
String message = context.getChr().equals(Globals.CHR_ALL) ? "Zoom in to see features." :
"Zoom in to see features, or right-click to increase Feature Visibility Window.";
GraphicUtils.drawCenteredText(message, textRect, g);
} else {
float max = getMaxEstimate(scores);
ContinuousColorScale cs = getColorScale();
if (cs != null) {
cs.setPosEnd(max);
}
setDataRange(new DataRange(0, 0, max));
coverageRenderer.render(scores, context, inputRect, this);
}
}
private float getMaxEstimate(List<LocusScore> scores) {
float max = 0;
int n = Math.min(200, scores.size());
for (int i = 0; i < n; i++) {
max = Math.max(max, scores.get(i).getScore());
}
return max;
}
/**
* Render features in the given input rectangle.
* @param context
* @param inputRect
*/
protected void renderFeatures(RenderContext context, Rectangle inputRect) {
if (featuresLoading || fatalLoadError) {
return;
}
if (log.isTraceEnabled()) {
String msg = String.format("renderFeatures: %s frame: %s", getName(), context.getReferenceFrame().getName());
log.trace(msg);
}
//Attempt to load the relevant data. Note that there is no guarantee
//the data will be loaded once preload exits, as loading may be asynchronous
preload(context);
PackedFeatures packedFeatures = packedFeaturesMap.get(context.getReferenceFrame().getName());
if (packedFeatures == null || !packedFeatures.containsInterval(context.getChr(), (int) context.getOrigin(), (int) context.getEndLocation() + 1)) {
if(packedFeatures == null) return;
}
try {
renderFeatureImpl(context, inputRect, packedFeatures);
} catch (TribbleException e) {
log.error("Tribble error", e);
//Error loading features. We'll let the user decide if this is "fatal" or not.
if (!fatalLoadError) {
fatalLoadError = true;
boolean unload = MessageUtils.confirm("<html> Error loading features: " + e.getMessage() +
"<br>Unload track " + getName() + "?");
if (unload) {
Collection<Track> tmp = Arrays.asList((Track) this);
IGV.getInstance().removeTracks(tmp);
IGV.getInstance().doRefresh();
} else {
fatalLoadError = false;
}
}
}
}
protected void renderFeatureImpl(RenderContext context, Rectangle inputRect, PackedFeatures packedFeatures) {
FeatureRenderer renderer = getRenderer();
if (areFeaturesStacked()) {
List<PackedFeatures.FeatureRow> rows = packedFeatures.getRows();
if (rows != null && rows.size() > 0) {
int nLevels = rows.size();
synchronized (levelRects) {
levelRects.clear();
// Divide rectangle into equal height levels
double h = inputRect.getHeight() / nLevels;
Rectangle rect = new Rectangle(inputRect.x, inputRect.y, inputRect.width, (int) h);
int i = 0;
renderer.reset();
for (PackedFeatures.FeatureRow row : rows) {
levelRects.add(new Rectangle(rect));
renderer.render(row.features, context, levelRects.get(i), this);
if (selectedFeatureRowIndex == i) {
Graphics2D fontGraphics = context.getGraphic2DForColor(SELECTED_FEATURE_ROW_COLOR);
fontGraphics.fillRect(rect.x, rect.y, rect.width, rect.height);
}
rect.y += h;
i++;
}
}
}
} else {
List<IGVFeature> features = packedFeatures.getFeatures();
if (features != null) {
renderer.render(features, context, inputRect, this);
}
}
}
/**
* Loads and segregates features into rows such that they do not overlap. Loading is done in a background
* thread.
*
* @param chr
* @param start
* @param end
*/
protected synchronized void loadFeatures(final String chr, final int start, final int end, final RenderContext context) {
// TODO -- improve or remove the need for this test. We know that FeatureCollectionSource has all the data
// in memory, and can by run synchronously
boolean aSync = !(source instanceof FeatureCollectionSource);
NamedRunnable runnable = new NamedRunnable() {
public void run() {
try {
featuresLoading = true;
if(log.isTraceEnabled()){
log.trace(String.format("Loading features: %s:%d-%d", chr, start, end));
}
int maxEnd = end;
Genome genome = GenomeManager.getInstance().getCurrentGenome();
if (genome != null) {
Chromosome c = genome.getChromosome(chr);
if (c != null) maxEnd = Math.max(c.getLength(), end);
}
int delta = (end - start) / 2;
int expandedStart = start - delta;
int expandedEnd = end + delta;
Iterator<Feature> iter = source.getFeatures(chr, expandedStart, expandedEnd);
if (iter == null) {
PackedFeatures pf = new PackedFeatures(chr, expandedStart, expandedEnd);
packedFeaturesMap.put(context.getReferenceFrame().getName(), pf);
} else {
//dhmay putting a switch in for different packing behavior in splice junction tracks.
//This should probably be switched somewhere else, but that would require a big refactor.
PackedFeatures pf = new PackedFeatures(chr, expandedStart, expandedEnd, iter, getName());
packedFeaturesMap.put(context.getReferenceFrame().getName(), pf);
}
//Now that features are loaded, we may need to repaint
//to accommodate.
context.getReferenceFrame().getEventBus().post(new DataLoadedEvent(context));
} catch (Exception e) {
// Mark the interval with an empty feature list to prevent an endless loop of load
// attempts.
PackedFeatures pf = new PackedFeatures(chr, start, end);
packedFeaturesMap.put(context.getReferenceFrame().getName(), pf);
String msg = "Error loading features for interval: " + chr + ":" + start + "-" + end + " <br>" + e.toString();
MessageUtils.showMessage(msg);
log.error(msg, e);
} finally {
featuresLoading = false;
}
}
public String getName() {
return "Load features: " + FeatureTrack.this.getName();
}
};
if (aSync) {
context.getReferenceFrame().getEventBus().register(FeatureTrack.this);
LongRunningTask.submit(runnable);
} else {
runnable.run();
}
}
/**
* Called after features are finished loading, which can be asynchronous
* @param event
*/
@Subscribe
private void receiveDataLoaded(DataLoadedEvent event){
if (IGV.hasInstance()) {
// TODO -- WHY IS THIS HERE????
//TODO Assuming this is necessary, there can be many data loaded events in succession,
//don't want to layout for each one
IGV.getInstance().layoutMainPanel();
}
JComponent panel = event.context.getPanel();
if(panel != null) panel.repaint();
}
/**
* Return the nextLine or previous feature relative to the center location.
* TODO -- investigate delegating this method to FeatureSource, where it might be possible to simplify the implementation
*
* @param chr
* @param center
* @param forward
* @return
* @throws IOException
*/
public Feature nextFeature(String chr, double center, boolean forward, ReferenceFrame frame) throws IOException {
Feature f = null;
boolean canScroll = (forward && !frame.windowAtEnd()) || (!forward && frame.getOrigin() > 0);
PackedFeatures packedFeatures = packedFeaturesMap.get(frame.getName());
if (packedFeatures != null && packedFeatures.containsInterval(chr, (int) center - 1, (int) center + 1)) {
if (packedFeatures.getFeatures().size() > 0 && canScroll) {
f = (forward ? FeatureUtils.getFeatureAfter(center + 1, packedFeatures.getFeatures()) :
FeatureUtils.getFeatureBefore(center - 1, packedFeatures.getFeatures()));
}
if (f == null) {
FeatureSource rawSource = source;
if (source instanceof CachingFeatureSource) {
rawSource = ((CachingFeatureSource) source).getSource();
}
if (rawSource instanceof MotifFinderSource || rawSource instanceof PluginFeatureSource) {
FeatureTrackUtils.nextFeatureSearch(source, chr, packedFeatures.getStart(), packedFeatures.getEnd(),
forward, new FeatureSearcher.GotoFeatureHandler());
} else {
f = FeatureTrackUtils.nextFeature(source, chr, packedFeatures.getStart(), packedFeatures.getEnd(), forward);
}
}
}
return f;
}
public void setVisibilityWindow(int windowSize) {
super.setVisibilityWindow(windowSize);
packedFeaturesMap.clear();
source.setFeatureWindowSize(visibilityWindow);
}
public int getSelectedFeatureRowIndex() {
return selectedFeatureRowIndex;
}
public void setSelectedFeatureRowIndex(int selectedFeatureRowIndex) {
this.selectedFeatureRowIndex = selectedFeatureRowIndex;
}
public IGVFeature getSelectedFeature() {
return selectedFeature;
}
public static boolean isDrawBorder() {
return drawBorder;
}
public static void setDrawBorder(boolean drawBorder) {
FeatureTrack.drawBorder = drawBorder;
}
public boolean isAlternateExonColor() {
return alternateExonColor;
}
@SubtlyImportant
private static FeatureTrack getNextTrack() {
FeatureTrack out = (FeatureTrack) IGVSessionReader.getNextTrack();
if (out == null) out = new FeatureTrack((String) null, null);
return out;
}
@Override
public void restorePersistentState(Node node) throws JAXBException {
super.restorePersistentState(node);
if (node.hasChildNodes()) {
NodeList childNodes = node.getChildNodes();
for (int ii = 0; ii < childNodes.getLength(); ii++) {
Node child = childNodes.item(ii);
String nodeName = child.getNodeName();
if (nodeName.contains("#text")) continue;
if (nodeName.equalsIgnoreCase(PLUGIN_SOURCE)) {
source = IGVSessionReader.getJAXBContext().createUnmarshaller().unmarshal(child, PluginFeatureSource.class).getValue();
} else if (nodeName.equalsIgnoreCase(SEQUENCE_MATCH_SOURCE)) {
FeatureSource rawSource = IGVSessionReader.getJAXBContext().createUnmarshaller().unmarshal(child, MotifFinderSource.class).getValue();
source = new CachingFeatureSource(rawSource);
} else {
try {
FeatureSource newSource = (FeatureSource) IGVSessionReader.getJAXBContext().createUnmarshaller().unmarshal(child, Class.forName(nodeName)).getValue();
source = newSource;
} catch (Exception e) {
//Lots can go wrong, it just means this isn't a FeatureSource
//Probably not an error
}
}
}
}
}
/**
* @param m
* @param trackElement
* @throws JAXBException
*/
public void marshalSource(Marshaller m, Element trackElement) throws JAXBException {
if (source == null) return;
FeatureSource rawSource = source;
if (rawSource instanceof CachingFeatureSource) {
rawSource = ((CachingFeatureSource) rawSource).getSource();
}
//We apply special treatment for a few classes
if (rawSource instanceof PluginSource) {
JAXBElement element = new JAXBElement<PluginSource>(new QName("", PLUGIN_SOURCE), PluginSource.class,
(PluginSource) rawSource);
m.marshal(element, trackElement);
} else if (rawSource instanceof MotifFinderSource) {
JAXBElement element = new JAXBElement<MotifFinderSource>(new QName("", SEQUENCE_MATCH_SOURCE), MotifFinderSource.class,
(MotifFinderSource) rawSource);
m.marshal(element, trackElement);
} else {
//Users can write their own FeatureSources, we tag with the fully qualified class name
Class<? extends FeatureSource> srcClazz = rawSource.getClass();
JAXBElement element = new JAXBElement(new QName("", srcClazz.getName()), srcClazz, rawSource);
try {
m.marshal(element, trackElement);
} catch (MarshalException e) {
//This happens if the source is not marshallable
//Many of our classes can't, and that's not an error
}
}
}
/**
* This method exists for Plugin tracks. When restoring a session there is no guarantee of track
* order, so arguments referring to other tracks may fail to resolve. We update those references
* here after all tracks have been processed
*
* @param allTracks
*/
public void updateTrackReferences(List<Track> allTracks) {
if (source instanceof PluginSource) {
((PluginSource) source).updateTrackReferences(allTracks);
}
}
}
|
// checkstyle: Checks Java source code for adherence to a set of rules.
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.puppycrawl.tools.checkstyle;
import java.util.HashMap;
import java.util.Map;
import org.apache.regexp.RE;
import org.apache.regexp.RESyntaxException;
/**
* Contains utility methods.
*
* @author <a href="mailto:oliver@puppycrawl.com">Oliver Burn</a>
* @version 1.0
*/
final class Utils
{
/** Map of all created regular expressions **/
private static final Map CREATED_RES = new HashMap();
/** stop instances being created **/
private Utils()
{
}
/**
* Returns whether the specified string contains only whitespace up to the
* specified index.
*
* @param aIndex index to check up to
* @param aLine the line to check
* @return whether there is only whitespace
*/
static boolean whitespaceBefore(int aIndex, String aLine)
{
for (int i = 0; i < aIndex; i++) {
if (!Character.isWhitespace(aLine.charAt(i))) {
return false;
}
}
return true;
}
/**
* Returns the length of a string ignoring all trailing whitespace. It is a
* pity that there is not a trim() like method that only removed the
* trailing whitespace.
* @param aLine the string to process
* @return the length of the string ignoring all trailing whitespace
**/
static int lengthMinusTrailingWhitespace(String aLine)
{
int len = aLine.length();
for (int i = len - 1; i >= 0; i
if (!Character.isWhitespace(aLine.charAt(i))) {
break;
}
len
}
return len;
}
/**
* Returns the length of a String prefix with tabs expanded.
* Each tab is counted as the number of characters is takes to
* jump to the next tab stop.
* @param aString the input String
* @param aToIdx index in aString (exclusive) where the calculation stops
* @param aTabWidth the distance betweeen tab stop position.
* @return the length of aString.substring(0, aToIdx) with tabs expanded.
*/
static int lengthExpandedTabs(String aString, int aToIdx, int aTabWidth)
{
int len = 0;
for (int idx = 0; idx < aToIdx; idx++) {
if (aString.charAt(idx) == '\t') {
len = (len / aTabWidth + 1) * aTabWidth;
}
else {
len++;
}
}
return len;
}
/**
* This is a factory method to return an RE object for the specified
* regular expression. This method is not MT safe, but neither are the
* returned RE objects.
* @return an RE object for the supplied pattern
* @param aPattern the regular expression pattern
* @throws RESyntaxException an invalid pattern was supplied
**/
static RE getRE(String aPattern)
throws RESyntaxException
{
RE retVal = (RE) CREATED_RES.get(aPattern);
if (retVal == null) {
retVal = new RE(aPattern);
CREATED_RES.put(aPattern, retVal);
}
return retVal;
}
/**
* @return whether a specified class is a runtime exception
* @param aName name of the class to check. If the class cannot be found
* and is not fully qualified, then "java.lang." is appended.
* @param aLoader the loader to load the class with
* @throws ClassNotFoundException if unable to load the specified class
*/
public static boolean isRuntimeException(String aName, ClassLoader aLoader)
throws ClassNotFoundException
{
// TODO: Need to remove the hack checking for java.lang. prefix, and
// instead use the logic Lars introduced for finding instantiations.
// This will also require putting @throws, @see, @link into the logic
// for finding unused imports.
// Logic should be:
// o Try class as is
// o See if matches any explicit imports
// o See if matched by any .* imports
// o See if matched with "java.lang."
Class c;
try {
// The next line will load the class using the specified class
// loader. The magic is having the "false" parameter. This means the
// class will not be initialised. Very, very important.
c = Class.forName(aName, false, aLoader);
}
catch (ClassNotFoundException e) {
if (aName.indexOf('.') == -1) {
c = Class.forName("java.lang." + aName, false, aLoader);
}
else {
throw e;
}
}
return RuntimeException.class.isAssignableFrom(c);
}
}
|
package org.erhsroboticsclub.robo2013;
import edu.wpi.first.wpilibj.RobotDrive;
import edu.wpi.first.wpilibj.networktables2.util.List;
import java.util.Hashtable;
import org.erhsroboticsclub.robo2013.utilities.MathX;
import org.erhsroboticsclub.robo2013.utilities.Messenger;
import org.erhsroboticsclub.robo2013.utilities.PIDControllerX;
import org.erhsroboticsclub.robo2013.utilities.Target;
public class AI {
private RobotDrive drive;
private Messenger msg;
private Com com;
private PIDControllerX pid;
private LinearAccelerator launcher;
public AI(RobotDrive drive, LinearAccelerator launcher) {
this.drive = drive;
this.launcher = launcher;
pid = new PIDControllerX(1, 0, 10);
com = new Com("http://10.0.53.23");
msg = new Messenger();
}
private List getAllTargets() {
Hashtable table = com.getValues("crio");
if (table == null) {
return null;
}
return com.parseTargets((String) table.get("targets"));
}
public Target getTopTarget() {
List targets = getAllTargets();
if (targets == null) {
return null;
}
Target high = (Target) targets.get(0);
for (int i = 0; i < targets.size(); i++) {
Target t = (Target) targets.get(i);
if (t.height > high.height) {
high = t;
}
}
return high;
}
public void turnToTarget(int t) {
pid.setSetpoint(320);
Target target = new Target(0, 0, 0);
int target_fails = 0;
int com_fails = 0;
do {
List list = getAllTargets();
if (list != null) {
if (t > list.size() - 1) {
msg.printLn("No target '" + t + "'");
target_fails += 1;
if (target_fails >= 500) {
msg.printLn("Giving up...");
break;
} else {
msg.printLn("Retrying...");
}
}
target = (Target) list.get(t);
double correction = pid.doPID(target.x);
drive.tankDrive(correction, -correction);
} else {
msg.printLn("BeagleBoard not responding!");
com_fails += 1;
if (com_fails >= 500) {
msg.printLn("Giving up...");
break;
} else {
msg.printLn("Retrying...");
}
}
} while (!MathX.isWithin(target.x, 320, 7));
pid.reset();
}
public void autoAimLauncher() {
// ToDo: Auto aim launcher angle
}
}
|
package com.shc.webgl4j.client;
import com.google.gwt.core.client.JavaScriptObject;
import java.util.HashMap;
import java.util.Map;
/**
* A class used to convert WebGL objects (WebGLTexture, WebGLBuffer etc.,) to integers just like the desktop OpenGL.
* This class is package-private since there is no direct use of this class for users. It is simply expected to work in
* the background. That is the reason this class is declared as package private.
*
* @author Sri Harsha Chilakapati
*/
final class WebGLObjectMap
{
private final static Map<WebGLContext, WebGLObjectMap> contexts = new HashMap<>();
// WebGL10 objects
private final Map<Integer, JavaScriptObject> shaders = new HashMap<>();
private final Map<Integer, JavaScriptObject> buffers = new HashMap<>();
private final Map<Integer, JavaScriptObject> programs = new HashMap<>();
private final Map<Integer, JavaScriptObject> textures = new HashMap<>();
private final Map<Integer, JavaScriptObject> frameBuffers = new HashMap<>();
private final Map<Integer, JavaScriptObject> renderBuffers = new HashMap<>();
private final Map<Integer, Map<Integer, JavaScriptObject>> uniforms = new HashMap<>();
// WebGL20 objects
private final Map<Integer, JavaScriptObject> queries = new HashMap<>();
private final Map<Integer, JavaScriptObject> samplers = new HashMap<>();
private final Map<Integer, JavaScriptObject> syncs = new HashMap<>();
private final Map<Integer, JavaScriptObject> transformFeedbacks = new HashMap<>();
private final Map<Integer, JavaScriptObject> vertexArrayObjects = new HashMap<>();
// Field to store the current program
int currentProgram = 0;
// Fields for last generated IDs of WebGL objects
private int lastShaderID = 0;
private int lastBufferID = 0;
private int lastProgramID = 0;
private int lastTextureID = 0;
private int lastFramebufferID = 0;
private int lastRenderbufferID = 0;
private int lastUniformID = 0;
private int lastQueryID = 0;
private int lastSamplerID = 0;
private int lastSyncID = 0;
private int lastTransformFeedbackID = 0;
private int lastVertexArrayObjectID = 0;
private WebGLObjectMap()
{
}
public static WebGLObjectMap get()
{
WebGLObjectMap map = contexts.get(WebGLContext.getCurrent());
if (map == null)
{
map = new WebGLObjectMap();
contexts.put(WebGLContext.getCurrent(), map);
}
return map;
}
int createShader(JavaScriptObject shader)
{
if (shader == null)
return 0;
if (shaders.values().contains(shader))
{
for (int key : shaders.keySet())
if (shaders.get(key) == shader)
return key;
}
shaders.put(++lastShaderID, shader);
return lastShaderID;
}
JavaScriptObject toShader(int shaderID)
{
return shaders.get(shaderID);
}
int createBuffer(JavaScriptObject buffer)
{
if (buffer == null)
return 0;
if (buffers.values().contains(buffer))
{
for (int key : buffers.keySet())
if (buffers.get(key) == buffer)
return key;
}
buffers.put(++lastBufferID, buffer);
return lastBufferID;
}
JavaScriptObject toBuffer(int bufferID)
{
return buffers.get(bufferID);
}
int createProgram(JavaScriptObject program)
{
if (program == null)
return 0;
if (programs.values().contains(program))
{
for (int key : programs.keySet())
if (programs.get(key) == program)
return key;
}
programs.put(++lastProgramID, program);
return lastProgramID;
}
JavaScriptObject toProgram(int programID)
{
return programs.get(programID);
}
int createTexture(JavaScriptObject texture)
{
if (texture == null)
return 0;
if (textures.values().contains(texture))
{
for (int key : textures.keySet())
if (textures.get(key) == texture)
return key;
}
textures.put(++lastTextureID, texture);
return lastTextureID;
}
JavaScriptObject toTexture(int textureID)
{
return textures.get(textureID);
}
int createFramebuffer(JavaScriptObject frameBuffer)
{
if (frameBuffer == null)
return 0;
if (frameBuffers.values().contains(frameBuffer))
{
for (int key : frameBuffers.keySet())
if (frameBuffers.get(key) == frameBuffer)
return key;
}
frameBuffers.put(++lastFramebufferID, frameBuffer);
return lastFramebufferID;
}
JavaScriptObject toFramebuffer(int frameBuffer)
{
return frameBuffers.get(frameBuffer);
}
int createRenderBuffer(JavaScriptObject renderBuffer)
{
if (renderBuffer == null)
return 0;
if (renderBuffers.values().contains(renderBuffer))
{
for (int key : renderBuffers.keySet())
if (renderBuffers.get(key) == renderBuffer)
return key;
}
renderBuffers.put(++lastRenderbufferID, renderBuffer);
return lastRenderbufferID;
}
JavaScriptObject toRenderBuffer(int renderBuffer)
{
return renderBuffers.get(renderBuffer);
}
int createUniform(JavaScriptObject uniform)
{
if (uniform == null)
return -1;
Map<Integer, JavaScriptObject> progUniforms = uniforms.get(currentProgram);
if (progUniforms == null)
{
progUniforms = new HashMap<>();
uniforms.put(currentProgram, progUniforms);
}
if (progUniforms.values().contains(uniform))
{
for (int key : progUniforms.keySet())
if (progUniforms.get(key) == uniform)
return key;
}
progUniforms.put(++lastUniformID, uniform);
return lastUniformID;
}
JavaScriptObject toUniform(int programID, int uniform)
{
return uniform == -1 ? null : uniforms.get(programID).get(uniform);
}
JavaScriptObject toUniform(int uniform)
{
return toUniform(currentProgram, uniform);
}
void deleteShader(int shader)
{
if (shader != 0)
shaders.remove(shader);
}
void deleteBuffer(int buffer)
{
if (buffer != 0)
buffers.remove(buffer);
}
void deleteProgram(int program)
{
if (program != 0)
{
programs.remove(program);
uniforms.remove(program);
}
}
void deleteTexture(int texture)
{
if (texture != 0)
textures.remove(texture);
}
void deleteFramebuffer(int frameBuffer)
{
if (frameBuffer != 0)
frameBuffers.remove(frameBuffer);
}
void deleteRenderBuffer(int renderBuffer)
{
if (renderBuffer != 0)
renderBuffers.remove(renderBuffer);
}
int createQuery(JavaScriptObject query)
{
if (query == null)
return 0;
if (queries.values().contains(query))
{
for (int key : queries.keySet())
if (queries.get(key) == query)
return key;
}
queries.put(++lastQueryID, query);
return lastQueryID;
}
JavaScriptObject toQuery(int query)
{
return queries.get(query);
}
int createSampler(JavaScriptObject sampler)
{
if (sampler == null)
return 0;
if (samplers.values().contains(sampler))
{
for (int key : samplers.keySet())
if (samplers.get(key) == sampler)
return key;
}
samplers.put(++lastSamplerID, sampler);
return lastSamplerID;
}
JavaScriptObject toSampler(int sampler)
{
return samplers.get(sampler);
}
int createSync(JavaScriptObject sync)
{
if (sync == null)
return 0;
if (syncs.values().contains(sync))
{
for (int key : syncs.keySet())
if (syncs.get(key) == sync)
return key;
}
syncs.put(++lastSyncID, sync);
return lastSyncID;
}
JavaScriptObject toSync(int sync)
{
return syncs.get(sync);
}
int createTransformFeedback(JavaScriptObject transformFeedback)
{
if (transformFeedback == null)
return 0;
if (transformFeedbacks.values().contains(transformFeedback))
{
for (int key : transformFeedbacks.keySet())
if (transformFeedbacks.get(key) == transformFeedback)
return key;
}
transformFeedbacks.put(++lastTransformFeedbackID, transformFeedback);
return lastTransformFeedbackID;
}
JavaScriptObject toTransformFeedback(int transformFeedback)
{
return transformFeedbacks.get(transformFeedback);
}
int createVertexArrayObject(JavaScriptObject vertexArrayObject)
{
if (vertexArrayObject == null)
return 0;
if (vertexArrayObjects.values().contains(vertexArrayObject))
{
for (int key : vertexArrayObjects.keySet())
if (vertexArrayObjects.get(key) == vertexArrayObject)
return key;
}
vertexArrayObjects.put(++lastVertexArrayObjectID, vertexArrayObject);
return lastVertexArrayObjectID;
}
JavaScriptObject toVertexArrayObject(int vertexArrayObject)
{
return vertexArrayObjects.get(vertexArrayObject);
}
void deleteQuery(int query)
{
if (query != 0)
queries.remove(query);
}
void deleteSampler(int sampler)
{
if (sampler != 0)
samplers.remove(sampler);
}
void deleteSync(int sync)
{
if (sync != 0)
syncs.remove(sync);
}
void deleteTransformFeedback(int transformFeedback)
{
if (transformFeedback != 0)
transformFeedbacks.remove(transformFeedback);
}
void deleteVertexArrayObject(int vertexArrayObject)
{
if (vertexArrayObject != 0)
vertexArrayObjects.remove(vertexArrayObject);
}
}
|
package replicant.spy.tools;
import elemental2.dom.DomGlobal;
import javax.annotation.Nonnull;
import org.realityforge.anodoc.Unsupported;
import replicant.AreaOfInterest;
import replicant.FilterUtil;
import replicant.Subscription;
import replicant.spy.AreaOfInterestCreatedEvent;
import replicant.spy.AreaOfInterestDisposedEvent;
import replicant.spy.AreaOfInterestFilterUpdatedEvent;
import replicant.spy.AreaOfInterestStatusUpdatedEvent;
import replicant.spy.ConnectFailureEvent;
import replicant.spy.ConnectedEvent;
import replicant.spy.DisconnectedEvent;
import replicant.spy.SubscriptionCreatedEvent;
import replicant.spy.SubscriptionDisposedEvent;
import replicant.spy.SubscriptionOrphanedEvent;
/**
* A SpyEventHandler that prints spy events to the tools console.
* The events are colored to make them easy to digest. This class is designed to be easy to sub-class.
*/
@Unsupported( "This class relies on unstable spy API and will likely evolve as the api evolves" )
public class ConsoleSpyEventProcessor
extends AbstractSpyEventProcessor
{
@CssRules
private static final String ENTITY_COLOR = "color: #CF8A3B; font-weight: normal;";
@CssRules
private static final String CONNECTOR_COLOR = "color: #F5A402; font-weight: normal;";
@CssRules
private static final String SUBSCRIPTION_COLOR = "color: #0FA13B; font-weight: normal;";
@CssRules
private static final String AREA_OF_INTEREST_COLOR = "color: #006AEB; font-weight: normal;";
@CssRules
private static final String ERROR_COLOR = "color: #A10001; font-weight: normal;";
/**
* Create the processor.
*/
public ConsoleSpyEventProcessor()
{
on( AreaOfInterestCreatedEvent.class, this::onAreaOfInterestCreated );
on( AreaOfInterestFilterUpdatedEvent.class, this::onAreaOfInterestFilterUpdated );
on( AreaOfInterestStatusUpdatedEvent.class, this::onAreaOfInterestStatusUpdated );
on( AreaOfInterestDisposedEvent.class, this::onAreaOfInterestDisposed );
on( SubscriptionCreatedEvent.class, this::onSubscriptionCreated );
on( SubscriptionDisposedEvent.class, this::onSubscriptionDisposed );
on( SubscriptionOrphanedEvent.class, this::onSubscriptionOrphaned );
on( ConnectedEvent.class, this::onConnected );
on( ConnectFailureEvent.class, this::onConnectFailure );
on( DisconnectedEvent.class, this::onDisconnected );
}
/**
* Handle the ConnectedEvent.
*
* @param e the event.
*/
private void onConnected( @Nonnull final ConnectedEvent e )
{
log( "%cConnector Connected " + e.getSystemType().getSimpleName(), CONNECTOR_COLOR );
}
/**
* Handle the ConnectFailureEvent.
*
* @param e the event.
*/
private void onConnectFailure( @Nonnull final ConnectFailureEvent e )
{
log( "%cConnector Connect Failed " + e.getSystemType().getSimpleName() + " Error: " + e.getError(), ERROR_COLOR );
}
/**
* Handle the DisconnectedEvent.
*
* @param e the event.
*/
private void onDisconnected( @Nonnull final DisconnectedEvent e )
{
log( "%cConnector Discnnected " + e.getSystemType().getSimpleName(), CONNECTOR_COLOR );
}
/**
* Handle the AreaOfInterestCreatedEvent.
*
* @param e the event.
*/
protected void onAreaOfInterestCreated( @Nonnull final AreaOfInterestCreatedEvent e )
{
final AreaOfInterest areaOfInterest = e.getAreaOfInterest();
final Object filter = areaOfInterest.getFilter();
final String filterString = null == filter ? "" : " - " + FilterUtil.filterToString( filter );
log( "%cAreaOfInterest Created " + areaOfInterest.getAddress() + filterString, AREA_OF_INTEREST_COLOR );
}
/**
* Handle the AreaOfInterestFilterUpdatedEvent.
*
* @param e the event.
*/
protected void onAreaOfInterestFilterUpdated( @Nonnull final AreaOfInterestFilterUpdatedEvent e )
{
final AreaOfInterest areaOfInterest = e.getAreaOfInterest();
final Object filter = areaOfInterest.getFilter();
final String filterString = FilterUtil.filterToString( filter );
log( "%cAreaOfInterest Filter Updated " + areaOfInterest.getAddress() + " - " + filterString,
AREA_OF_INTEREST_COLOR );
}
/**
* Handle the AreaOfInterestStatusUpdatedEvent.
*
* @param e the event.
*/
protected void onAreaOfInterestStatusUpdated( @Nonnull final AreaOfInterestStatusUpdatedEvent e )
{
final AreaOfInterest areaOfInterest = e.getAreaOfInterest();
final Object filter = areaOfInterest.getFilter();
final String filterString = FilterUtil.filterToString( filter );
log( "%cAreaOfInterest Status Updated " + areaOfInterest.getAddress() + " - " + filterString,
AREA_OF_INTEREST_COLOR );
}
/**
* Handle the AreaOfInterestDisposedEvent.
*
* @param e the event.
*/
protected void onAreaOfInterestDisposed( @Nonnull final AreaOfInterestDisposedEvent e )
{
log( "%cAreaOfInterest Disposed " + e.getAreaOfInterest().getAddress(), AREA_OF_INTEREST_COLOR );
}
/**
* Handle the SubscriptionCreatedEvent.
*
* @param e the event.
*/
protected void onSubscriptionCreated( @Nonnull final SubscriptionCreatedEvent e )
{
final Subscription subscription = e.getSubscription();
final Object filter = subscription.getFilter();
final String filterString = null == filter ? "" : " - " + FilterUtil.filterToString( filter );
log( "%cSubscription Created " + subscription.getAddress() + filterString, SUBSCRIPTION_COLOR );
}
/**
* Handle the SubscriptionDisposedEvent.
*
* @param e the event.
*/
protected void onSubscriptionDisposed( @Nonnull final SubscriptionDisposedEvent e )
{
log( "%cSubscription Disposed " + e.getSubscription().getAddress(), SUBSCRIPTION_COLOR );
}
/**
* Handle the SubscriptionOrphanedEvent.
*
* @param e the event.
*/
protected void onSubscriptionOrphaned( @Nonnull final SubscriptionOrphanedEvent e )
{
log( "%cSubscription Orphaned " + e.getSubscription().getAddress(), SUBSCRIPTION_COLOR );
}
/**
* Log specified message with parameters
*
* @param message the message.
* @param styling the styling parameter. It is assumed that the message has a %c somewhere in it to identify the start of the styling.
*/
protected void log( @Nonnull final String message,
@CssRules @Nonnull final String styling )
{
DomGlobal.console.log( message, styling );
}
/**
* {@inheritDoc}
*/
@Override
protected void handleUnhandledEvent( @Nonnull final Object event )
{
DomGlobal.console.log( event );
}
}
|
package org.exist.cocoon;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.cocoon.ProcessingException;
import org.apache.cocoon.environment.Context;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Request;
import org.apache.cocoon.environment.Response;
import org.apache.cocoon.environment.Session;
import org.apache.cocoon.environment.SourceResolver;
import org.apache.cocoon.environment.http.HttpEnvironment;
import org.apache.cocoon.generation.ServiceableGenerator;
import org.apache.excalibur.source.Source;
import org.apache.excalibur.source.SourceValidity;
import org.exist.storage.serializers.EXistOutputKeys;
import org.exist.storage.serializers.Serializer;
import org.exist.xmldb.CollectionImpl;
import org.exist.xmldb.CompiledExpression;
import org.exist.xmldb.XQueryService;
import org.exist.xquery.functions.request.RequestModule;
import org.xml.sax.SAXException;
import org.xmldb.api.DatabaseManager;
import org.xmldb.api.base.Collection;
import org.xmldb.api.base.Database;
import org.xmldb.api.base.ResourceSet;
import org.xmldb.api.base.XMLDBException;
import org.xmldb.api.modules.XMLResource;
/**
* A generator for Cocoon which reads an XQuery script, executes it and passes
* the results into the Cocoon pipeline.
*
* The following sitemap parameters (with default values) are accepted:
*
* <pre>
* <map:parameter name="collection" value="xmldb:exist:///db"/>
* <map:parameter name="user" value="guest"/>
* <map:parameter name="password" value="guest"/>
* <map:parameter name="create-session" value="false"/>
* <map:parameter name="expand-xincludes" value="false"/>
* </pre>
*
* Parameter collection identifies the XML:DB root collection used to process
* the request. If set to "true", parameter create-session indicates that an
* HTTP session should be created upon the first invocation.
*
* @author wolf
*/
public class XQueryGenerator extends ServiceableGenerator {
public final static String DRIVER = "org.exist.xmldb.DatabaseImpl";
private Source inputSource = null;
private Map objectModel = null;
private boolean createSession = false;
private boolean expandXIncludes = false;
private String collectionURI = null;
private String defaultUser = null;
private String defaultPassword = null;
private Map optionalParameters;
private ThreadLocal cache = new ThreadLocal() {
/* (non-Javadoc)
* @see java.lang.ThreadLocal#initialValue()
*/
protected Object initialValue() {
return new HashMap();
}
};
private class CachedExpression {
SourceValidity validity;
CompiledExpression expr;
public CachedExpression(SourceValidity validity, CompiledExpression expr) {
this.validity = validity;
this.expr = expr;
}
}
/*
* (non-Javadoc)
*
* @see org.apache.cocoon.generation.AbstractGenerator#setup(org.apache.cocoon.environment.SourceResolver,
* java.util.Map, java.lang.String,
* org.apache.avalon.framework.parameters.Parameters)
*/
public void setup(SourceResolver resolver, Map objectModel, String source,
Parameters parameters) throws ProcessingException,
SAXException, IOException {
super.setup(resolver, objectModel, source, parameters);
this.objectModel = objectModel;
this.inputSource = resolver.resolveURI(source);
this.collectionURI = parameters.getParameter("collection",
"xmldb:exist:
this.defaultUser = parameters.getParameter("user", "guest");
this.defaultPassword = parameters.getParameter("password", "guest");
this.createSession = parameters.getParameterAsBoolean("create-session",
false);
this.expandXIncludes = parameters.getParameterAsBoolean(
"expand-xincludes", false);
this.optionalParameters = new HashMap();
String paramNames[] = parameters.getNames();
for (int i = 0; i < paramNames.length; i++) {
String param = paramNames[i];
if (!(param.equals("collection") || param.equals("user")
|| param.equals("password")
|| param.equals("create-session") || param
.equals("expand-xincludes"))) {
this.optionalParameters.put(param, parameters
.getParameter(param, ""));
}
}
try {
Class driver = Class.forName(DRIVER);
Database database = (Database)driver.newInstance();
database.setProperty("create-database", "true");
DatabaseManager.registerDatabase(database);
} catch(Exception e) {
throw new ProcessingException("Failed to initialize database driver: " + e.getMessage(), e);
}
}
/*
* (non-Javadoc)
*
* @see org.apache.cocoon.generation.AbstractGenerator#recycle()
*/
public void recycle() {
if (resolver != null)
resolver.release(inputSource);
inputSource = null;
super.recycle();
}
/*
* (non-Javadoc)
*
* @see org.apache.cocoon.generation.Generator#generate()
*/
public void generate() throws IOException, SAXException,
ProcessingException {
if (inputSource == null)
throw new ProcessingException("No input source");
Request request = ObjectModelHelper.getRequest(objectModel);
Response response = ObjectModelHelper.getResponse(objectModel);
Context context = ObjectModelHelper.getContext(objectModel);
Session session = request.getSession(createSession);
String baseURI = request.getRequestURI();
int p = baseURI.lastIndexOf('/');
if (p > -1)
baseURI = baseURI.substring(0, p);
baseURI = context.getRealPath(baseURI.substring(request
.getContextPath().length()));
String user = null;
String password = null;
// check if user and password can be read from the session
if (session != null && request.isRequestedSessionIdValid()) {
user = (String) session.getAttribute("user");
password = (String) session.getAttribute("password");
}
if (user == null)
user = defaultUser;
if (password == null)
password = defaultPassword;
try {
Collection collection = DatabaseManager.getCollection(
collectionURI, user, password);
if (collection == null) {
if (getLogger().isErrorEnabled())
getLogger().error(
"Collection " + collectionURI + " not found");
throw new ProcessingException("Collection " + collectionURI
+ " not found");
}
XQueryService service = (XQueryService) collection.getService(
"XQueryService", "1.0");
service.setProperty(Serializer.GENERATE_DOC_EVENTS, "false");
service.setProperty(EXistOutputKeys.EXPAND_XINCLUDES,
expandXIncludes ? "yes" : "no");
service.setProperty("base-uri", baseURI);
String prefix = RequestModule.PREFIX;
service.setNamespace(prefix, RequestModule.NAMESPACE_URI);
service.setModuleLoadPath(baseURI);
if(!((CollectionImpl)collection).isRemoteCollection()) {
HttpServletRequest httpRequest = (HttpServletRequest) objectModel
.get(HttpEnvironment.HTTP_REQUEST_OBJECT);
service.declareVariable(prefix + ":request",
new CocoonRequestWrapper(request, httpRequest));
service.declareVariable(prefix + ":response",
new CocoonResponseWrapper(response));
service.declareVariable(prefix + ":session",
new CocoonSessionWrapper(session));
}
declareParameters(service);
String uri = inputSource.getURI();
CompiledExpression expr;
CachedExpression cached;
cached = (CachedExpression) ((Map)cache.get()).get(uri);
if (cached != null) {
// check if source is valid or should be reloaded
int valid = cached.validity.isValid();
if (valid == SourceValidity.UNKNOWN)
valid = cached.validity.isValid(inputSource
.getValidity());
if (valid != SourceValidity.VALID) {
((Map)cache.get()).remove(uri);
cached = null;
}
}
if (cached == null) {
String xquery = readQuery();
expr = service.compile(xquery);
cached = new CachedExpression(inputSource.getValidity(),
expr);
((Map)cache.get()).put(uri, cached);
} else {
expr = cached.expr;
}
ResourceSet result = service.execute(expr);
XMLResource resource;
this.contentHandler.startDocument();
for (long i = 0; i < result.getSize(); i++) {
resource = (XMLResource) result.getResource(i);
resource.getContentAsSAX(this.contentHandler);
}
this.contentHandler.endDocument();
} catch (XMLDBException e) {
throw new ProcessingException("XMLDBException occurred: "
+ e.getMessage(), e);
}
}
private String readQuery() throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream((int) inputSource
.getContentLength());
byte[] t = new byte[512];
InputStream is = inputSource.getInputStream();
int count = 0;
while ((count = is.read(t)) != -1) {
os.write(t, 0, count);
}
return os.toString("UTF-8");
}
private void declareParameters(XQueryService service) throws XMLDBException {
for(Iterator i = optionalParameters.entrySet().iterator(); i.hasNext(); ) {
Map.Entry entry = (Map.Entry)i.next();
service.declareVariable((String)entry.getKey(), entry.getValue());
}
}
}
|
package org.java_websocket;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.ByteChannel;
import java.nio.channels.NotYetConnectedException;
import java.nio.channels.SelectionKey;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import org.java_websocket.drafts.Draft;
import org.java_websocket.drafts.Draft.CloseHandshakeType;
import org.java_websocket.drafts.Draft.HandshakeState;
import org.java_websocket.drafts.Draft_10;
import org.java_websocket.drafts.Draft_17;
import org.java_websocket.drafts.Draft_75;
import org.java_websocket.drafts.Draft_76;
import org.java_websocket.exceptions.IncompleteHandshakeException;
import org.java_websocket.exceptions.InvalidDataException;
import org.java_websocket.exceptions.InvalidFrameException;
import org.java_websocket.exceptions.InvalidHandshakeException;
import org.java_websocket.framing.CloseFrame;
import org.java_websocket.framing.CloseFrameBuilder;
import org.java_websocket.framing.Framedata;
import org.java_websocket.framing.Framedata.Opcode;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.handshake.ClientHandshakeBuilder;
import org.java_websocket.handshake.Handshakedata;
import org.java_websocket.handshake.ServerHandshake;
import org.java_websocket.handshake.ServerHandshakeBuilder;
import org.java_websocket.server.WebSocketServer.WebSocketWorker;
import org.java_websocket.util.Charsetfunctions;
/**
* Represents one end (client or server) of a single WebSocketImpl connection.
* Takes care of the "handshake" phase, then allows for easy sending of
* text frames, and receiving frames through an event-based model.
*
* This is an inner class, used by <tt>WebSocketClient</tt> and <tt>WebSocketServer</tt>, and should never need to be instantiated directly
* by your code. However, instances are exposed in <tt>WebSocketServer</tt> through the <i>onClientOpen</i>, <i>onClientClose</i>,
* <i>onClientMessage</i> callbacks.
*
*/
public class WebSocketImpl extends WebSocket {
public SelectionKey key;
/* only used to optain the socket addresses*/
public final Socket socket;
/** the possibly wrapped channel object whose selection is controlled by {@link #key} */
public ByteChannel channel;
/**
* Queue of buffers that need to be sent to the client.
*/
public final BlockingQueue<ByteBuffer> outQueue;
/**
* Queue of buffers that need to be processed
*/
public final BlockingQueue<ByteBuffer> inQueue;
/**
* Helper variable ment to store the thread which ( exclusively ) triggers this objects decode method.
**/
public volatile WebSocketWorker workerThread; // TODO reset worker?
/**
* Determines whether to receive data as part of the
* handshake, or as part of text/data frame transmitted over the websocket.
*/
private volatile boolean handshakeComplete = false;
/**
* Determines whether we sent already a request to Close the connection or not.
*/
private volatile boolean closeHandshakeSent = false;
/**
* Determines whether the connection is open or not
*/
private volatile boolean connectionClosed = false;
/**
* The listener to notify of WebSocket events.
*/
private final WebSocketListener wsl;
private List<Draft> knownDrafts;
private Draft draft = null;
private Role role;
/** used to join continuous frames */
private Framedata tempContiniousFrame;// FIXME out of mem risk
/** the bytes of an incomplete received handshake */
private ByteBuffer tmpHandshakeBytes;
/** stores the handshake sent by this websocket ( Role.CLIENT only ) */
private ClientHandshake handshakerequest = null;
/**
* crates a websocket with server role
*/
public WebSocketImpl( WebSocketListener listener , List<Draft> drafts , Socket sock ) {
this( listener, (Draft) null, sock );
this.role = Role.SERVER;
if( knownDrafts == null || knownDrafts.isEmpty() ) {
knownDrafts = new ArrayList<Draft>( 1 );
knownDrafts.add( new Draft_17() );
knownDrafts.add( new Draft_10() );
knownDrafts.add( new Draft_76() );
knownDrafts.add( new Draft_75() );
} else {
knownDrafts = drafts;
}
}
/**
* crates a websocket with client role
*/
public WebSocketImpl( WebSocketListener listener , Draft draft , Socket sock ) {
this.outQueue = new LinkedBlockingQueue<ByteBuffer>();
inQueue = new LinkedBlockingQueue<ByteBuffer>();
this.wsl = listener;
this.role = Role.CLIENT;
this.draft = draft;
this.socket = sock;
}
/**
* Should be called when a Selector has a key that is writable for this
* WebSocketImpl's SocketChannel connection.
*
* @throws IOException
* When socket related I/O errors occur.
* @throws InterruptedException
*/
public void decode( ByteBuffer socketBuffer ) throws IOException {
if( !socketBuffer.hasRemaining() || connectionClosed )
return;
if( DEBUG )
System.out.println( "process(" + socketBuffer.remaining() + "): {" + ( socketBuffer.remaining() > 1000 ? "too big to display" : new String( socketBuffer.array(), socketBuffer.position(), socketBuffer.remaining() ) ) + "}" );
if( handshakeComplete ) {
decodeFrames( socketBuffer );
} else {
if( decodeHandshake( socketBuffer ) ) {
decodeFrames( socketBuffer );
}
}
assert ( isClosing() || isClosed() || !socketBuffer.hasRemaining() );
}
/**
* Returns whether the handshake phase has is completed.
* In case of a broken handshake this will be never the case.
**/
private boolean decodeHandshake( ByteBuffer socketBufferNew ) throws IOException {
ByteBuffer socketBuffer;
if( tmpHandshakeBytes == null ) {
socketBuffer = socketBufferNew;
} else {
if( tmpHandshakeBytes.remaining() < socketBufferNew.remaining() ) {
ByteBuffer buf = ByteBuffer.allocate( tmpHandshakeBytes.capacity() + socketBufferNew.remaining() );
tmpHandshakeBytes.flip();
buf.put( tmpHandshakeBytes );
tmpHandshakeBytes = buf;
}
tmpHandshakeBytes.put( socketBufferNew );
tmpHandshakeBytes.flip();
socketBuffer = tmpHandshakeBytes;
}
socketBuffer.mark();
try {
if( draft == null ) {
HandshakeState isflashedgecase = isFlashEdgeCase( socketBuffer );
if( isflashedgecase == HandshakeState.MATCHED ) {
write( ByteBuffer.wrap( Charsetfunctions.utf8Bytes( wsl.getFlashPolicy( this ) ) ) );
close( CloseFrame.FLASHPOLICY, "" );
return false;
}
}
HandshakeState handshakestate = null;
try {
if( role == Role.SERVER ) {
if( draft == null ) {
for( Draft d : knownDrafts ) {
try {
d.setParseMode( role );
socketBuffer.reset();
Handshakedata tmphandshake = d.translateHandshake( socketBuffer );
if( tmphandshake instanceof ClientHandshake == false ) {
closeConnection( CloseFrame.PROTOCOL_ERROR, "wrong http function", false );
return false;
}
ClientHandshake handshake = (ClientHandshake) tmphandshake;
handshakestate = d.acceptHandshakeAsServer( handshake );
if( handshakestate == HandshakeState.MATCHED ) {
ServerHandshakeBuilder response;
try {
response = wsl.onWebsocketHandshakeReceivedAsServer( this, d, handshake );
} catch ( InvalidDataException e ) {
closeConnection( e.getCloseCode(), e.getMessage(), false );
return false;
}
write( d.createHandshake( d.postProcessHandshakeResponseAsServer( handshake, response ), role ) );
draft = d;
open( handshake );
return true;
}
} catch ( InvalidHandshakeException e ) {
// go on with an other draft
}
}
if( draft == null ) {
close( CloseFrame.PROTOCOL_ERROR, "no draft matches" );
}
return false;
} else {
// special case for multiple step handshakes
Handshakedata tmphandshake = draft.translateHandshake( socketBuffer );
if( tmphandshake instanceof ClientHandshake == false ) {
closeConnection( CloseFrame.PROTOCOL_ERROR, "wrong http function", false );
return false;
}
ClientHandshake handshake = (ClientHandshake) tmphandshake;
handshakestate = draft.acceptHandshakeAsServer( handshake );
if( handshakestate == HandshakeState.MATCHED ) {
open( handshake );
return true;
} else {
close( CloseFrame.PROTOCOL_ERROR, "the handshake did finaly not match" );
}
return false;
}
} else if( role == Role.CLIENT ) {
draft.setParseMode( role );
Handshakedata tmphandshake = draft.translateHandshake( socketBuffer );
if( tmphandshake instanceof ServerHandshake == false ) {
closeConnection( CloseFrame.PROTOCOL_ERROR, "Wwrong http function", false );
return false;
}
ServerHandshake handshake = (ServerHandshake) tmphandshake;
handshakestate = draft.acceptHandshakeAsClient( handshakerequest, handshake );
if( handshakestate == HandshakeState.MATCHED ) {
try {
wsl.onWebsocketHandshakeReceivedAsClient( this, handshakerequest, handshake );
} catch ( InvalidDataException e ) {
closeConnection( e.getCloseCode(), e.getMessage(), false );
return false;
}
open( handshake );
return true;
} else {
close( CloseFrame.PROTOCOL_ERROR, "draft " + draft + " refuses handshake" );
}
}
} catch ( InvalidHandshakeException e ) {
close( e );
}
} catch ( IncompleteHandshakeException e ) {
if( tmpHandshakeBytes == null ) {
socketBuffer.reset();
int newsize = e.getPreferedSize();
if( newsize == 0 ) {
newsize = socketBuffer.capacity() + 16;
} else {
assert ( e.getPreferedSize() >= socketBuffer.remaining() );
}
tmpHandshakeBytes = ByteBuffer.allocate( newsize );
tmpHandshakeBytes.put( socketBufferNew );
// tmpHandshakeBytes.flip();
} else {
tmpHandshakeBytes.position( tmpHandshakeBytes.limit() );
tmpHandshakeBytes.limit( tmpHandshakeBytes.capacity() );
}
}
return false;
}
private void decodeFrames( ByteBuffer socketBuffer ) {
List<Framedata> frames;
try {
frames = draft.translateFrame( socketBuffer );
for( Framedata f : frames ) {
if( DEBUG )
System.out.println( "matched frame: " + f );
Opcode curop = f.getOpcode();
if( curop == Opcode.CLOSING ) {
int code = CloseFrame.NOCODE;
String reason = "";
if( f instanceof CloseFrame ) {
CloseFrame cf = (CloseFrame) f;
code = cf.getCloseCode();
reason = cf.getMessage();
}
if( closeHandshakeSent ) {
// complete the close handshake by disconnecting
closeConnection( code, reason, true );
} else {
// echo close handshake
if( draft.getCloseHandshakeType() == CloseHandshakeType.TWOWAY )
close( code, reason );
closeConnection( code, reason, false );
}
continue;
} else if( curop == Opcode.PING ) {
wsl.onWebsocketPing( this, f );
continue;
} else if( curop == Opcode.PONG ) {
wsl.onWebsocketPong( this, f );
continue;
} else {
// process non control frames
if( tempContiniousFrame == null ) {
if( f.getOpcode() == Opcode.CONTINUOUS ) {
throw new InvalidFrameException( "unexpected continious frame" );
} else if( f.isFin() ) {
// receive normal onframe message
deliverMessage( f );
} else {
// remember the frame whose payload is about to be continued
tempContiniousFrame = f;
}
} else if( f.getOpcode() == Opcode.CONTINUOUS ) {
tempContiniousFrame.append( f );
if( f.isFin() ) {
deliverMessage( tempContiniousFrame );
tempContiniousFrame = null;
}
} else {
throw new InvalidDataException( CloseFrame.PROTOCOL_ERROR, "non control or continious frame expected" );
}
}
}
} catch ( InvalidDataException e1 ) {
wsl.onWebsocketError( this, e1 );
close( e1 );
return;
}
}
@Override
public void close( int code, String message ) {
if( !closeHandshakeSent ) {
if( handshakeComplete ) {
if( code == CloseFrame.ABNORMAL_CLOSE ) {
closeConnection( code, true );
closeHandshakeSent = true;
return;
}
if( draft.getCloseHandshakeType() != CloseHandshakeType.NONE ) {
try {
sendFrame( new CloseFrameBuilder( code, message ) );
} catch ( InvalidDataException e ) {
wsl.onWebsocketError( this, e );
closeConnection( CloseFrame.ABNORMAL_CLOSE, "generated frame is invalid", false );
}
} else {
closeConnection( code, false );
}
} else if( code == CloseFrame.FLASHPOLICY ) {
closeConnection( CloseFrame.FLASHPOLICY, true );
} else {
closeConnection( CloseFrame.NEVERCONNECTED, false );
}
if( code == CloseFrame.PROTOCOL_ERROR )// this endpoint found a PROTOCOL_ERROR
closeConnection( code, false );
closeHandshakeSent = true;
tmpHandshakeBytes = null;
return;
}
}
/**
* closes the socket no matter if the closing handshake completed.
* Does not send any not yet written data before closing.
* Calling this method more than once will have no effect.
*
* @param remote
* Indicates who "generated" <code>code</code>.<br>
* <code>true</code> means that this endpoint received the <code>code</code> from the other endpoint.<br>
* false means this endpoint decided to send the given code,<br>
* <code>remote</code> may also be true if this endpoint started the closing handshake since the other endpoint may not simply echo the <code>code</code> but close the connection the same time this endpoint does do but with an other <code>code</code>. <br>
**/
protected synchronized void closeConnection( int code, String message, boolean remote ) {
if( connectionClosed ) {
return;
}
connectionClosed = true;
if( key != null ) {
// key.attach( null ); //see issue #114
key.cancel();
}
// sockchannel.close();
this.wsl.onWebsocketClose( this, code, message, remote );
if( draft != null )
draft.reset();
tempContiniousFrame = null;
handshakerequest = null;
}
protected void closeConnection( int code, boolean remote ) {
closeConnection( code, "", remote );
}
public void eot( Exception e ) {
if( e == null || e instanceof IOException ) {
if( draft == null ) {
closeConnection( CloseFrame.ABNORMAL_CLOSE, true );
} else if( draft.getCloseHandshakeType() == CloseHandshakeType.NONE ) {
closeConnection( CloseFrame.NORMAL, true );
} else if( draft.getCloseHandshakeType() == CloseHandshakeType.ONEWAY ) {
if( role == Role.SERVER )
closeConnection( CloseFrame.ABNORMAL_CLOSE, true );
else
closeConnection( CloseFrame.NORMAL, true );
} else {
closeConnection( CloseFrame.ABNORMAL_CLOSE, true );
}
} else {
closeConnection( CloseFrame.BUGGYCLOSE, e.toString(), false );
}
}
@Override
public void close( int code ) {
close( code, "" );
}
@Override
public void close( InvalidDataException e ) {
close( e.getCloseCode(), e.getMessage() );
}
@Override
public void send( String text ) throws NotYetConnectedException {
if( text == null )
throw new IllegalArgumentException( "Cannot send 'null' data to a WebSocketImpl." );
send( draft.createFrames( text, role == Role.CLIENT ) );
}
@Override
public void send( ByteBuffer bytes ) throws IllegalArgumentException , NotYetConnectedException , InterruptedException {
if( bytes == null )
throw new IllegalArgumentException( "Cannot send 'null' data to a WebSocketImpl." );
send( draft.createFrames( bytes, role == Role.CLIENT ) );
}
@Override
public void send( byte[] bytes ) throws IllegalArgumentException , NotYetConnectedException , InterruptedException {
send( ByteBuffer.wrap( bytes ) );
}
private void send( Collection<Framedata> frames ) {
if( !this.handshakeComplete )
throw new NotYetConnectedException();
for( Framedata f : frames ) {
sendFrame( f );
}
}
@Override
public void sendFrame( Framedata framedata ) {
if( DEBUG )
System.out.println( "send frame: " + framedata );
write( draft.createBinaryFrame( framedata ) );
}
@Override
public boolean hasBufferedData() {
return !this.outQueue.isEmpty();
}
private HandshakeState isFlashEdgeCase( ByteBuffer request ) throws IncompleteHandshakeException {
request.mark();
if( request.limit() > Draft.FLASH_POLICY_REQUEST.length ) {
return HandshakeState.NOT_MATCHED;
} else if( request.limit() < Draft.FLASH_POLICY_REQUEST.length ) {
throw new IncompleteHandshakeException( Draft.FLASH_POLICY_REQUEST.length );
} else {
for( int flash_policy_index = 0 ; request.hasRemaining() ; flash_policy_index++ ) {
if( Draft.FLASH_POLICY_REQUEST[ flash_policy_index ] != request.get() ) {
request.reset();
return HandshakeState.NOT_MATCHED;
}
}
return HandshakeState.MATCHED;
}
}
@Override
public void startHandshake( ClientHandshakeBuilder handshakedata ) throws InvalidHandshakeException , InterruptedException {
if( handshakeComplete )
throw new IllegalStateException( "Handshake has already been sent." );
// Store the Handshake Request we are about to send
this.handshakerequest = draft.postProcessHandshakeRequestAsClient( handshakedata );
// Notify Listener
try {
wsl.onWebsocketHandshakeSentAsClient( this, this.handshakerequest );
} catch ( InvalidDataException e ) {
// Stop if the client code throws an exception
throw new InvalidHandshakeException( "Handshake data rejected by client." );
}
// Send
write( draft.createHandshake( this.handshakerequest, role ) );
}
private void write( ByteBuffer buf ) {
if( DEBUG )
System.out.println( "write(" + buf.remaining() + "): {" + ( buf.remaining() > 1000 ? "too big to display" : new String( buf.array() ) ) + "}" );
try {
outQueue.put( buf );
} catch ( InterruptedException e ) {
e.printStackTrace();
}
wsl.onWriteDemand( this );
}
private void write( List<ByteBuffer> bufs ) {
for( ByteBuffer b : bufs ) {
write( b );
}
}
private void deliverMessage( Framedata d ) throws InvalidDataException {
try {
if( d.getOpcode() == Opcode.TEXT ) {
wsl.onWebsocketMessage( this, Charsetfunctions.stringUtf8( d.getPayloadData() ) );
} else if( d.getOpcode() == Opcode.BINARY ) {
wsl.onWebsocketMessage( this, d.getPayloadData() );
} else {
if( DEBUG )
System.out.println( "Ignoring frame:" + d.toString() );
assert ( false );
}
} catch ( RuntimeException e ) {
wsl.onWebsocketError( this, e );
}
}
private void open( Handshakedata d ) throws IOException {
if( DEBUG )
System.out.println( "open using draft: " + draft.getClass().getSimpleName() );
handshakeComplete = true;
wsl.onWebsocketOpen( this, d );
}
@Override
public boolean isConnecting() {
return ( !connectionClosed && !closeHandshakeSent && !handshakeComplete );
}
@Override
public boolean isOpen() {
return ( !connectionClosed && !closeHandshakeSent && handshakeComplete );
}
@Override
public boolean isClosing() {
return ( !connectionClosed && closeHandshakeSent );
}
@Override
public boolean isClosed() {
return connectionClosed;
}
/**
* Retrieve the WebSocketImpl 'readyState'.
* This represents the state of the connection.
* It returns a numerical value, as per W3C WebSockets specs.
*
* @return Returns '0 = CONNECTING', '1 = OPEN', '2 = CLOSING' or '3 = CLOSED'
*/
@Override
public int getReadyState() {
if( isConnecting() ) {
return READY_STATE_CONNECTING;
} else if( isOpen() ) {
return READY_STATE_OPEN;
} else if( isClosing() ) {
return READY_STATE_CLOSING;
} else if( isClosed() ) {
return READY_STATE_CLOSED;
}
assert ( false );
return -1; // < This can't happen, by design!
}
@Override
public int hashCode() {
return super.hashCode();
}
@Override
public String toString() {
return super.toString(); // its nice to be able to set breakpoints here
}
@Override
public InetSocketAddress getRemoteSocketAddress() {
return (InetSocketAddress) socket.getRemoteSocketAddress();
}
@Override
public InetSocketAddress getLocalSocketAddress() {
return (InetSocketAddress) socket.getLocalSocketAddress();
}
@Override
public Draft getDraft() {
return draft;
}
}
|
package cucumber.runtime.clojure;
import cucumber.runtime.snippets.SnippetGenerator;
import gherkin.formatter.model.Comment;
import gherkin.formatter.model.Step;
import org.junit.Test;
import java.util.Collections;
import static org.junit.Assert.assertEquals;
public class ClojureSnippetTest {
@Test
public void generatesPlainSnippet() {
Step step = new Step(Collections.<Comment>emptyList(), "Given ", "I have 4 cukes in my \"big\" belly", 0, null, null);
String snippet = new SnippetGenerator(new ClojureSnippet()).getSnippet(step);
String expected = "" +
"(Given #\"^I have (\\d+) cukes in my \"([^\"]*)\" belly$\" [arg1, arg2]\n" +
" (comment Express the Regexp above with the code you wish you had ))\n";
assertEquals(expected, snippet);
}
}
|
// $Id: GMS.java,v 1.55 2006/05/22 10:03:10 belaban Exp $
package org.jgroups.protocols.pbcast;
import org.jgroups.*;
import org.jgroups.stack.Protocol;
import org.jgroups.util.*;
import org.jgroups.util.Queue;
import org.apache.commons.logging.Log;
import java.io.*;
import java.util.*;
import java.util.List;
/**
* Group membership protocol. Handles joins/leaves/crashes (suspicions) and emits new views
* accordingly. Use VIEW_ENFORCER on top of this layer to make sure new members don't receive
* any messages until they are members.
*/
public class GMS extends Protocol {
private GmsImpl impl=null;
Address local_addr=null;
final Membership members=new Membership(); // real membership
private final Membership tmp_members=new Membership(); // base for computing next view
/** Members joined but for which no view has been received yet */
private final Vector joining=new Vector(7);
/** Members excluded from group, but for which no view has been received yet */
private final Vector leaving=new Vector(7);
View view=null;
ViewId view_id=null;
private long ltime=0;
long join_timeout=5000;
long join_retry_timeout=2000;
long leave_timeout=5000;
private long digest_timeout=0; // time to wait for a digest (from PBCAST). should be fast
long merge_timeout=10000; // time to wait for all MERGE_RSPS
private final Object impl_mutex=new Object(); // synchronizes event entry into impl
private final Object digest_mutex=new Object();
private final Promise digest_promise=new Promise(); // holds result of GET_DIGEST event
private final Hashtable impls=new Hashtable(3);
private boolean shun=true;
boolean merge_leader=false; // can I initiate a merge ?
private boolean print_local_addr=true;
boolean disable_initial_coord=false; // can the member become a coord on startup or not ?
/** Setting this to false disables concurrent startups. This is only used by unit testing code
* for testing merging. To everybody else: don't change it to false ! */
boolean handle_concurrent_startup=true;
static final String CLIENT="Client";
static final String COORD="Coordinator";
static final String PART="Participant";
TimeScheduler timer=null;
/** Max number of old members to keep in history */
protected int num_prev_mbrs=50;
/** Keeps track of old members (up to num_prev_mbrs) */
BoundedList prev_members=null;
int num_views=0;
/** Stores the last 20 views */
BoundedList prev_views=new BoundedList(20);
/** Class to process JOIN, LEAVE and MERGE requests */
private final ViewHandler view_handler=new ViewHandler();
/** To collect VIEW_ACKs from all members */
final AckCollector ack_collector=new AckCollector();
/** Time in ms to wait for all VIEW acks (0 == wait forever) */
long view_ack_collection_timeout=2000;
/** How long should a Resumer wait until resuming the ViewHandler */
long resume_task_timeout=20000;
public static final String name="GMS";
public GMS() {
initState();
}
public String getName() {
return name;
}
public String getView() {return view_id != null? view_id.toString() : "null";}
public int getNumberOfViews() {return num_views;}
public String getLocalAddress() {return local_addr != null? local_addr.toString() : "null";}
public String getMembers() {return members != null? members.toString() : "[]";}
public int getNumMembers() {return members != null? members.size() : 0;}
public long getJoinTimeout() {return join_timeout;}
public void setJoinTimeout(long t) {join_timeout=t;}
public long getJoinRetryTimeout() {return join_retry_timeout;}
public void setJoinRetryTimeout(long t) {join_retry_timeout=t;}
public boolean isShun() {return shun;}
public void setShun(boolean s) {shun=s;}
public String printPreviousMembers() {
StringBuffer sb=new StringBuffer();
if(prev_members != null) {
for(Enumeration en=prev_members.elements(); en.hasMoreElements();) {
sb.append(en.nextElement()).append("\n");
}
}
return sb.toString();
}
public int viewHandlerSize() {return view_handler.size();}
public boolean isViewHandlerSuspended() {return view_handler.suspended();}
public String dumpViewHandlerQueue() {
return view_handler.dumpQueue();
}
public String dumpViewHandlerHistory() {
return view_handler.dumpHistory();
}
public void suspendViewHandler() {
view_handler.suspend(null);
}
public void resumeViewHandler() {
view_handler.resumeForce();
}
Log getLog() {return log;}
ViewHandler getViewHandler() {return view_handler;}
public String printPreviousViews() {
StringBuffer sb=new StringBuffer();
for(Enumeration en=prev_views.elements(); en.hasMoreElements();) {
sb.append(en.nextElement()).append("\n");
}
return sb.toString();
}
public boolean isCoordinator() {
Address coord=determineCoordinator();
return coord != null && local_addr != null && local_addr.equals(coord);
}
public void resetStats() {
super.resetStats();
num_views=0;
prev_views.removeAll();
}
public Vector requiredDownServices() {
Vector retval=new Vector(3);
retval.addElement(new Integer(Event.GET_DIGEST));
retval.addElement(new Integer(Event.SET_DIGEST));
retval.addElement(new Integer(Event.FIND_INITIAL_MBRS));
return retval;
}
public void setImpl(GmsImpl new_impl) {
synchronized(impl_mutex) {
if(impl == new_impl) // superfluous
return;
impl=new_impl;
if(log.isDebugEnabled()) {
String msg=(local_addr != null? local_addr.toString()+" " : "") + "changed role to " + new_impl.getClass().getName();
log.debug(msg);
}
}
}
public GmsImpl getImpl() {
return impl;
}
public void init() throws Exception {
prev_members=new BoundedList(num_prev_mbrs);
timer=stack != null? stack.timer : null;
if(timer == null)
throw new Exception("GMS.init(): timer is null");
if(impl != null)
impl.init();
}
public void start() throws Exception {
if(impl != null) impl.start();
}
public void stop() {
view_handler.stop(true);
if(impl != null) impl.stop();
if(prev_members != null)
prev_members.removeAll();
}
public void becomeCoordinator() {
CoordGmsImpl tmp=(CoordGmsImpl)impls.get(COORD);
if(tmp == null) {
tmp=new CoordGmsImpl(this);
impls.put(COORD, tmp);
}
try {
tmp.init();
}
catch(Exception e) {
log.error("exception switching to coordinator role", e);
}
setImpl(tmp);
}
public void becomeParticipant() {
ParticipantGmsImpl tmp=(ParticipantGmsImpl)impls.get(PART);
if(tmp == null) {
tmp=new ParticipantGmsImpl(this);
impls.put(PART, tmp);
}
try {
tmp.init();
}
catch(Exception e) {
log.error("exception switching to participant", e);
}
setImpl(tmp);
}
public void becomeClient() {
ClientGmsImpl tmp=(ClientGmsImpl)impls.get(CLIENT);
if(tmp == null) {
tmp=new ClientGmsImpl(this);
impls.put(CLIENT, tmp);
}
try {
tmp.init();
}
catch(Exception e) {
log.error("exception switching to client role", e);
}
setImpl(tmp);
}
boolean haveCoordinatorRole() {
return impl != null && impl instanceof CoordGmsImpl;
}
/**
* Computes the next view. Returns a copy that has <code>old_mbrs</code> and
* <code>suspected_mbrs</code> removed and <code>new_mbrs</code> added.
*/
public View getNextView(Vector new_mbrs, Vector old_mbrs, Vector suspected_mbrs) {
Vector mbrs;
long vid;
View v;
Membership tmp_mbrs;
Address tmp_mbr;
synchronized(members) {
if(view_id == null) {
log.error("view_id is null");
return null; // this should *never* happen !
}
vid=Math.max(view_id.getId(), ltime) + 1;
ltime=vid;
tmp_mbrs=tmp_members.copy(); // always operate on the temporary membership
tmp_mbrs.remove(suspected_mbrs);
tmp_mbrs.remove(old_mbrs);
tmp_mbrs.add(new_mbrs);
mbrs=tmp_mbrs.getMembers();
v=new View(local_addr, vid, mbrs);
// Update membership (see DESIGN for explanation):
tmp_members.set(mbrs);
// Update joining list (see DESIGN for explanation)
if(new_mbrs != null) {
for(int i=0; i < new_mbrs.size(); i++) {
tmp_mbr=(Address)new_mbrs.elementAt(i);
if(!joining.contains(tmp_mbr))
joining.addElement(tmp_mbr);
}
}
// Update leaving list (see DESIGN for explanations)
if(old_mbrs != null) {
for(Iterator it=old_mbrs.iterator(); it.hasNext();) {
Address addr=(Address)it.next();
if(!leaving.contains(addr))
leaving.add(addr);
}
}
if(suspected_mbrs != null) {
for(Iterator it=suspected_mbrs.iterator(); it.hasNext();) {
Address addr=(Address)it.next();
if(!leaving.contains(addr))
leaving.add(addr);
}
}
if(log.isDebugEnabled()) log.debug("new view is " + v);
return v;
}
}
/**
Compute a new view, given the current view, the new members and the suspected/left
members. Then simply mcast the view to all members. This is different to the VS GMS protocol,
in which we run a FLUSH protocol which tries to achive consensus on the set of messages mcast in
the current view before proceeding to install the next view.
The members for the new view are computed as follows:
<pre>
existing leaving suspected joining
1. new_view y n n y
2. tmp_view y y n y
(view_dest)
</pre>
<ol>
<li>
The new view to be installed includes the existing members plus the joining ones and
excludes the leaving and suspected members.
<li>
A temporary view is sent down the stack as an <em>event</em>. This allows the bottom layer
(e.g. UDP or TCP) to determine the members to which to send a multicast message. Compared
to the new view, leaving members are <em>included</em> since they have are waiting for a
view in which they are not members any longer before they leave. So, if we did not set a
temporary view, joining members would not receive the view (signalling that they have been
joined successfully). The temporary view is essentially the current view plus the joining
members (old members are still part of the current view).
</ol>
*/
public void castViewChange(Vector new_mbrs, Vector old_mbrs, Vector suspected_mbrs) {
View new_view;
// next view: current mbrs + new_mbrs - old_mbrs - suspected_mbrs
new_view=getNextView(new_mbrs, old_mbrs, suspected_mbrs);
castViewChange(new_view, null);
}
public void castViewChange(View new_view, Digest digest) {
castViewChangeWithDest(new_view, digest, null);
}
/**
* Broadcasts the new view and digest, and waits for acks from all members in the list given as argument.
* If the list is null, we take the members who are part of new_view
* @param new_view
* @param digest
* @param members
*/
public void castViewChangeWithDest(View new_view, Digest digest, java.util.List members) {
Message view_change_msg;
GmsHeader hdr;
long start, stop;
ViewId vid=new_view.getVid();
int size=-1;
if(members == null || members.size() == 0)
members=new_view.getMembers();
if(log.isTraceEnabled())
log.trace("mcasting view {" + new_view + "} (" + new_view.size() + " mbrs)\n");
start=System.currentTimeMillis();
view_change_msg=new Message(); // bcast to all members
hdr=new GmsHeader(GmsHeader.VIEW, new_view);
hdr.my_digest=digest;
view_change_msg.putHeader(name, hdr);
ack_collector.reset(vid, members);
size=ack_collector.size();
passDown(new Event(Event.MSG, view_change_msg));
try {
ack_collector.waitForAllAcks(view_ack_collection_timeout);
stop=System.currentTimeMillis();
if(trace)
log.trace("received all ACKs (" + size + ") for " + vid + " in " + (stop-start) + "ms");
}
catch(TimeoutException e) {
log.warn("failed to collect all ACKs (" + size + ") for view " + new_view + " after " + view_ack_collection_timeout +
"ms, missing ACKs from " + ack_collector.getMissing() + " (received=" + ack_collector.getReceived() +
"), local_addr=" + local_addr);
}
}
/**
* Sets the new view and sends a VIEW_CHANGE event up and down the stack. If the view is a MergeView (subclass
* of View), then digest will be non-null and has to be set before installing the view.
*/
public void installView(View new_view, Digest digest) {
if(digest != null)
mergeDigest(digest);
installView(new_view);
}
/**
* Sets the new view and sends a VIEW_CHANGE event up and down the stack.
*/
public void installView(View new_view) {
Address coord;
int rc;
ViewId vid=new_view.getVid();
Vector mbrs=new_view.getMembers();
if(log.isDebugEnabled()) log.debug("[local_addr=" + local_addr + "] view is " + new_view);
if(stats) {
num_views++;
prev_views.add(new_view);
}
// Discards view with id lower than our own. Will be installed without check if first view
if(view_id != null) {
rc=vid.compareTo(view_id);
if(rc <= 0) {
if(log.isTraceEnabled() && rc < 0) // only scream if view is smaller, silently discard same views
log.trace("[" + local_addr + "] received view < current view;" +
" discarding it (current vid: " + view_id + ", new vid: " + vid + ')');
return;
}
}
ltime=Math.max(vid.getId(), ltime); // compute Lamport logical time
/* Check for self-inclusion: if I'm not part of the new membership, I just discard it.
This ensures that messages sent in view V1 are only received by members of V1 */
if(checkSelfInclusion(mbrs) == false) {
// only shun if this member was previously part of the group. avoids problem where multiple
// members (e.g. X,Y,Z) join {A,B} concurrently, X is joined first, and Y and Z get view
// {A,B,X}, which would cause Y and Z to be shunned as they are not part of the membership
// bela Nov 20 2003
if(shun && local_addr != null && prev_members.contains(local_addr)) {
if(warn)
log.warn("I (" + local_addr + ") am not a member of view " + new_view +
", shunning myself and leaving the group (prev_members are " + prev_members +
", current view is " + view + ")");
if(impl != null)
impl.handleExit();
passUp(new Event(Event.EXIT));
}
else {
if(warn) log.warn("I (" + local_addr + ") am not a member of view " + new_view + "; discarding view");
}
return;
}
synchronized(members) { // serialize access to views
// assign new_view to view_id
if(new_view instanceof MergeView)
view=new View(new_view.getVid(), new_view.getMembers());
else
view=new_view;
view_id=vid.copy();
// Set the membership. Take into account joining members
if(mbrs != null && mbrs.size() > 0) {
members.set(mbrs);
tmp_members.set(members);
joining.removeAll(mbrs); // remove all members in mbrs from joining
// remove all elements from 'leaving' that are not in 'mbrs'
leaving.retainAll(mbrs);
tmp_members.add(joining); // add members that haven't yet shown up in the membership
tmp_members.remove(leaving); // remove members that haven't yet been removed from the membership
// add to prev_members
for(Iterator it=mbrs.iterator(); it.hasNext();) {
Address addr=(Address)it.next();
if(!prev_members.contains(addr))
prev_members.add(addr);
}
}
// Send VIEW_CHANGE event up and down the stack:
Event view_event=new Event(Event.VIEW_CHANGE, new_view.clone());
passDown(view_event); // needed e.g. by failure detector or UDP
passUp(view_event);
coord=determineCoordinator();
// if(coord != null && coord.equals(local_addr) && !(coord.equals(vid.getCoordAddress()))) {
// changed on suggestion by yaronr and Nicolas Piedeloupe
if(coord != null && coord.equals(local_addr) && !haveCoordinatorRole()) {
becomeCoordinator();
}
else {
if(haveCoordinatorRole() && !local_addr.equals(coord))
becomeParticipant();
}
}
}
protected Address determineCoordinator() {
synchronized(members) {
return members != null && members.size() > 0? (Address)members.elementAt(0) : null;
}
}
/** Checks whether the potential_new_coord would be the new coordinator (2nd in line) */
protected boolean wouldBeNewCoordinator(Address potential_new_coord) {
Address new_coord;
if(potential_new_coord == null) return false;
synchronized(members) {
if(members.size() < 2) return false;
new_coord=(Address)members.elementAt(1); // member at 2nd place
return new_coord != null && new_coord.equals(potential_new_coord);
}
}
/** Returns true if local_addr is member of mbrs, else false */
protected boolean checkSelfInclusion(Vector mbrs) {
Object mbr;
if(mbrs == null)
return false;
for(int i=0; i < mbrs.size(); i++) {
mbr=mbrs.elementAt(i);
if(mbr != null && local_addr.equals(mbr))
return true;
}
return false;
}
public View makeView(Vector mbrs) {
Address coord=null;
long id=0;
if(view_id != null) {
coord=view_id.getCoordAddress();
id=view_id.getId();
}
return new View(coord, id, mbrs);
}
public View makeView(Vector mbrs, ViewId vid) {
Address coord=null;
long id=0;
if(vid != null) {
coord=vid.getCoordAddress();
id=vid.getId();
}
return new View(coord, id, mbrs);
}
/** Send down a SET_DIGEST event */
public void setDigest(Digest d) {
passDown(new Event(Event.SET_DIGEST, d));
}
/** Send down a MERGE_DIGEST event */
public void mergeDigest(Digest d) {
passDown(new Event(Event.MERGE_DIGEST, d));
}
/** Sends down a GET_DIGEST event and waits for the GET_DIGEST_OK response, or
timeout, whichever occurs first */
public Digest getDigest() {
Digest ret=null;
synchronized(digest_mutex) {
digest_promise.reset();
passDown(Event.GET_DIGEST_EVT);
try {
ret=(Digest)digest_promise.getResultWithTimeout(digest_timeout);
}
catch(TimeoutException e) {
if(log.isErrorEnabled()) log.error("digest could not be fetched from below");
}
return ret;
}
}
public void up(Event evt) {
Object obj;
Message msg;
GmsHeader hdr;
MergeData merge_data;
switch(evt.getType()) {
case Event.MSG:
msg=(Message)evt.getArg();
obj=msg.getHeader(name);
if(obj == null || !(obj instanceof GmsHeader))
break;
hdr=(GmsHeader)msg.removeHeader(name);
switch(hdr.type) {
case GmsHeader.JOIN_REQ:
view_handler.add(new Request(Request.JOIN, hdr.mbr, false, null));
break;
case GmsHeader.JOIN_RSP:
impl.handleJoinResponse(hdr.join_rsp);
break;
case GmsHeader.LEAVE_REQ:
if(log.isDebugEnabled())
log.debug("received LEAVE_REQ for " + hdr.mbr + " from " + msg.getSrc());
if(hdr.mbr == null) {
if(log.isErrorEnabled()) log.error("LEAVE_REQ's mbr field is null");
return;
}
view_handler.add(new Request(Request.LEAVE, hdr.mbr, false, null));
break;
case GmsHeader.LEAVE_RSP:
impl.handleLeaveResponse();
break;
case GmsHeader.VIEW:
if(hdr.view == null) {
if(log.isErrorEnabled()) log.error("[VIEW]: view == null");
return;
}
// send VIEW_ACK to sender of view
Address coord=msg.getSrc();
Message view_ack=new Message(coord, null, null);
GmsHeader tmphdr=new GmsHeader(GmsHeader.VIEW_ACK, hdr.view);
view_ack.putHeader(name, tmphdr);
if(trace)
log.trace("sending VIEW_ACK to " + coord);
passDown(new Event(Event.MSG, view_ack));
impl.handleViewChange(hdr.view, hdr.my_digest);
break;
case GmsHeader.VIEW_ACK:
Object sender=msg.getSrc();
ack_collector.ack(sender);
return; // don't pass further up
case GmsHeader.MERGE_REQ:
impl.handleMergeRequest(msg.getSrc(), hdr.merge_id);
break;
case GmsHeader.MERGE_RSP:
merge_data=new MergeData(msg.getSrc(), hdr.view, hdr.my_digest);
merge_data.merge_rejected=hdr.merge_rejected;
impl.handleMergeResponse(merge_data, hdr.merge_id);
break;
case GmsHeader.INSTALL_MERGE_VIEW:
impl.handleMergeView(new MergeData(msg.getSrc(), hdr.view, hdr.my_digest), hdr.merge_id);
break;
case GmsHeader.CANCEL_MERGE:
impl.handleMergeCancelled(hdr.merge_id);
break;
default:
if(log.isErrorEnabled()) log.error("GmsHeader with type=" + hdr.type + " not known");
}
return; // don't pass up
case Event.CONNECT_OK: // sent by someone else, but WE are responsible for sending this !
case Event.DISCONNECT_OK: // dito (e.g. sent by TP layer). Don't send up the stack
return;
case Event.SET_LOCAL_ADDRESS:
local_addr=(Address)evt.getArg();
if(print_local_addr) {
System.out.println("\n
"GMS: address is " + local_addr +
"\n
}
break; // pass up
case Event.SUSPECT:
Address suspected=(Address)evt.getArg();
view_handler.add(new Request(Request.LEAVE, suspected, true, null));
ack_collector.suspect(suspected);
break; // pass up
case Event.UNSUSPECT:
impl.unsuspect((Address)evt.getArg());
return; // discard
case Event.MERGE:
view_handler.add(new Request(Request.MERGE, null, false, (Vector)evt.getArg()));
return; // don't pass up
}
if(impl.handleUpEvent(evt))
passUp(evt);
}
/**
This method is overridden to avoid hanging on getDigest(): when a JOIN is received, the coordinator needs
to retrieve the digest from the NAKACK layer. It therefore sends down a GET_DIGEST event, to which the NAKACK layer
responds with a GET_DIGEST_OK event.<p>
However, the GET_DIGEST_OK event will not be processed because the thread handling the JOIN request won't process
the GET_DIGEST_OK event until the JOIN event returns. The receiveUpEvent() method is executed by the up-handler
thread of the lower protocol and therefore can handle the event. All we do here is unblock the mutex on which
JOIN is waiting, allowing JOIN to return with a valid digest. The GET_DIGEST_OK event is then discarded, because
it won't be processed twice.
*/
public void receiveUpEvent(Event evt) {
switch(evt.getType()) {
case Event.GET_DIGEST_OK:
digest_promise.setResult(evt.getArg());
return; // don't pass further up
}
super.receiveUpEvent(evt);
}
public void down(Event evt) {
switch(evt.getType()) {
case Event.CONNECT:
Object arg=null;
passDown(evt);
if(local_addr == null)
if(log.isFatalEnabled()) log.fatal("[CONNECT] local_addr is null");
try {
impl.join(local_addr);
}
catch(SecurityException e) {
arg=e;
}
passUp(new Event(Event.CONNECT_OK, arg));
return; // don't pass down: was already passed down
case Event.DISCONNECT:
impl.leave((Address)evt.getArg());
if(!(impl instanceof CoordGmsImpl)) {
passUp(new Event(Event.DISCONNECT_OK));
initState(); // in case connect() is called again
}
break; // pass down
}
if(impl.handleDownEvent(evt))
passDown(evt);
}
/** Setup the Protocol instance according to the configuration string */
public boolean setProperties(Properties props) {
String str;
super.setProperties(props);
str=props.getProperty("shun");
if(str != null) {
shun=Boolean.valueOf(str).booleanValue();
props.remove("shun");
}
str=props.getProperty("merge_leader");
if(str != null) {
merge_leader=Boolean.valueOf(str).booleanValue();
props.remove("merge_leader");
}
str=props.getProperty("print_local_addr");
if(str != null) {
print_local_addr=Boolean.valueOf(str).booleanValue();
props.remove("print_local_addr");
}
str=props.getProperty("join_timeout"); // time to wait for JOIN
if(str != null) {
join_timeout=Long.parseLong(str);
props.remove("join_timeout");
}
str=props.getProperty("join_retry_timeout"); // time to wait between JOINs
if(str != null) {
join_retry_timeout=Long.parseLong(str);
props.remove("join_retry_timeout");
}
str=props.getProperty("leave_timeout"); // time to wait until coord responds to LEAVE req.
if(str != null) {
leave_timeout=Long.parseLong(str);
props.remove("leave_timeout");
}
str=props.getProperty("merge_timeout"); // time to wait for MERGE_RSPS from subgroup coordinators
if(str != null) {
merge_timeout=Long.parseLong(str);
props.remove("merge_timeout");
}
str=props.getProperty("digest_timeout"); // time to wait for GET_DIGEST_OK from PBCAST
if(str != null) {
digest_timeout=Long.parseLong(str);
props.remove("digest_timeout");
}
str=props.getProperty("view_ack_collection_timeout");
if(str != null) {
view_ack_collection_timeout=Long.parseLong(str);
props.remove("view_ack_collection_timeout");
}
str=props.getProperty("resume_task_timeout");
if(str != null) {
resume_task_timeout=Long.parseLong(str);
props.remove("resume_task_timeout");
}
str=props.getProperty("disable_initial_coord");
if(str != null) {
disable_initial_coord=Boolean.valueOf(str).booleanValue();
props.remove("disable_initial_coord");
}
str=props.getProperty("handle_concurrent_startup");
if(str != null) {
handle_concurrent_startup=Boolean.valueOf(str).booleanValue();
props.remove("handle_concurrent_startup");
}
str=props.getProperty("num_prev_mbrs");
if(str != null) {
num_prev_mbrs=Integer.parseInt(str);
props.remove("num_prev_mbrs");
}
if(props.size() > 0) {
log.error("GMS.setProperties(): the following properties are not recognized: " + props);
return false;
}
return true;
}
final void initState() {
becomeClient();
view_id=null;
view=null;
}
public static class GmsHeader extends Header implements Streamable {
public static final byte JOIN_REQ=1;
public static final byte JOIN_RSP=2;
public static final byte LEAVE_REQ=3;
public static final byte LEAVE_RSP=4;
public static final byte VIEW=5;
public static final byte MERGE_REQ=6;
public static final byte MERGE_RSP=7;
public static final byte INSTALL_MERGE_VIEW=8;
public static final byte CANCEL_MERGE=9;
public static final byte VIEW_ACK=10;
byte type=0;
View view=null; // used when type=VIEW or MERGE_RSP or INSTALL_MERGE_VIEW
Address mbr=null; // used when type=JOIN_REQ or LEAVE_REQ
JoinRsp join_rsp=null; // used when type=JOIN_RSP
Digest my_digest=null; // used when type=MERGE_RSP or INSTALL_MERGE_VIEW
ViewId merge_id=null; // used when type=MERGE_REQ or MERGE_RSP or INSTALL_MERGE_VIEW or CANCEL_MERGE
boolean merge_rejected=false; // used when type=MERGE_RSP
public GmsHeader() {
} // used for Externalization
public GmsHeader(byte type) {
this.type=type;
}
/** Used for VIEW header */
public GmsHeader(byte type, View view) {
this.type=type;
this.view=view;
}
/** Used for JOIN_REQ or LEAVE_REQ header */
public GmsHeader(byte type, Address mbr) {
this.type=type;
this.mbr=mbr;
}
/** Used for JOIN_RSP header */
public GmsHeader(byte type, JoinRsp join_rsp) {
this.type=type;
this.join_rsp=join_rsp;
}
public byte getType() {
return type;
}
public Address getMemeber() {
return mbr;
}
public String toString() {
StringBuffer sb=new StringBuffer("GmsHeader");
sb.append('[' + type2String(type) + ']');
switch(type) {
case JOIN_REQ:
sb.append(": mbr=" + mbr);
break;
case JOIN_RSP:
sb.append(": join_rsp=" + join_rsp);
break;
case LEAVE_REQ:
sb.append(": mbr=" + mbr);
break;
case LEAVE_RSP:
break;
case VIEW:
case VIEW_ACK:
sb.append(": view=" + view);
break;
case MERGE_REQ:
sb.append(": merge_id=" + merge_id);
break;
case MERGE_RSP:
sb.append(": view=" + view + ", digest=" + my_digest + ", merge_rejected=" + merge_rejected +
", merge_id=" + merge_id);
break;
case INSTALL_MERGE_VIEW:
sb.append(": view=" + view + ", digest=" + my_digest);
break;
case CANCEL_MERGE:
sb.append(", <merge cancelled>, merge_id=" + merge_id);
break;
}
return sb.toString();
}
public static String type2String(int type) {
switch(type) {
case JOIN_REQ: return "JOIN_REQ";
case JOIN_RSP: return "JOIN_RSP";
case LEAVE_REQ: return "LEAVE_REQ";
case LEAVE_RSP: return "LEAVE_RSP";
case VIEW: return "VIEW";
case MERGE_REQ: return "MERGE_REQ";
case MERGE_RSP: return "MERGE_RSP";
case INSTALL_MERGE_VIEW: return "INSTALL_MERGE_VIEW";
case CANCEL_MERGE: return "CANCEL_MERGE";
case VIEW_ACK: return "VIEW_ACK";
default: return "<unknown>";
}
}
public void writeExternal(ObjectOutput out) throws IOException {
out.writeByte(type);
out.writeObject(view);
out.writeObject(mbr);
out.writeObject(join_rsp);
out.writeObject(my_digest);
out.writeObject(merge_id);
out.writeBoolean(merge_rejected);
}
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
type=in.readByte();
view=(View)in.readObject();
mbr=(Address)in.readObject();
join_rsp=(JoinRsp)in.readObject();
my_digest=(Digest)in.readObject();
merge_id=(ViewId)in.readObject();
merge_rejected=in.readBoolean();
}
public void writeTo(DataOutputStream out) throws IOException {
out.writeByte(type);
boolean isMergeView=view != null && view instanceof MergeView;
out.writeBoolean(isMergeView);
Util.writeStreamable(view, out);
Util.writeAddress(mbr, out);
Util.writeStreamable(join_rsp, out);
Util.writeStreamable(my_digest, out);
Util.writeStreamable(merge_id, out); // kludge: we know merge_id is a ViewId
out.writeBoolean(merge_rejected);
}
public void readFrom(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException {
type=in.readByte();
boolean isMergeView=in.readBoolean();
if(isMergeView)
view=(View)Util.readStreamable(MergeView.class, in);
else
view=(View)Util.readStreamable(View.class, in);
mbr=Util.readAddress(in);
join_rsp=(JoinRsp)Util.readStreamable(JoinRsp.class, in);
my_digest=(Digest)Util.readStreamable(Digest.class, in);
merge_id=(ViewId)Util.readStreamable(ViewId.class, in);
merge_rejected=in.readBoolean();
}
public long size() {
long retval=Global.BYTE_SIZE *2; // type + merge_rejected
retval+=Global.BYTE_SIZE; // presence view
retval+=Global.BYTE_SIZE; // MergeView or View
if(view != null)
retval+=view.serializedSize();
retval+=Util.size(mbr);
retval+=Global.BYTE_SIZE; // presence of join_rsp
if(join_rsp != null)
retval+=join_rsp.serializedSize();
retval+=Global.BYTE_SIZE; // presence for my_digest
if(my_digest != null)
retval+=my_digest.serializedSize();
retval+=Global.BYTE_SIZE; // presence for merge_id
if(merge_id != null)
retval+=merge_id.serializedSize();
return retval;
}
}
public static class Request {
static final int JOIN = 1;
static final int LEAVE = 2;
static final int SUSPECT = 3;
static final int MERGE = 4;
static final int VIEW = 5;
int type=-1;
Address mbr=null;
boolean suspected;
Vector coordinators=null;
View view=null;
Digest digest=null;
List target_members=null;
Request(int type) {
this.type=type;
}
Request(int type, Address mbr, boolean suspected, Vector coordinators) {
this.type=type;
this.mbr=mbr;
this.suspected=suspected;
this.coordinators=coordinators;
}
public String toString() {
switch(type) {
case JOIN: return "JOIN(" + mbr + ")";
case LEAVE: return "LEAVE(" + mbr + ", " + suspected + ")";
case SUSPECT: return "SUSPECT(" + mbr + ")";
case MERGE: return "MERGE(" + coordinators + ")";
case VIEW: return "VIEW (" + view.getVid() + ")";
}
return "<invalid (type=" + type + ")";
}
}
/**
* Class which processes JOIN, LEAVE and MERGE requests. Requests are queued and processed in FIFO order
* @author Bela Ban
* @version $Id: GMS.java,v 1.55 2006/05/22 10:03:10 belaban Exp $
*/
class ViewHandler implements Runnable {
Thread t;
Queue q=new Queue(); // Queue<Request>
boolean suspended=false;
final static long INTERVAL=5000;
private static final long MAX_COMPLETION_TIME=10000;
/** Maintains a list of the last 20 requests */
private final BoundedList history=new BoundedList(20);
/** Map<Object,TimeScheduler.CancellableTask>. Keeps track of Resumer tasks which have not fired yet */
private final Map resume_tasks=new HashMap();
private Object merge_id=null;
void add(Request req) {
add(req, false, false);
}
synchronized void add(Request req, boolean at_head, boolean unsuspend) {
if(suspended && !unsuspend) {
log.warn("queue is suspended; request " + req + " is discarded");
return;
}
start(unsuspend);
try {
if(at_head)
q.addAtHead(req);
else
q.add(req);
history.add(new Date() + ": " + req.toString());
}
catch(QueueClosedException e) {
if(trace)
log.trace("queue is closed; request " + req + " is discarded");
}
}
synchronized void waitUntilCompleted(long timeout) {
if(t != null) {
try {
t.join(timeout);
}
catch(InterruptedException e) {
}
}
}
/**
* Waits until the current request has been processes, then clears the queue and discards new
* requests from now on
*/
public synchronized void suspend(Object merge_id) {
if(suspended)
return;
suspended=true;
this.merge_id=merge_id;
q.clear();
waitUntilCompleted(MAX_COMPLETION_TIME);
q.close(true);
if(trace)
log.trace("suspended ViewHandler");
Resumer r=new Resumer(resume_task_timeout, merge_id, resume_tasks, this);
resume_tasks.put(merge_id, r);
timer.add(r);
}
public synchronized void resume(Object merge_id) {
if(!suspended)
return;
boolean same_merge_id=this.merge_id != null && merge_id != null && this.merge_id.equals(merge_id);
same_merge_id=same_merge_id || (this.merge_id == null && merge_id == null);
if(!same_merge_id) {
if(warn)
log.warn("resume(" +merge_id+ ") does not match " + this.merge_id + ", ignoring resume()");
return;
}
synchronized(resume_tasks) {
TimeScheduler.CancellableTask task=(TimeScheduler.CancellableTask)resume_tasks.get(merge_id);
if(task != null) {
task.cancel();
resume_tasks.remove(merge_id);
}
}
resumeForce();
}
public synchronized void resumeForce() {
if(q.closed())
q.reset();
suspended=false;
if(trace)
log.trace("resumed ViewHandler");
}
public void run() {
Request req;
while(!q.closed() && Thread.currentThread().equals(t)) {
try {
req=(Request)q.remove(INTERVAL); // throws a TimeoutException if it runs into timeout
process(req);
}
catch(QueueClosedException e) {
break;
}
catch(TimeoutException e) {
break;
}
catch(Throwable catchall) {
Util.sleep(50);
}
}
}
public int size() {return q.size();}
public boolean suspended() {return suspended;}
public String dumpQueue() {
StringBuffer sb=new StringBuffer();
List v=q.values();
for(Iterator it=v.iterator(); it.hasNext();) {
sb.append(it.next() + "\n");
}
return sb.toString();
}
public String dumpHistory() {
StringBuffer sb=new StringBuffer();
for(Enumeration en=history.elements(); en.hasMoreElements();) {
sb.append(en.nextElement() + "\n");
}
return sb.toString();
}
private void process(Request req) {
if(trace)
log.trace("processing " + req);
switch(req.type) {
case Request.JOIN:
impl.handleJoin(req.mbr);
break;
case Request.LEAVE:
if(req.suspected)
impl.suspect(req.mbr);
else
impl.handleLeave(req.mbr, req.suspected);
break;
case Request.SUSPECT:
impl.suspect(req.mbr);
break;
case Request.MERGE:
impl.merge(req.coordinators);
break;
case Request.VIEW:
castViewChangeWithDest(req.view, req.digest, req.target_members);
break;
default:
log.error("Request " + req.type + " is unknown; discarded");
}
}
synchronized void start(boolean unsuspend) {
if(q.closed())
q.reset();
if(unsuspend) {
suspended=false;
synchronized(resume_tasks) {
TimeScheduler.CancellableTask task=(TimeScheduler.CancellableTask)resume_tasks.get(merge_id);
if(task != null) {
task.cancel();
resume_tasks.remove(merge_id);
}
}
}
merge_id=null;
if(t == null || !t.isAlive()) {
t=new Thread(this, "ViewHandler");
t.setDaemon(false); // thread cannot terminate if we have tasks left, e.g. when we as coord leave
t.start();
if(trace)
log.trace("ViewHandler started");
}
}
synchronized void stop(boolean flush) {
q.close(flush);
TimeScheduler.CancellableTask task;
synchronized(resume_tasks) {
for(Iterator it=resume_tasks.values().iterator(); it.hasNext();) {
task=(TimeScheduler.CancellableTask)it.next();
task.cancel();
}
resume_tasks.clear();
}
merge_id=null;
resumeForce();
}
}
/**
* Resumer is a second line of defense: when the ViewHandler is suspended, it will be resumed when the current
* merge is cancelled, or when the merge completes. However, in a case where this never happens (this
* shouldn't be the case !), the Resumer will nevertheless resume the ViewHandler.
* We chose this strategy because ViewHandler is critical: if it is suspended indefinitely, we would
* not be able to process new JOIN requests ! So, this is for peace of mind, although it most likely
* will never be used...
*/
static class Resumer implements TimeScheduler.CancellableTask {
boolean cancelled=false;
long interval;
final Object token;
final Map tasks;
final ViewHandler handler;
public Resumer(long interval, final Object token, final Map t, final ViewHandler handler) {
this.interval=interval;
this.token=token;
this.tasks=t;
this.handler=handler;
}
public void cancel() {
cancelled=true;
}
public boolean cancelled() {
return cancelled;
}
public long nextInterval() {
return interval;
}
public void run() {
TimeScheduler.CancellableTask t;
boolean execute=true;
synchronized(tasks) {
t=(TimeScheduler.CancellableTask)tasks.get(token);
if(t != null) {
t.cancel();
execute=true;
}
else {
execute=false;
}
tasks.remove(token);
}
if(execute) {
handler.resume(token);
}
}
}
}
|
package cn.ce.binlog.mongo.simple;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import cn.ce.utils.common.BeanUtil;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.MongoException;
import com.mongodb.MongoOptions;
import com.mongodb.ServerAddress;
import com.mongodb.WriteConcern;
public class MongoConnectionFactory {
private final static Log logger = LogFactory
.getLog(MongoConnectionFactory.class);
private static Lock lock = new ReentrantLock();
// private static String username;
// private static String passwd;
private final static CopyOnWriteArraySet<String> indexSet = new CopyOnWriteArraySet<String>();
private static Map<String, DBCollection> tbMap = new ConcurrentHashMap<String, DBCollection>();
private static Map<String, MongoClient> dbMap = new ConcurrentHashMap<String, MongoClient>();
// public static Map<String, Object> parseJSON2Map(String jsonStr) {
// Map<String, Object> map = new HashMap<String, Object>();
// JSONObject json = JSONObject.fromObject(jsonStr);
// for (Object k : json.keySet()) {
// Object v = json.get(k);
// if (v instanceof JSONArray) {
// List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
// Iterator<JSONObject> it = ((JSONArray) v).iterator();
// while (it.hasNext()) {
// JSONObject json2 = it.next();
// list.add(parseJSON2Map(json2.toString()));
// map.put(k.toString(), list);
// } else {
// map.put(k.toString(), v);
// return map;
public static void createIndex(String ipcsv, Integer port, String dbname,
String tbname, String username, String passwd,
String connectionsPerHost_s,
String threadsAllowedToBlockForConnectionMultiplier_s,
String... columName2Indexs) throws Exception {
StringBuilder muliKeyName = new StringBuilder();
BasicDBObject copmIndex = new BasicDBObject();
for (String oneName : columName2Indexs) {
muliKeyName.append(oneName);
muliKeyName.append(".");
copmIndex.append(oneName, 1);
}
muliKeyName.append("dvs");
String indexKeyName = ipcsv + "." + port + "." + dbname + "." + tbname
+ "." + muliKeyName.toString();
if (indexSet.add(indexKeyName)) {
if (columName2Indexs != null && columName2Indexs.length == 1
&& "_id".equalsIgnoreCase(columName2Indexs[0])) {
logger.info("no need create index,columName2Indexs:"
+ columName2Indexs);
return;
}
DBCollection dbc = MongoConnectionFactory.getMongoTBConn(ipcsv,
port, dbname, tbname, username, passwd,
connectionsPerHost_s,
threadsAllowedToBlockForConnectionMultiplier_s);
dbc.createIndex(
copmIndex,
new BasicDBObject().append("background", true)
.append("unique", false).append("dropDups", true)
.append("ns", dbc.getFullName())
.append("name", muliKeyName.toString()));
logger.info("create mongodb index>>>>>>>>> indexKeyName:"
+ indexKeyName + " muliKeyName:" + muliKeyName.toString());
}
}
private static MongoClient getMongoClient(String ipcsv, int port,
String connectionsPerHost_s,
String threadsAllowedToBlockForConnectionMultiplier_s,
String username, String passwd, String mongodbname) {
logger.info("ipcsv:" + ipcsv);
logger.info("port:" + port);
logger.info("username:" + username);
logger.info("passwd:" + passwd);
logger.info("mongodbname:" + mongodbname);
String dbKeyName = ipcsv + "." + port;
try {
MongoConnectionFactory.lock.lock();
if (dbMap.containsKey(dbKeyName)) {
MongoClient mc = dbMap.get(dbKeyName);
return mc;
}
List<String> ips = BeanUtil.csvToList(ipcsv, ",");
List<ServerAddress> seeds = new ArrayList<ServerAddress>(5);
for (String ip : ips) {
seeds.add(new ServerAddress(ip, port));
}
MongoClient mc = null;
if (StringUtils.isBlank(username)) {
mc = new MongoClient(seeds);
} else {
MongoCredential credential = MongoCredential.createCredential(
username, mongodbname, passwd.toCharArray());
mc = new MongoClient(seeds, Arrays.asList(credential));
}
MongoOptions opt = mc.getMongoOptions();
opt.setConnectionsPerHost(new Integer(connectionsPerHost_s));
opt.setThreadsAllowedToBlockForConnectionMultiplier(new Integer(
threadsAllowedToBlockForConnectionMultiplier_s));
opt.autoConnectRetry = true;
dbMap.put(dbKeyName, mc);
return mc;
} catch (Throwable t) {
String msg = t.getMessage();
t.printStackTrace();
dbMap.remove(dbKeyName);
throw new RuntimeException(msg);
} finally {
MongoConnectionFactory.lock.unlock();
}
}
public static DBCollection getMongoTBConn(String ipcsv, int port,
String mongodbname, String mongotbname, String username,
String passwd, String connectionsPerHost_s,
String threadsAllowedToBlockForConnectionMultiplier_s)
throws Exception {
String tbkey = ipcsv + "." + port + "." + mongodbname + "."
+ mongotbname;
try {
MongoConnectionFactory.lock.lock();
if (tbMap.containsKey(tbkey)) {
DBCollection tb = tbMap.get(tbkey);
return tb;
}
MongoClient mclinet = MongoConnectionFactory.getMongoClient(ipcsv,
port, connectionsPerHost_s,
threadsAllowedToBlockForConnectionMultiplier_s, username,
passwd, mongodbname);
DB db = mclinet.getDB(mongodbname);
// if (!StringUtils.isBlank(username)) {
// boolean auth = db.authenticate(username, passwd.toCharArray());
// if (auth) {
// System.out.println("");
// } else {
// throw new RuntimeException(",ipcsv=" + ipcsv
// + " dbname=" + mongodbname + " port=" + port
// + " username=" + username + " passwd=" + passwd);
DBCollection col = db.getCollection(mongotbname);
col.setWriteConcern(WriteConcern.SAFE);
tbMap.put(tbkey, col);
return col;
} catch (Throwable t) {
String msg = t.getMessage();
t.printStackTrace();
tbMap.remove(tbkey);
throw new RuntimeException(msg);
} finally {
MongoConnectionFactory.lock.unlock();
}
}
public static void close() {
for (String ipcsv : dbMap.keySet()) {
MongoClient mclinet = dbMap.get(ipcsv);
if (mclinet != null) {
mclinet.close();
}
}
dbMap.clear();
tbMap.clear();
indexSet.clear();
}
public static void main(String[] args) throws UnknownHostException {
DBCollection dbc;
try {
dbc = MongoConnectionFactory.getMongoTBConn("", 27017, "", "",
"test", "log4j", "", "");
DBObject dbo = new BasicDBObject();
dbo.put("key111", "value");
dbc.insert(dbo, WriteConcern.SAFE);
dbc.ensureIndex("key111");
System.out.println("++++++++++++++++");
} catch (MongoException e) {
System.out.println("
// e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
package org.jetel.component;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.nio.charset.Charset;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jetel.component.infobright.BooleanType;
import org.jetel.component.infobright.CloverValueConverter;
import org.jetel.connection.jdbc.DBConnection;
import org.jetel.connection.jdbc.specific.JdbcSpecific;
import org.jetel.connection.jdbc.specific.JdbcSpecific.OperationType;
import org.jetel.data.DataRecord;
import org.jetel.data.Defaults;
import org.jetel.data.parser.DataParser;
import org.jetel.data.parser.Parser;
import org.jetel.database.IConnection;
import org.jetel.exception.ComponentNotReadyException;
import org.jetel.exception.ConfigurationProblem;
import org.jetel.exception.ConfigurationStatus;
import org.jetel.exception.JetelException;
import org.jetel.exception.XMLConfigurationException;
import org.jetel.exception.ConfigurationStatus.Priority;
import org.jetel.exception.ConfigurationStatus.Severity;
import org.jetel.graph.InputPort;
import org.jetel.graph.Node;
import org.jetel.graph.OutputPort;
import org.jetel.graph.Result;
import org.jetel.graph.TransactionMethod;
import org.jetel.graph.TransformationGraph;
import org.jetel.metadata.DataFieldMetadata;
import org.jetel.metadata.DataRecordMetadata;
import org.jetel.util.SynchronizeUtils;
import org.jetel.util.file.FileUtils;
import org.jetel.util.property.ComponentXMLAttributes;
import org.jetel.util.string.StringUtils;
import org.w3c.dom.Element;
import com.infobright.etl.model.BrighthouseRecord;
import com.infobright.etl.model.DataFormat;
import com.infobright.etl.model.ValueConverter;
import com.infobright.etl.model.datatype.AbstractColumnType;
import com.infobright.io.InfobrightNamedPipeLoader;
import com.infobright.logging.EtlLogger;
public class InfobrightDataWriter extends Node {
private static final String XML_TABLE_ATTRIBUTE = "table";
private static final String XML_DBCONNECTION_ATTRIBUTE = "dbConnection";
private static final String XML_DATA_FORMAT_ATTRIBUTE = "dataFormat";
private static final String XML_CHARSET_ATTRIBUTE = "charset";
private static final String XML_LOG_FILE_ATTRIBUTE = "logFile";
private static final String XML_APPEND_ATTRIBUTE = "append";
private static final String XML_PIPE_NAMEPREFIX_ATTRIBUTE = "pipeNamePrefix";//changing this parameter has no effect - infobright-core bug
private static final String XML_TIMEOUT_ATTRIBUTE = "timeout";
private static final String XML_CLOVER_FIELDS_ATTRIBUTE = "cloverFields";
private static final String XML_CHECK_VALUES_ATTRIBUTE = "checkValues";
public final static String COMPONENT_TYPE = "INFOBRIGHT_DATA_WRITER";
static Log logger = LogFactory.getLog(CheckForeignKey.class);
private final static int READ_FROM_PORT = 0;
private final static int WRITE_TO_PORT = 0;
private String table;
private String connectionName;
private DBConnection dbConnection;
private Connection sqlConnection;
private DataFormat dataFormat = DataFormat.TXT_VARIABLE;
private String charset;
private String logFile;
private boolean append = false;
private String pipeNamePrefix;
private int timeout = -1;
private String[] cloverFields;
private BrighthouseRecord bRecord;
private ValueConverter converter;
private InfobrightNamedPipeLoader loader;
private int[] cloverFieldIndexes;
private DataParser dataParser;
private Charset chset;
private CommonsLogger log;
private boolean checkValues = false;
/**
* @param id
*/
public InfobrightDataWriter(String id) {
super(id);
}
/* (non-Javadoc)
* @see org.jetel.graph.GraphElement#checkConfig(org.jetel.exception.ConfigurationStatus)
*/
public ConfigurationStatus checkConfig(ConfigurationStatus status) {
super.checkConfig(status);
if(!checkInputPorts(status, 1, 1)
|| !checkOutputPorts(status, 0, 1)) {
return status;
}
// get dbConnection from graph
if (dbConnection == null){
IConnection conn = getGraph().getConnection(connectionName);
if(conn == null) {
status.add("Can't find DBConnection ID: " + connectionName, Severity.ERROR, this, Priority.NORMAL, XML_DBCONNECTION_ATTRIBUTE);
}else
if(!(conn instanceof DBConnection)) {
status.add("Connection with ID: " + connectionName + " isn't instance of the DBConnection class.", Severity.ERROR, this, Priority.NORMAL, XML_DBCONNECTION_ATTRIBUTE);
}else{
dbConnection = (DBConnection) conn;
}
}
//check connection
if (dbConnection != null && !dbConnection.isInitialized()) {
try {
dbConnection.init();
sqlConnection = dbConnection.getConnection(getId(), OperationType.WRITE).getSqlConnection();
} catch (ComponentNotReadyException e) {
status.add(e, Severity.ERROR, this, Priority.NORMAL, XML_DBCONNECTION_ATTRIBUTE);
} catch (JetelException e) {
status.add(e.getMessage(), Severity.ERROR, this, Priority.NORMAL, XML_DBCONNECTION_ATTRIBUTE);
}
}
try {
chset = Charset.forName(charset != null ? charset : Defaults.DataFormatter.DEFAULT_CHARSET_ENCODER);
} catch (Exception e) {
status.add(e.getMessage(), Severity.ERROR, this, Priority.NORMAL, XML_DBCONNECTION_ATTRIBUTE);
}
//check debug file
try {
if (logFile != null && !FileUtils.canWrite(getGraph().getProjectURL(), logFile)) {
status.add(new ConfigurationProblem("Can't write to " + logFile, Severity.WARNING, this, Priority.NORMAL, XML_LOG_FILE_ATTRIBUTE));
}
} catch (ComponentNotReadyException e) {
status.add(new ConfigurationProblem(e, Severity.WARNING, this, Priority.NORMAL, XML_LOG_FILE_ATTRIBUTE));
}
EtlLogger log = new DumbLogger();
DataRecordMetadata metadata = getInputPort(READ_FROM_PORT).getMetadata();
if (cloverFields != null) {
cloverFieldIndexes = new int[cloverFields.length];
for (int i = 0; i < cloverFieldIndexes.length; i++) {
cloverFieldIndexes[i] = metadata.getFieldPosition(cloverFields[i]);
}
}else{
cloverFieldIndexes = new int[metadata.getNumFields()];
for (int i = 0; i < cloverFieldIndexes.length; i++) {
cloverFieldIndexes[i] = i;
}
}
//try to create loader and Brighthouse record
try {
loader = new InfobrightNamedPipeLoader(table, sqlConnection, log, dataFormat, chset);
if (sqlConnection != null) {
bRecord = createBrighthouseRecord(metadata, dbConnection.getJdbcSpecific(), log);
}
}catch (SQLException e) {//table doesn't exist yet
status.add(e.getMessage(), Severity.WARNING, this, Priority.NORMAL);
} catch (Exception e) {
status.add(e.getMessage(), Severity.ERROR, this, Priority.NORMAL);
}
return status;
}
/* (non-Javadoc)
* @see org.jetel.graph.Node#init()
*/
public void init() throws ComponentNotReadyException {
if(isInitialized()) return;
super.init();
// get dbConnection from graph
if (dbConnection == null){
IConnection conn = getGraph().getConnection(connectionName);
if(conn == null) {
throw new ComponentNotReadyException("Can't find DBConnection ID: " + connectionName);
}
if(!(conn instanceof DBConnection)) {
throw new ComponentNotReadyException("Connection with ID: " + connectionName + " isn't instance of the DBConnection class.");
}
dbConnection = (DBConnection) conn;
}
if (!dbConnection.isInitialized()) {
dbConnection.init();
}
try {
sqlConnection = dbConnection.getConnection(getId(), OperationType.WRITE).getSqlConnection();
} catch (JetelException e) {
throw new ComponentNotReadyException(this, XML_DBCONNECTION_ATTRIBUTE, e.getMessage());
}
//prepare indexes of clover fields to load
DataRecordMetadata metadata = getInputPort(READ_FROM_PORT).getMetadata();
if (cloverFields != null) {
cloverFieldIndexes = new int[cloverFields.length];
for (int i = 0; i < cloverFieldIndexes.length; i++) {
cloverFieldIndexes[i] = metadata.getFieldPosition(cloverFields[i]);
}
}else{
cloverFieldIndexes = new int[metadata.getNumFields()];
for (int i = 0; i < cloverFieldIndexes.length; i++) {
cloverFieldIndexes[i] = i;
}
}
chset = Charset.forName(charset != null ? charset : Defaults.DataFormatter.DEFAULT_CHARSET_ENCODER);
//create loader and Brighthouse record
log = new CommonsLogger(logger);
try {
loader = new InfobrightNamedPipeLoader(table, sqlConnection, log, dataFormat, chset);
if (logFile != null) {
loader.setDebugOutputStream(FileUtils.getOutputStream(getGraph().getProjectURL(), logFile, append, -1));
}else if (getOutputPort(WRITE_TO_PORT) != null){//prepare parser for output port
dataParser = new DataParser(charset);
dataParser.setQuotedStrings(true);
dataParser.init(getOutputPort(WRITE_TO_PORT).getMetadata());
PipedInputStream parserInput = new PipedInputStream();
PipedOutputStream loaderOutput = new PipedOutputStream(parserInput);
dataParser.setDataSource(parserInput);
loader.setDebugOutputStream(loaderOutput);
}
if (pipeNamePrefix != null){//has no effect - infobright-core bug
loader.setPipeNamePrefix(pipeNamePrefix);
}
if (timeout > -1){
loader.setTimeout(timeout);
}
} catch (Exception e) {
throw new ComponentNotReadyException(this, e);
}
converter = new CloverValueConverter();
}
/**
* Creates brighthouse record from input metadata
*
* @param metadata input metadata
* @param jdbcSpecific connection specific (should be MYSQL)
* @param logger
* @return
* @throws SQLException when database error occurs
* @throws ComponentNotReadyException for wrong number or type of the fields
*/
private BrighthouseRecord createBrighthouseRecord(DataRecordMetadata metadata, JdbcSpecific jdbcSpecific,
EtlLogger logger) throws Exception{
Statement stmt = sqlConnection.createStatement();
ResultSet rs = stmt.executeQuery("select * from `" + table + "` limit 0");
ResultSetMetaData md = rs.getMetaData();
if (md.getColumnCount() != cloverFieldIndexes.length) {
throw new ComponentNotReadyException(this, "Number of db fields (" + md.getColumnCount()+ ") is different then " +
"number of clover fields (" + cloverFieldIndexes.length + ")." );
}
List<AbstractColumnType> columns = new ArrayList<AbstractColumnType>(md.getColumnCount());
AbstractColumnType col;
for (int i = 0; i < cloverFieldIndexes.length; i++) {
col = jetelType2Brighthouse(metadata.getField(cloverFieldIndexes[i]), md.getPrecision(i + 1), jdbcSpecific, logger);
col.setCheckValues(checkValues);
columns.add(col);
}
rs.close();
stmt.close();
return dataFormat.createRecord(columns, chset, logger);
}
/**
* Convert clover type to brighthouse type
*
* @param field field metadata
* @param precision length for character and binary fields, precision for decimal field
* @param jdbcSpecific connection specific (should be MYSQL)
* @param logger
* @return
* @throws ComponentNotReadyException
*/
private AbstractColumnType jetelType2Brighthouse(DataFieldMetadata field, int precision, JdbcSpecific jdbcSpecific, EtlLogger logger) throws ComponentNotReadyException{
String columnName = field.getName();
String columnTypeName = field.getTypeAsString();
switch (field.getType()) {
case DataFieldMetadata.BOOLEAN_FIELD:
logger.info(String.format("Column: %s %s(%d)", columnName, columnTypeName, 0));
return new BooleanType();
case DataFieldMetadata.BYTE_FIELD:
case DataFieldMetadata.BYTE_FIELD_COMPRESSED:
return AbstractColumnType.getInstance(columnName, field.isFixed() ? Types.BINARY : Types.VARBINARY, columnTypeName,
field.isFixed() ? field.getSize() : precision, 0, chset, logger);
case DataFieldMetadata.DATE_FIELD:
return AbstractColumnType.getInstance(columnName, jdbcSpecific.jetelType2sql(field), columnTypeName, 0, 0, chset, logger);
case DataFieldMetadata.DECIMAL_FIELD:
return AbstractColumnType.getInstance(columnName, Types.DECIMAL, columnTypeName,
field.getFieldProperties().getIntProperty(DataFieldMetadata.LENGTH_ATTR),
field.getFieldProperties().getIntProperty(DataFieldMetadata.SCALE_ATTR), chset, logger);
case DataFieldMetadata.INTEGER_FIELD:
return AbstractColumnType.getInstance(columnName, Types.INTEGER, columnTypeName, precision, 0, chset, logger);
case DataFieldMetadata.LONG_FIELD:
return AbstractColumnType.getInstance(columnName, Types.BIGINT, columnTypeName, precision, 0, chset, logger);
case DataFieldMetadata.NUMERIC_FIELD:
return AbstractColumnType.getInstance(columnName, Types.DOUBLE, columnTypeName, precision, 0, chset, logger);
case DataFieldMetadata.STRING_FIELD:
return AbstractColumnType.getInstance(columnName, field.isFixed() ? Types.CHAR : Types.VARCHAR, columnTypeName,
field.isFixed() ? field.getSize() : precision, 0, chset, logger);
default:
throw new ComponentNotReadyException(this, "Unsupported type (" + columnTypeName + ") for column " + columnName);
}
}
/* (non-Javadoc)
* @see org.jetel.graph.Node#execute()
*/
/* (non-Javadoc)
* @see org.jetel.graph.Node#preExecute()
*/
@Override
public void preExecute() throws ComponentNotReadyException {
try {
//create brighthouse record if it hasn't been created yet
if (bRecord == null) {
bRecord = createBrighthouseRecord(getInputPort(READ_FROM_PORT).getMetadata(), dbConnection.getJdbcSpecific(), log);
}
} catch (Exception e) {
throw new ComponentNotReadyException(this, e);
}
super.preExecute();
}
/* (non-Javadoc)
* @see org.jetel.graph.Node#execute()
*/
public Result execute() throws Exception {
Result result = Result.RUNNING;
Throwable ex = null;
InputPort inPort = getInputPort(READ_FROM_PORT);
DataRecord inRecord = new DataRecord(inPort.getMetadata());
inRecord.init();
//thread that writes data to database
InfoBrightWriter infobrightWriter =
new InfoBrightWriter(Thread.currentThread(), inPort, inRecord, cloverFieldIndexes, bRecord, converter, loader);
infobrightWriter.start();
registerChildThread(infobrightWriter);
PortWriter portWriter = null;
//thread that sends debug data to output port
if (dataParser != null) {
OutputPort outPort = getOutputPort(WRITE_TO_PORT);
DataRecord out_record = new DataRecord(outPort.getMetadata());
out_record.init();
portWriter = new PortWriter(Thread.currentThread(), outPort, out_record, dataParser);
portWriter.start();
registerChildThread(portWriter);
try {
portWriter.join();
} catch (InterruptedException e) {
runIt = false;
infobrightWriter.stop_it();//interrupt writing to database
resultMessage = "Writing to output port interrupted";
}
result = portWriter.getResultCode();
if (result == Result.ERROR){
resultMessage = "Port writer error: " + portWriter.getResultMsg();
ex = portWriter.getResultException();
}
}
try {
infobrightWriter.join();
} catch (InterruptedException e) {
runIt = false;
if (portWriter != null) {
portWriter.stop_it();//interrupt sending data to output port
}
resultMessage = "Writing to database interrupted";
}
if (infobrightWriter.getResultCode() == Result.ERROR) {
result = Result.ERROR;
resultMessage = (resultMessage == null ? "" : resultMessage + "\n") + "Infobright writer error: " + infobrightWriter.getResultMsg();
ex = infobrightWriter.getResultException();
}
if (result == Result.ERROR) {
throw new JetelException(resultMessage, ex);
}
return runIt ? Result.FINISHED_OK : Result.ABORTED;
}
/* (non-Javadoc)
* @see org.jetel.graph.GraphElement#postExecute(org.jetel.graph.TransactionMethod)
*/
public void postExecute(TransactionMethod transactionMethod) throws ComponentNotReadyException {
try {
if (transactionMethod.equals(TransactionMethod.ROLLBACK) || runResult == Result.ERROR) {
sqlConnection.rollback();
logger.warn(this.getId() + " finished with error. The current transaction has been rolled back.");
}else{
sqlConnection.commit();
}
} catch (Exception e) {
throw new ComponentNotReadyException(this, e);
}
super.postExecute(transactionMethod);
}
/* (non-Javadoc)
* @see org.jetel.graph.Node#getType()
*/
public String getType() {
return COMPONENT_TYPE;
}
/* (non-Javadoc)
* @see org.jetel.graph.Node#toXML(org.w3c.dom.Element)
*/
public void toXML(Element xmlElement) {
super.toXML(xmlElement);
xmlElement.setAttribute(XML_DATA_FORMAT_ATTRIBUTE, dataFormat.getBhDataFormat());
xmlElement.setAttribute(XML_TABLE_ATTRIBUTE, table);
xmlElement.setAttribute(XML_DBCONNECTION_ATTRIBUTE, connectionName != null ? connectionName : dbConnection.getId());
xmlElement.setAttribute(XML_CHECK_VALUES_ATTRIBUTE, String.valueOf(checkValues));
if (logFile != null) {
xmlElement.setAttribute(XML_LOG_FILE_ATTRIBUTE, logFile);
xmlElement.setAttribute(XML_APPEND_ATTRIBUTE, String.valueOf(append));
}
if (pipeNamePrefix != null) {
xmlElement.setAttribute(XML_PIPE_NAMEPREFIX_ATTRIBUTE, pipeNamePrefix);
}
if (timeout > -1){
xmlElement.setAttribute(XML_TIMEOUT_ATTRIBUTE, String.valueOf(timeout));
}
if (cloverFields != null){
xmlElement.setAttribute(XML_CLOVER_FIELDS_ATTRIBUTE, StringUtils.stringArraytoString(cloverFields, Defaults.Component.KEY_FIELDS_DELIMITER));
}
}
public static Node fromXML(TransformationGraph graph, Element xmlElement) throws XMLConfigurationException {
ComponentXMLAttributes xattribs = new ComponentXMLAttributes(xmlElement, graph);
InfobrightDataWriter loader;
try {
loader = new InfobrightDataWriter(xattribs.getString(XML_ID_ATTRIBUTE));
loader.setDbConnection(xattribs.getString(XML_DBCONNECTION_ATTRIBUTE));
loader.setTable(xattribs.getString(XML_TABLE_ATTRIBUTE));
if (xattribs.exists(XML_CHARSET_ATTRIBUTE)) {
loader.setCharset(xattribs.getString(XML_CHARSET_ATTRIBUTE));
}
if (xattribs.exists(XML_DATA_FORMAT_ATTRIBUTE)) {
loader.setDataFormat(xattribs.getString(XML_DATA_FORMAT_ATTRIBUTE));
}
if (xattribs.exists(XML_LOG_FILE_ATTRIBUTE)) {
loader.setLogFile(xattribs.getString(XML_LOG_FILE_ATTRIBUTE));
loader.setAppend(xattribs.getBoolean(XML_APPEND_ATTRIBUTE, false));
}
if (xattribs.exists(XML_PIPE_NAMEPREFIX_ATTRIBUTE)) {
loader.setPipeNamePrefix(xattribs.getString(XML_PIPE_NAMEPREFIX_ATTRIBUTE));
}
if (xattribs.exists(XML_TIMEOUT_ATTRIBUTE)) {
loader.setTimeout(xattribs.getInteger(XML_TIMEOUT_ATTRIBUTE));
}
if (xattribs.exists(XML_CLOVER_FIELDS_ATTRIBUTE)){
loader.setCloverFields(xattribs.getString(XML_CLOVER_FIELDS_ATTRIBUTE).split(Defaults.Component.KEY_FIELDS_DELIMITER_REGEX));
}
if (xattribs.exists(XML_CHECK_VALUES_ATTRIBUTE)){
loader.setCheckValues(xattribs.getBoolean(XML_CHECK_VALUES_ATTRIBUTE));
}
return loader;
} catch (Exception ex) {
throw new XMLConfigurationException(COMPONENT_TYPE + ":" + xattribs.getString(XML_ID_ATTRIBUTE," unknown ID ") + ":" + ex.getMessage(),ex);
}
}
/**
* Should strings and binary types be checked for size before being passed to the database?
* (Should be set to TRUE if you support an error path)
*
* @param checkValues
*/
public void setCheckValues(boolean checkValues) {
this.checkValues = checkValues;
}
/**
* @param table the table to set
*/
public void setTable(String table) {
this.table = table;
}
/**
* @param timeout the timeout to set
*/
public void setTimeout(int timeout) {
this.timeout = timeout;
}
/**
* @param cloverFields the cloverFields to set
*/
public void setCloverFields(String[] cloverFields) {
this.cloverFields = cloverFields;
}
/**
* @param pipeNamePrefix the pipeNamePrefix to set
*/
public void setPipeNamePrefix(String pipeNamePrefix) {
this.pipeNamePrefix = pipeNamePrefix;
}
/**
* @param logFile the logFile to set
*/
public void setLogFile(String logFile) {
this.logFile = logFile;
}
/**
* @param append the append to set
*/
public void setAppend(boolean append) {
this.append = append;
}
/**
* @param dbConnection the dbConnection to set
*/
public void setDbConnection(String dbConnection) {
this.connectionName = dbConnection;
}
/**
* @param dbConnection the dbConnection to set
*/
public void setDbConnection(DBConnection dbConnection) {
this.dbConnection = dbConnection;
}
/**
* @param dataFormat the dataFormat to set
*/
public void setDataFormat(String dataFormat) {
this.dataFormat = dataFormat.equalsIgnoreCase(DataFormat.BINARY.getBhDataFormat()) ?
DataFormat.BINARY : DataFormat.TXT_VARIABLE;
}
/**
* @param charset the charset to set
*/
public void setCharset(String charset) {
this.charset = charset;
}
private static class CommonsLogger implements EtlLogger {
Log logger;
/**
* @param logger
*/
public CommonsLogger(Log logger) {
this.logger = logger;
}
/* (non-Javadoc)
* @see com.infobright.logging.EtlLogger#debug(java.lang.String)
*/
public void debug(String s) {
logger.debug(s);
}
/* (non-Javadoc)
* @see com.infobright.logging.EtlLogger#error(java.lang.String)
*/
public void error(String s) {
logger.error(s);
}
/* (non-Javadoc)
* @see com.infobright.logging.EtlLogger#error(java.lang.String, java.lang.Throwable)
*/
public void error(String s, Throwable cause) {
logger.error(s, cause);
}
/* (non-Javadoc)
* @see com.infobright.logging.EtlLogger#fatal(java.lang.String)
*/
public void fatal(String s) {
logger.fatal(s);
}
/* (non-Javadoc)
* @see com.infobright.logging.EtlLogger#info(java.lang.String)
*/
public void info(String s) {
logger.info(s);
}
/* (non-Javadoc)
* @see com.infobright.logging.EtlLogger#trace(java.lang.String)
*/
public void trace(String s) {
logger.trace(s);
}
/* (non-Javadoc)
* @see com.infobright.logging.EtlLogger#warn(java.lang.String)
*/
public void warn(String s) {
logger.warn(s);
}
}
private static class DumbLogger implements EtlLogger {
/* (non-Javadoc)
* @see com.infobright.logging.EtlLogger#debug(java.lang.String)
*/
public void debug(String s) {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see com.infobright.logging.EtlLogger#error(java.lang.String)
*/
public void error(String s) {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see com.infobright.logging.EtlLogger#error(java.lang.String, java.lang.Throwable)
*/
public void error(String s, Throwable cause) {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see com.infobright.logging.EtlLogger#fatal(java.lang.String)
*/
public void fatal(String s) {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see com.infobright.logging.EtlLogger#info(java.lang.String)
*/
public void info(String s) {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see com.infobright.logging.EtlLogger#trace(java.lang.String)
*/
public void trace(String s) {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see com.infobright.logging.EtlLogger#warn(java.lang.String)
*/
public void warn(String s) {
// TODO Auto-generated method stub
}
}
private static class InfoBrightWriter extends Thread {
InputPort inPort;
DataRecord in_record;
String resultMsg=null;
Result resultCode;
volatile boolean runIt;
Throwable resultException;
private int[] cloverFields;
private BrighthouseRecord bRecord;
private ValueConverter converter;
private OutputStream output;
private InfobrightNamedPipeLoader loader;
InfoBrightWriter(Thread parentThread,InputPort inPort,DataRecord in_record,int[] cloverFields, BrighthouseRecord bRecord,
ValueConverter converter, InfobrightNamedPipeLoader loader) throws IOException{
super(parentThread.getName()+".InfoBrightWriter");
this.in_record=in_record;
this.inPort=inPort;
this.cloverFields = cloverFields;
this.bRecord = bRecord;
this.converter = converter;
runIt=true;
this.loader = loader;
}
public void stop_it(){
runIt=false;
}
public void run() {
resultCode = Result.RUNNING;
try{
loader.start();
output = loader.getOutputStream2();
while (runIt && (( in_record=inPort.readRecord(in_record))!= null )) {
for (int i = 0; i < cloverFields.length; i++) {
bRecord.setData(i, in_record.getField(cloverFields[i]), converter);
}
bRecord.writeTo(output);
SynchronizeUtils.cloverYield();
}
}catch(IOException ex){
resultMsg = ex.getMessage();
resultCode = Result.ERROR;
resultException = ex;
resultMsg = ex.getMessage();
}catch (InterruptedException ex){
resultCode = Result.ABORTED;
}catch(Exception ex){
resultMsg = ex.getMessage();
resultCode = Result.ERROR;
resultException = ex;
} finally{
try {
loader.stop();
} catch (Exception e) {
resultMsg = e.getMessage();
resultCode = Result.ERROR;
resultException = e;
}
}
if (resultCode==Result.RUNNING){
if (runIt){
resultCode=Result.FINISHED_OK;
}else{
resultCode = Result.ABORTED;
}
}
}
public Result getResultCode() {
return resultCode;
}
public String getResultMsg() {
return resultMsg;
}
public Throwable getResultException() {
return resultException;
}
}
private static class PortWriter extends Thread {
DataRecord out_record;
OutputPort outPort;
Parser parser;
String resultMsg=null;
Result resultCode;
volatile boolean runIt;
Throwable resultException;
PortWriter(Thread parentThread,OutputPort outPort,DataRecord out_record,Parser parser){
super(parentThread.getName()+".SendData");
this.out_record=out_record;
this.parser=parser;
this.outPort=outPort;
this.runIt=true;
}
public void stop_it(){
runIt=false;
}
public void run() {
resultCode=Result.RUNNING;
try{
while (runIt && ((out_record = parser.getNext(out_record))!= null) ) {
outPort.writeRecord(out_record);
SynchronizeUtils.cloverYield();
}
}catch(IOException ex){
resultMsg = ex.getMessage();
resultCode = Result.ERROR;
resultException = ex;
}catch (InterruptedException ex){
resultCode = Result.ABORTED;
}catch(Exception ex){
resultMsg = ex.getMessage();
resultCode = Result.ERROR;
resultException = ex;
}finally{
try {
parser.close();
} catch (Exception e) {
resultMsg = e.getMessage();
resultCode = Result.ERROR;
resultException = e;
}
}
if (resultCode == Result.RUNNING)
if (runIt) {
resultCode = Result.FINISHED_OK;
} else {
resultCode = Result.ABORTED;
}
}
/**
* @return Returns the resultCode.
*/
public Result getResultCode() {
return resultCode;
}
public String getResultMsg() {
return resultMsg;
}
public Throwable getResultException() {
return resultException;
}
}
}
|
// $Id: GMS.java,v 1.15 2004/08/31 16:29:25 belaban Exp $
package org.jgroups.protocols.pbcast;
import org.jgroups.*;
import org.jgroups.stack.Protocol;
import org.jgroups.util.BoundedList;
import org.jgroups.util.TimeScheduler;
import org.jgroups.util.Util;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.Serializable;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Properties;
import java.util.Vector;
/**
* Group membership protocol. Handles joins/leaves/crashes (suspicions) and emits new views
* accordingly. Use VIEW_ENFORCER on top of this layer to make sure new members don't receive
* any messages until they are members.
*/
public class GMS extends Protocol {
private GmsImpl impl=null;
public Address local_addr=null;
public String group_addr=null;
public Membership members=new Membership(); // real membership
public Membership tmp_members=new Membership(); // base for computing next view
/** Members joined but for which no view has been received yet */
public Vector joining=new Vector(7);
/** Members excluded from group, but for which no view has been received yet */
public Vector leaving=new Vector(7);
public ViewId view_id=null;
public long ltime=0;
public long join_timeout=5000;
public long join_retry_timeout=2000;
public long leave_timeout=5000;
public long digest_timeout=5000; // time to wait for a digest (from PBCAST). should be fast
public long merge_timeout=10000; // time to wait for all MERGE_RSPS
public Object impl_mutex=new Object(); // synchronizes event entry into impl
private Object digest_mutex=new Object(); // synchronizes the GET_DIGEST/GET_DIGEST_OK events
private Digest digest=null; // holds result of GET_DIGEST event
private Hashtable impls=new Hashtable(3);
private boolean shun=true;
private boolean print_local_addr=true;
boolean disable_initial_coord=false; // can the member become a coord on startup or not ?
final String CLIENT="Client";
final String COORD="Coordinator";
final String PART="Participant";
TimeScheduler timer=null;
/** Max number of old members to keep in history */
protected int num_prev_mbrs=50;
/** Keeps track of old members (up to num_prev_mbrs) */
BoundedList prev_members=null;
public GMS() {
initState();
}
public String getName() {
return "GMS";
}
public Vector requiredDownServices() {
Vector retval=new Vector(3);
retval.addElement(new Integer(Event.GET_DIGEST));
retval.addElement(new Integer(Event.SET_DIGEST));
retval.addElement(new Integer(Event.FIND_INITIAL_MBRS));
return retval;
}
public void setImpl(GmsImpl new_impl) {
synchronized(impl_mutex) {
impl=new_impl;
if(log.isDebugEnabled())
log.debug(local_addr + ": changed role to " + new_impl.getClass().getName());
}
}
public GmsImpl getImpl() {
return impl;
}
public void init() throws Exception {
prev_members=new BoundedList(num_prev_mbrs);
timer=stack != null? stack.timer : null;
if(timer == null)
throw new Exception("GMS.init(): timer is null");
if(impl != null)
impl.init();
}
public void start() throws Exception {
if(impl != null) impl.start();
}
public void stop() {
if(impl != null) impl.stop();
if(prev_members != null)
prev_members.removeAll();
}
public void becomeCoordinator() {
CoordGmsImpl tmp=(CoordGmsImpl)impls.get(COORD);
if(tmp == null) {
tmp=new CoordGmsImpl(this);
impls.put(COORD, tmp);
}
tmp.leaving=false;
setImpl(tmp);
if(log.isDebugEnabled()) log.debug(local_addr + " became coordinator");
}
public void becomeParticipant() {
ParticipantGmsImpl tmp=(ParticipantGmsImpl)impls.get(PART);
if(tmp == null) {
tmp=new ParticipantGmsImpl(this);
impls.put(PART, tmp);
}
tmp.leaving=false;
setImpl(tmp);
if(log.isDebugEnabled()) log.debug(local_addr + " became participant");
}
public void becomeClient() {
ClientGmsImpl tmp=(ClientGmsImpl)impls.get(CLIENT);
if(tmp == null) {
tmp=new ClientGmsImpl(this);
impls.put(CLIENT, tmp);
}
tmp.initial_mbrs.removeAllElements();
setImpl(tmp);
if(log.isDebugEnabled()) log.debug(local_addr + " became client");
}
boolean haveCoordinatorRole() {
return impl != null && impl instanceof CoordGmsImpl;
}
/**
* Computes the next view. Returns a copy that has <code>old_mbrs</code> and
* <code>suspected_mbrs</code> removed and <code>new_mbrs</code> added.
*/
public View getNextView(Vector new_mbrs, Vector old_mbrs, Vector suspected_mbrs) {
Vector mbrs;
long vid=0;
View v;
Membership tmp_mbrs=null;
Address tmp_mbr;
synchronized(members) {
if(view_id == null) {
if(log.isErrorEnabled()) log.error("view_id is null");
return null; // this should *never* happen !
}
vid=Math.max(view_id.getId(), ltime) + 1;
ltime=vid;
if(log.isDebugEnabled()) log.debug("VID=" + vid + ", current members=" +
Util.printMembers(members.getMembers()) +
", new_mbrs=" + Util.printMembers(new_mbrs) +
", old_mbrs=" + Util.printMembers(old_mbrs) + ", suspected_mbrs=" +
Util.printMembers(suspected_mbrs));
tmp_mbrs=tmp_members.copy(); // always operate on the temporary membership
tmp_mbrs.remove(suspected_mbrs);
tmp_mbrs.remove(old_mbrs);
tmp_mbrs.add(new_mbrs);
mbrs=tmp_mbrs.getMembers();
v=new View(local_addr, vid, mbrs);
// Update membership (see DESIGN for explanation):
tmp_members.set(mbrs);
// Update joining list (see DESIGN for explanation)
if(new_mbrs != null) {
for(int i=0; i < new_mbrs.size(); i++) {
tmp_mbr=(Address)new_mbrs.elementAt(i);
if(!joining.contains(tmp_mbr))
joining.addElement(tmp_mbr);
}
}
// Update leaving list (see DESIGN for explanations)
if(old_mbrs != null) {
for(Iterator it=old_mbrs.iterator(); it.hasNext();) {
Address addr=(Address)it.next();
if(!leaving.contains(addr))
leaving.add(addr);
}
}
if(suspected_mbrs != null) {
for(Iterator it=suspected_mbrs.iterator(); it.hasNext();) {
Address addr=(Address)it.next();
if(!leaving.contains(addr))
leaving.add(addr);
}
}
if(log.isDebugEnabled()) log.debug("new view is " + v);
return v;
}
}
/**
Compute a new view, given the current view, the new members and the suspected/left
members. Then simply mcast the view to all members. This is different to the VS GMS protocol,
in which we run a FLUSH protocol which tries to achive consensus on the set of messages mcast in
the current view before proceeding to install the next view.
The members for the new view are computed as follows:
<pre>
existing leaving suspected joining
1. new_view y n n y
2. tmp_view y y n y
(view_dest)
</pre>
<ol>
<li>
The new view to be installed includes the existing members plus the joining ones and
excludes the leaving and suspected members.
<li>
A temporary view is sent down the stack as an <em>event</em>. This allows the bottom layer
(e.g. UDP or TCP) to determine the members to which to send a multicast message. Compared
to the new view, leaving members are <em>included</em> since they have are waiting for a
view in which they are not members any longer before they leave. So, if we did not set a
temporary view, joining members would not receive the view (signalling that they have been
joined successfully). The temporary view is essentially the current view plus the joining
members (old members are still part of the current view).
</ol>
@return View The new view
*/
public View castViewChange(Vector new_mbrs, Vector old_mbrs, Vector suspected_mbrs) {
View new_view;
// next view: current mbrs + new_mbrs - old_mbrs - suspected_mbrs
new_view=getNextView(new_mbrs, old_mbrs, suspected_mbrs);
castViewChange(new_view);
return new_view;
}
public void castViewChange(View new_view) {
castViewChange(new_view, null);
}
public void castViewChange(View new_view, Digest digest) {
Message view_change_msg;
GmsHeader hdr;
if(log.isDebugEnabled()) log.debug("mcasting view {" + new_view + "} (" + new_view.size() + " mbrs)\n");
view_change_msg=new Message(); // bcast to all members
hdr=new GmsHeader(GmsHeader.VIEW, new_view);
hdr.digest=digest;
view_change_msg.putHeader(getName(), hdr);
passDown(new Event(Event.MSG, view_change_msg));
}
/**
* Sets the new view and sends a VIEW_CHANGE event up and down the stack. If the view is a MergeView (subclass
* of View), then digest will be non-null and has to be set before installing the view.
*/
public void installView(View new_view, Digest digest) {
if(digest != null)
mergeDigest(digest);
installView(new_view);
}
/**
* Sets the new view and sends a VIEW_CHANGE event up and down the stack.
*/
public void installView(View new_view) {
Address coord;
int rc;
ViewId vid=new_view.getVid();
Vector mbrs=new_view.getMembers();
if(log.isDebugEnabled()) log.debug("[local_addr=" + local_addr + "] view is " + new_view);
// Discards view with id lower than our own. Will be installed without check if first view
if(view_id != null) {
rc=vid.compareTo(view_id);
if(rc <= 0) {
if(log.isErrorEnabled())
log.error("[" + local_addr + "] received view <= current view;" +
" discarding it (current vid: " + view_id + ", new vid: " + vid + ')');
return;
}
}
ltime=Math.max(vid.getId(), ltime); // compute Lamport logical time
/* Check for self-inclusion: if I'm not part of the new membership, I just discard it.
This ensures that messages sent in view V1 are only received by members of V1 */
if(checkSelfInclusion(mbrs) == false) {
if(log.isWarnEnabled()) log.warn("checkSelfInclusion() failed, " + local_addr +
" is not a member of view " + new_view + "; discarding view");
// only shun if this member was previously part of the group. avoids problem where multiple
// members (e.g. X,Y,Z) join {A,B} concurrently, X is joined first, and Y and Z get view
// {A,B,X}, which would cause Y and Z to be shunned as they are not part of the membership
// bela Nov 20 2003
if(shun && local_addr != null && prev_members.contains(local_addr)) {
if(log.isWarnEnabled())
log.warn("I (" + local_addr + ") am being shunned, will leave and " +
"rejoin group (prev_members are " + prev_members + ')');
passUp(new Event(Event.EXIT));
}
return;
}
synchronized(members) { // serialize access to views
// assign new_view to view_id
view_id=vid.copy();
// Set the membership. Take into account joining members
if(mbrs != null && mbrs.size() > 0) {
members.set(mbrs);
tmp_members.set(members);
joining.removeAll(mbrs); // remove all members in mbrs from joining
// remove all elements from 'leaving' that are not in 'mbrs'
leaving.retainAll(mbrs);
tmp_members.add(joining); // add members that haven't yet shown up in the membership
tmp_members.remove(leaving); // remove members that haven't yet been removed from the membership
// add to prev_members
for(Iterator it=mbrs.iterator(); it.hasNext();) {
Address addr=(Address)it.next();
if(!prev_members.contains(addr))
prev_members.add(addr);
}
}
// Send VIEW_CHANGE event up and down the stack:
Event view_event=new Event(Event.VIEW_CHANGE, new_view.clone());
passDown(view_event); // needed e.g. by failure detector or UDP
passUp(view_event);
coord=determineCoordinator();
// if(coord != null && coord.equals(local_addr) && !(coord.equals(vid.getCoordAddress()))) {
// changed on suggestion by yaronr
if(coord != null && coord.equals(local_addr)) {
becomeCoordinator();
}
else {
if(haveCoordinatorRole() && !local_addr.equals(coord))
becomeParticipant();
}
}
}
protected Address determineCoordinator() {
synchronized(members) {
return members != null && members.size() > 0? (Address)members.elementAt(0) : null;
}
}
/** Checks whether the potential_new_coord would be the new coordinator (2nd in line) */
protected boolean wouldBeNewCoordinator(Address potential_new_coord) {
Address new_coord=null;
if(potential_new_coord == null) return false;
synchronized(members) {
if(members.size() < 2) return false;
new_coord=(Address)members.elementAt(1); // member at 2nd place
if(new_coord != null && new_coord.equals(potential_new_coord))
return true;
return false;
}
}
/** Returns true if local_addr is member of mbrs, else false */
protected boolean checkSelfInclusion(Vector mbrs) {
Object mbr;
if(mbrs == null)
return false;
for(int i=0; i < mbrs.size(); i++) {
mbr=mbrs.elementAt(i);
if(mbr != null && local_addr.equals(mbr))
return true;
}
return false;
}
public View makeView(Vector mbrs) {
Address coord=null;
long id=0;
if(view_id != null) {
coord=view_id.getCoordAddress();
id=view_id.getId();
}
return new View(coord, id, mbrs);
}
public View makeView(Vector mbrs, ViewId vid) {
Address coord=null;
long id=0;
if(vid != null) {
coord=vid.getCoordAddress();
id=vid.getId();
}
return new View(coord, id, mbrs);
}
/** Send down a SET_DIGEST event */
public void setDigest(Digest d) {
passDown(new Event(Event.SET_DIGEST, d));
}
/** Send down a MERGE_DIGEST event */
public void mergeDigest(Digest d) {
passDown(new Event(Event.MERGE_DIGEST, d));
}
/** Sends down a GET_DIGEST event and waits for the GET_DIGEST_OK response, or
timeout, whichever occurs first */
public Digest getDigest() {
Digest ret=null;
synchronized(digest_mutex) {
digest=null;
passDown(new Event(Event.GET_DIGEST));
if(digest == null) {
try {
digest_mutex.wait(digest_timeout);
}
catch(Exception ex) {
}
}
if(digest != null) {
ret=digest;
digest=null;
return ret;
}
else {
if(log.isErrorEnabled()) log.error("digest could not be fetched from PBCAST layer");
return null;
}
}
}
public void up(Event evt) {
Object obj;
Message msg;
GmsHeader hdr;
MergeData merge_data;
switch(evt.getType()) {
case Event.MSG:
msg=(Message)evt.getArg();
obj=msg.getHeader(getName());
if(obj == null || !(obj instanceof GmsHeader))
break;
hdr=(GmsHeader)msg.removeHeader(getName());
switch(hdr.type) {
case GmsHeader.JOIN_REQ:
handleJoinRequest(hdr.mbr);
break;
case GmsHeader.JOIN_RSP:
impl.handleJoinResponse(hdr.join_rsp);
break;
case GmsHeader.LEAVE_REQ:
if(log.isDebugEnabled()) log.debug("received LEAVE_REQ " + hdr + " from " + msg.getSrc());
if(hdr.mbr == null) {
if(log.isErrorEnabled()) log.error("LEAVE_REQ's mbr field is null");
return;
}
sendLeaveResponse(hdr.mbr);
impl.handleLeave(hdr.mbr, false);
break;
case GmsHeader.LEAVE_RSP:
impl.handleLeaveResponse();
break;
case GmsHeader.VIEW:
if(hdr.view == null) {
if(log.isErrorEnabled()) log.error("[VIEW]: view == null");
return;
}
impl.handleViewChange(hdr.view, hdr.digest);
break;
case GmsHeader.MERGE_REQ:
impl.handleMergeRequest(msg.getSrc(), hdr.merge_id);
break;
case GmsHeader.MERGE_RSP:
merge_data=new MergeData(msg.getSrc(), hdr.view, hdr.digest);
merge_data.merge_rejected=hdr.merge_rejected;
impl.handleMergeResponse(merge_data, hdr.merge_id);
break;
case GmsHeader.INSTALL_MERGE_VIEW:
impl.handleMergeView(new MergeData(msg.getSrc(), hdr.view, hdr.digest), hdr.merge_id);
break;
case GmsHeader.CANCEL_MERGE:
impl.handleMergeCancelled(hdr.merge_id);
break;
default:
if(log.isErrorEnabled()) log.error("GmsHeader with type=" + hdr.type + " not known");
}
return; // don't pass up
case Event.CONNECT_OK: // sent by someone else, but WE are responsible for sending this !
case Event.DISCONNECT_OK: // dito (e.g. sent by UDP layer). Don't send up the stack
return;
case Event.SET_LOCAL_ADDRESS:
local_addr=(Address)evt.getArg();
if(print_local_addr) {
System.out.println("\n
"GMS: address is " + local_addr +
"\n
}
break; // pass up
case Event.SUSPECT:
impl.suspect((Address)evt.getArg());
break; // pass up
case Event.UNSUSPECT:
impl.unsuspect((Address)evt.getArg());
return; // discard
case Event.MERGE:
impl.merge((Vector)evt.getArg());
return; // don't pass up
}
if(impl.handleUpEvent(evt))
passUp(evt);
}
/**
This method is overridden to avoid hanging on getDigest(): when a JOIN is received, the coordinator needs
to retrieve the digest from the PBCAST layer. It therefore sends down a GET_DIGEST event, to which the PBCAST layer
responds with a GET_DIGEST_OK event.<p>
However, the GET_DIGEST_OK event will not be processed because the thread handling the JOIN request won't process
the GET_DIGEST_OK event until the JOIN event returns. The receiveUpEvent() method is executed by the up-handler
thread of the lower protocol and therefore can handle the event. All we do here is unblock the mutex on which
JOIN is waiting, allowing JOIN to return with a valid digest. The GET_DIGEST_OK event is then discarded, because
it won't be processed twice.
*/
public void receiveUpEvent(Event evt) {
if(evt.getType() == Event.GET_DIGEST_OK) {
synchronized(digest_mutex) {
digest=(Digest)evt.getArg();
digest_mutex.notifyAll();
}
return;
}
super.receiveUpEvent(evt);
}
public void down(Event evt) {
switch(evt.getType()) {
case Event.CONNECT:
passDown(evt);
try {
group_addr=(String)evt.getArg();
}
catch(ClassCastException cce) {
if(log.isErrorEnabled()) log.error("[CONNECT]: group address must be a string (channel name)");
}
if(local_addr == null)
if(log.isFatalEnabled()) log.fatal("[CONNECT] local_addr is null");
impl.join(local_addr);
passUp(new Event(Event.CONNECT_OK));
return; // don't pass down: was already passed down
case Event.DISCONNECT:
impl.leave((Address)evt.getArg());
passUp(new Event(Event.DISCONNECT_OK));
initState(); // in case connect() is called again
break; // pass down
}
if(impl.handleDownEvent(evt))
passDown(evt);
}
/** Setup the Protocol instance according to the configuration string */
public boolean setProperties(Properties props) {
String str;
super.setProperties(props);
str=props.getProperty("shun");
if(str != null) {
shun=Boolean.valueOf(str).booleanValue();
props.remove("shun");
}
str=props.getProperty("print_local_addr");
if(str != null) {
print_local_addr=Boolean.valueOf(str).booleanValue();
props.remove("print_local_addr");
}
str=props.getProperty("join_timeout"); // time to wait for JOIN
if(str != null) {
join_timeout=Long.parseLong(str);
props.remove("join_timeout");
}
str=props.getProperty("join_retry_timeout"); // time to wait between JOINs
if(str != null) {
join_retry_timeout=Long.parseLong(str);
props.remove("join_retry_timeout");
}
str=props.getProperty("leave_timeout"); // time to wait until coord responds to LEAVE req.
if(str != null) {
leave_timeout=Long.parseLong(str);
props.remove("leave_timeout");
}
str=props.getProperty("merge_timeout"); // time to wait for MERGE_RSPS from subgroup coordinators
if(str != null) {
merge_timeout=Long.parseLong(str);
props.remove("merge_timeout");
}
str=props.getProperty("digest_timeout"); // time to wait for GET_DIGEST_OK from PBCAST
if(str != null) {
digest_timeout=Long.parseLong(str);
props.remove("digest_timeout");
}
str=props.getProperty("disable_initial_coord");
if(str != null) {
disable_initial_coord=Boolean.valueOf(str).booleanValue();
props.remove("disable_initial_coord");
}
str=props.getProperty("num_prev_mbrs");
if(str != null) {
num_prev_mbrs=Integer.parseInt(str);
props.remove("num_prev_mbrs");
}
if(props.size() > 0) {
System.err.println("GMS.setProperties(): the following properties are not recognized:");
props.list(System.out);
return false;
}
return true;
}
void initState() {
becomeClient();
view_id=null;
}
void handleJoinRequest(Address mbr) {
JoinRsp join_rsp;
Message m;
GmsHeader hdr;
if(mbr == null) {
if(log.isErrorEnabled()) log.error("mbr is null");
return;
}
if(log.isDebugEnabled()) log.debug("mbr=" + mbr);
// 1. Get the new view and digest
join_rsp=impl.handleJoin(mbr);
if(join_rsp == null)
if(log.isErrorEnabled())
log.error(impl.getClass().toString() + ".handleJoin(" + mbr +
") returned null: will not be able to multicast new view");
// 2. Send down a local TMP_VIEW event. This is needed by certain layers (e.g. NAKACK) to compute correct digest
// in case client's next request (e.g. getState()) reaches us *before* our own view change multicast.
// Check NAKACK's TMP_VIEW handling for details
if(join_rsp != null && join_rsp.getView() != null)
passDown(new Event(Event.TMP_VIEW, join_rsp.getView()));
// 3. Return result to client
m=new Message(mbr, null, null);
hdr=new GmsHeader(GmsHeader.JOIN_RSP, join_rsp);
m.putHeader(getName(), hdr);
passDown(new Event(Event.MSG, m));
// 4. Bcast the new view
if(join_rsp != null)
castViewChange(join_rsp.getView());
}
void sendLeaveResponse(Address mbr) {
Message msg=new Message(mbr, null, null);
GmsHeader hdr=new GmsHeader(GmsHeader.LEAVE_RSP);
msg.putHeader(getName(), hdr);
passDown(new Event(Event.MSG, msg));
}
public static class GmsHeader extends Header {
public static final int JOIN_REQ=1;
public static final int JOIN_RSP=2;
public static final int LEAVE_REQ=3;
public static final int LEAVE_RSP=4;
public static final int VIEW=5;
public static final int MERGE_REQ=6;
public static final int MERGE_RSP=7;
public static final int INSTALL_MERGE_VIEW=8;
public static final int CANCEL_MERGE=9;
int type=0;
View view=null; // used when type=VIEW or MERGE_RSP or INSTALL_MERGE_VIEW
Address mbr=null; // used when type=JOIN_REQ or LEAVE_REQ
JoinRsp join_rsp=null; // used when type=JOIN_RSP
Digest digest=null; // used when type=MERGE_RSP or INSTALL_MERGE_VIEW
Serializable merge_id=null; // used when type=MERGE_REQ or MERGE_RSP or INSTALL_MERGE_VIEW or CANCEL_MERGE
boolean merge_rejected=false; // used when type=MERGE_RSP
public GmsHeader() {
} // used for Externalization
public GmsHeader(int type) {
this.type=type;
}
/** Used for VIEW header */
public GmsHeader(int type, View view) {
this.type=type;
this.view=view;
}
/** Used for JOIN_REQ or LEAVE_REQ header */
public GmsHeader(int type, Address mbr) {
this.type=type;
this.mbr=mbr;
}
/** Used for JOIN_RSP header */
public GmsHeader(int type, JoinRsp join_rsp) {
this.type=type;
this.join_rsp=join_rsp;
}
public String toString() {
StringBuffer sb=new StringBuffer("GmsHeader");
sb.append('[' + type2String(type) + ']');
switch(type) {
case JOIN_REQ:
sb.append(": mbr=" + mbr);
break;
case JOIN_RSP:
sb.append(": join_rsp=" + join_rsp);
break;
case LEAVE_REQ:
sb.append(": mbr=" + mbr);
break;
case LEAVE_RSP:
break;
case VIEW:
sb.append(": view=" + view);
break;
case MERGE_REQ:
sb.append(": merge_id=" + merge_id);
break;
case MERGE_RSP:
sb.append(": view=" + view + ", digest=" + digest + ", merge_rejected=" + merge_rejected +
", merge_id=" + merge_id);
break;
case INSTALL_MERGE_VIEW:
sb.append(": view=" + view + ", digest=" + digest);
break;
case CANCEL_MERGE:
sb.append(", <merge cancelled>, merge_id=" + merge_id);
break;
}
sb.append('\n');
return sb.toString();
}
public static String type2String(int type) {
switch(type) {
case JOIN_REQ:
return "JOIN_REQ";
case JOIN_RSP:
return "JOIN_RSP";
case LEAVE_REQ:
return "LEAVE_REQ";
case LEAVE_RSP:
return "LEAVE_RSP";
case VIEW:
return "VIEW";
case MERGE_REQ:
return "MERGE_REQ";
case MERGE_RSP:
return "MERGE_RSP";
case INSTALL_MERGE_VIEW:
return "INSTALL_MERGE_VIEW";
case CANCEL_MERGE:
return "CANCEL_MERGE";
default:
return "<unknown>";
}
}
public void writeExternal(ObjectOutput out) throws IOException {
out.writeInt(type);
out.writeObject(view);
out.writeObject(mbr);
out.writeObject(join_rsp);
out.writeObject(digest);
out.writeObject(merge_id);
out.writeBoolean(merge_rejected);
}
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
type=in.readInt();
view=(View)in.readObject();
mbr=(Address)in.readObject();
join_rsp=(JoinRsp)in.readObject();
digest=(Digest)in.readObject();
merge_id=(Serializable)in.readObject();
merge_rejected=in.readBoolean();
}
}
}
|
package <%=packageName%>.domain;
<% if (databaseType == 'cassandra') { %>
import com.datastax.driver.mapping.annotations.*;<% } %><%
var importJsonignore = false;
for (relationshipId in relationships) {
if (relationships[relationshipId].relationshipType == 'one-to-many') {
importJsonignore = true;
} else if (relationships[relationshipId].relationshipType == 'one-to-one' && relationships[relationshipId].ownerSide == false) {
importJsonignore = true;
} else if (relationships[relationshipId].relationshipType == 'many-to-many' && relationships[relationshipId].ownerSide == false) {
importJsonignore = true;
}
}
if (importJsonignore) { %>
import com.fasterxml.jackson.annotation.JsonIgnore;<% } %><% if (fieldsContainCustomTime == true) { %>
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;<% } %><% if (fieldsContainLocalDate == true) { %>
import <%=packageName%>.domain.util.CustomLocalDateSerializer;
import <%=packageName%>.domain.util.ISO8601LocalDateDeserializer;<% } %><% if (fieldsContainDateTime == true) { %>
import <%=packageName%>.domain.util.CustomDateTimeDeserializer;
import <%=packageName%>.domain.util.CustomDateTimeSerializer;<% } %><% if (hibernateCache != 'no') { %>
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;<% } %><% if (fieldsContainCustomTime == true && databaseType == 'sql') { %>
import org.hibernate.annotations.Type;<% } %><% if (fieldsContainLocalDate == true) { %>
import org.joda.time.LocalDate;<% } %><% if (fieldsContainDateTime == true) { %>
import org.joda.time.DateTime;<% } %><% if (databaseType == 'mongodb') { %>
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;<% } %><% if (searchEngine == 'elasticsearch') { %>
import org.springframework.data.elasticsearch.annotations.Document;<% } %>
<% if (databaseType == 'sql') { %>
import javax.persistence.*;<% } %><% if (validation) { %>
import javax.validation.constraints.*;<% } %>
import java.io.Serializable;<% if (fieldsContainBigDecimal == true) { %>
import java.math.BigDecimal;<% } %><% if (fieldsContainDate == true) { %>
import java.util.Date;<% } %><% if (relationships.length > 0) { %>
import java.util.HashSet;
import java.util.Set;<% } %>
import java.util.Objects;<% if (databaseType == 'cassandra') { %>
import java.util.UUID;<% } %>
<%
var uniqueEnums = {};
for (fieldId in fields) {
if (fields[fieldId].fieldIsEnum && (
!uniqueEnums[fields[fieldId].fieldType] || (uniqueEnums[fields[fieldId].fieldType] && fields[fieldId].fieldValues.length !== 0))) {
uniqueEnums[fields[fieldId].fieldType] = fields[fieldId].fieldType;
}
}
Object.keys(uniqueEnums).forEach(function(element) {%>
import <%=packageName%>.domain.enumeration.<%= element %>;<% }); %>
/**
* A <%= entityClass %>.
*/<% if (databaseType == 'sql') { %>
@Entity
@Table(name = "<%= name.toUpperCase() %>")<% if (hibernateCache != 'no') { %>
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)<% } %><% } %><% if (databaseType == 'mongodb') { %>
@Document(collection = "<%= name.toUpperCase() %>")<% } %><% if (databaseType == 'cassandra') { %>
@Table(name = "<%= entityInstance %>")<% } %><% if (searchEngine == 'elasticsearch') { %>
@Document(indexName="<%= entityInstance.toLowerCase() %>")<% } %>
public class <%= entityClass %> implements Serializable {
<% if (databaseType == 'sql') { %>
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;<% } %><% if (databaseType == 'mongodb') { %>
@Id
private String id;<% } %><% if (databaseType == 'cassandra') { %>
@PartitionKey
private UUID id;<% } %>
<% for (fieldId in fields) { %><% if (fields[fieldId].fieldValidate == true) {
var required = false;
if (fields[fieldId].fieldValidate == true && fields[fieldId].fieldValidateRules.indexOf('required') != -1) {
required = true;
}
if (required) { %>
@NotNull<% } %><% if (fields[fieldId].fieldValidateRules.indexOf('minlength') != -1 && fields[fieldId].fieldValidateRules.indexOf('maxlength') == -1) { %>
@Size(min = <%= fields[fieldId].fieldValidateRulesMinlength %>)<% } %><% if (fields[fieldId].fieldValidateRules.indexOf('maxlength') != -1 && fields[fieldId].fieldValidateRules.indexOf('minlength') == -1) { %>
@Size(max = <%= fields[fieldId].fieldValidateRulesMaxlength %>)<% } %><% if (fields[fieldId].fieldValidateRules.indexOf('minlength') != -1 && fields[fieldId].fieldValidateRules.indexOf('maxlength') != -1) { %>
@Size(min = <%= fields[fieldId].fieldValidateRulesMinlength %>, max = <%= fields[fieldId].fieldValidateRulesMaxlength %>)<% } %><% if (fields[fieldId].fieldValidateRules.indexOf('min') != -1) { %>
@Min(value = <%= fields[fieldId].fieldValidateRulesMin %>)<% } %><% if (fields[fieldId].fieldValidateRules.indexOf('max') != -1) { %>
@Max(value = <%= fields[fieldId].fieldValidateRulesMax %>)<% } %><% if (fields[fieldId].fieldValidateRules.indexOf('pattern') != -1) { %>
@Pattern(regexp = "<%= fields[fieldId].fieldValidateRulesPattern %>")<% } } %><% if (databaseType == 'sql') { %><% if (fields[fieldId].fieldIsEnum) { %>
@Enumerated(EnumType.STRING)<% } %><% if (fields[fieldId].fieldType == 'DateTime') { %>
@Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
@JsonSerialize(using = CustomDateTimeSerializer.class)
@JsonDeserialize(using = CustomDateTimeDeserializer.class)
@Column(name = "<%=fields[fieldId].fieldNameUnderscored %>"<% if (required) { %>, nullable = false<% } %>)<% } else if (fields[fieldId].fieldType == 'LocalDate') { %>
@Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalDate")
@JsonSerialize(using = CustomLocalDateSerializer.class)
@JsonDeserialize(using = ISO8601LocalDateDeserializer.class)
@Column(name = "<%=fields[fieldId].fieldNameUnderscored %>"<% if (required) { %>, nullable = false<% } %>)<% } else if (fields[fieldId].fieldType == 'BigDecimal') { %>
@Column(name = "<%=fields[fieldId].fieldNameUnderscored %>", precision=10, scale=2<% if (required) { %>, nullable = false<% } %>)<% } else { %>
@Column(name = "<%=fields[fieldId].fieldNameUnderscored %>"<% if (fields[fieldId].fieldValidate == true) { %><% if (fields[fieldId].fieldValidateRules.indexOf('maxlength') != -1) { %>, length = <%= fields[fieldId].fieldValidateRulesMaxlength %><% } %><% if (required) { %>, nullable = false<% } %><% } %>)<% } } %><% if (databaseType == 'mongodb') { %><% if (fields[fieldId].fieldType == 'DateTime') { %>
@JsonSerialize(using = CustomDateTimeSerializer.class)
@JsonDeserialize(using = CustomDateTimeDeserializer.class)<% } else if (fields[fieldId].fieldType == 'LocalDate') { %>
@JsonSerialize(using = CustomLocalDateSerializer.class)
@JsonDeserialize(using = ISO8601LocalDateDeserializer.class)<% } %>
@Field("<%=fields[fieldId].fieldNameUnderscored %>")<% } %>
private <%= fields[fieldId].fieldType %> <%= fields[fieldId].fieldName %>;
<% } %><% for (relationshipId in relationships) {
otherEntityRelationshipName = relationships[relationshipId].otherEntityRelationshipName;
if (otherEntityRelationshipName != null) {
mappedBy = otherEntityRelationshipName.charAt(0).toLowerCase() + otherEntityRelationshipName.slice(1)
}
%><% if (relationships[relationshipId].relationshipType == 'one-to-many') { %>
@OneToMany(mappedBy = "<%= relationships[relationshipId].otherEntityRelationshipName %>")
@JsonIgnore<% if (hibernateCache != 'no') { %>
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)<% } %>
private Set<<%= relationships[relationshipId].otherEntityNameCapitalized %>> <%= relationships[relationshipId].relationshipFieldName %>s = new HashSet<>();<% } else if (relationships[relationshipId].relationshipType == 'many-to-one') { %>
@ManyToOne
private <%= relationships[relationshipId].otherEntityNameCapitalized %> <%= relationships[relationshipId].relationshipFieldName %>;<% } else if (relationships[relationshipId].relationshipType == 'many-to-many') { %>
@ManyToMany<% if (relationships[relationshipId].ownerSide == false) { %>(mappedBy = "<%= relationships[relationshipId].otherEntityRelationshipName %>s")
@JsonIgnore<% } %><% if (hibernateCache != 'no') { %>
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)<% } %><% if (relationships[relationshipId].ownerSide == true) { %>
@JoinTable(name = "<%= name.toUpperCase() + '_' + relationships[relationshipId].relationshipName.toUpperCase() %>",
joinColumns = @JoinColumn(name="<%= name.toLowerCase() %>s_id", referencedColumnName="ID"),
inverseJoinColumns = @JoinColumn(name="<%= relationships[relationshipId].relationshipName.toLowerCase() %>s_id", referencedColumnName="ID"))<% } %>
private Set<<%= relationships[relationshipId].otherEntityNameCapitalized %>> <%= relationships[relationshipId].relationshipFieldName %>s = new HashSet<>();<% } else { %>
@OneToOne<% if (relationships[relationshipId].ownerSide == false) { %>(mappedBy = "<%= relationships[relationshipId].otherEntityRelationshipName %>")
@JsonIgnore<% } %>
private <%= relationships[relationshipId].otherEntityNameCapitalized %> <%= relationships[relationshipId].relationshipFieldName %>;<% } %>
<% } %>
public <% if (databaseType == 'sql') { %>Long<% } %><% if (databaseType == 'mongodb') { %>String<% } %><% if (databaseType == 'cassandra') { %>UUID<% } %> getId() {
return id;
}
public void setId(<% if (databaseType == 'sql') { %>Long<% } %><% if (databaseType == 'mongodb') { %>String<% } %><% if (databaseType == 'cassandra') { %>UUID<% } %> id) {
this.id = id;
}
<% for (fieldId in fields) { %>
public <%= fields[fieldId].fieldType %> get<%= fields[fieldId].fieldInJavaBeanMethod %>() {
return <%= fields[fieldId].fieldName %>;
}
public void set<%= fields[fieldId].fieldInJavaBeanMethod %>(<%= fields[fieldId].fieldType %> <%= fields[fieldId].fieldName %>) {
this.<%= fields[fieldId].fieldName %> = <%= fields[fieldId].fieldName %>;
}
<% } %><% for (relationshipId in relationships) { %><% if (relationships[relationshipId].relationshipType == 'one-to-many' || relationships[relationshipId].relationshipType == 'many-to-many') { %>
public Set<<%= relationships[relationshipId].otherEntityNameCapitalized %>> get<%= relationships[relationshipId].relationshipNameCapitalized %>s() {
return <%= relationships[relationshipId].relationshipFieldName %>s;
}
public void set<%= relationships[relationshipId].relationshipNameCapitalized %>s(Set<<%= relationships[relationshipId].otherEntityNameCapitalized %>> <%= relationships[relationshipId].otherEntityName %>s) {
this.<%= relationships[relationshipId].relationshipFieldName %>s = <%= relationships[relationshipId].otherEntityName %>s;
}<% } else { %>
public <%= relationships[relationshipId].otherEntityNameCapitalized %> get<%= relationships[relationshipId].relationshipNameCapitalized %>() {
return <%= relationships[relationshipId].relationshipFieldName %>;
}
public void set<%= relationships[relationshipId].relationshipNameCapitalized %>(<%= relationships[relationshipId].otherEntityNameCapitalized %> <%= relationships[relationshipId].otherEntityName %>) {
this.<%= relationships[relationshipId].relationshipFieldName %> = <%= relationships[relationshipId].otherEntityName %>;
}<% } %>
<% } %>
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
<%= entityClass %> <%= entityInstance %> = (<%= entityClass %>) o;
if ( ! Objects.equals(id, <%= entityInstance %>.id)) return false;
return true;
}
@Override
public int hashCode() {
return Objects.hashCode(id);
}
@Override
public String toString() {
return "<%= entityClass %>{" +
"id=" + id +<% for (fieldId in fields) { %>
", <%= fields[fieldId].fieldName %>='" + <%= fields[fieldId].fieldName %> + "'" +<% } %>
'}';
}
}
|
package cn.cerc.mis.ado;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Supplier;
import cn.cerc.db.core.DataRow;
public interface EntityQueryOne<T> {
boolean isEmpty();
// loadOne.isEmptyThrow:
<X extends Throwable> EntityQueryOne<T> isEmptyThrow(Supplier<? extends X> exceptionSupplier) throws X;
boolean isPresent();
// loadOne.isPresentThrow:
<X extends Throwable> EntityQueryOne<T> isPresentThrow(Supplier<? extends X> exceptionSupplier) throws X;
T get();
// entity
<X extends Throwable> T getElseThrow(Supplier<? extends X> exceptionSupplier) throws X;
void save(T entity);
// update.orElseInsert: entity
EntityQueryOne<T> update(Consumer<T> action);
// loadOne.orElseInsert:
EntityQueryOne<T> orElseInsert(Consumer<T> action);
// delete.orElseThrow: entity
Optional<T> delete();
DataRow current();
}
|
package com.akjava.gwt.modelweight.client;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.akjava.bvh.client.BVH;
import com.akjava.bvh.client.BVHParser;
import com.akjava.bvh.client.BVHParser.ParserListener;
import com.akjava.bvh.client.threejs.AnimationBoneConverter;
import com.akjava.bvh.client.threejs.AnimationDataConverter;
import com.akjava.gwt.html5.client.HTML5InputRange;
import com.akjava.gwt.html5.client.extra.HTML5Builder;
import com.akjava.gwt.html5.client.file.File;
import com.akjava.gwt.html5.client.file.FileHandler;
import com.akjava.gwt.html5.client.file.FileReader;
import com.akjava.gwt.html5.client.file.FileUtils;
import com.akjava.gwt.modelweight.client.weight.GWTWeightData;
import com.akjava.gwt.modelweight.client.weight.WeighDataParser;
import com.akjava.gwt.three.client.THREE;
import com.akjava.gwt.three.client.core.Geometry;
import com.akjava.gwt.three.client.core.Intersect;
import com.akjava.gwt.three.client.core.Object3D;
import com.akjava.gwt.three.client.core.Projector;
import com.akjava.gwt.three.client.core.Vector3;
import com.akjava.gwt.three.client.core.Vector4;
import com.akjava.gwt.three.client.extras.GeometryUtils;
import com.akjava.gwt.three.client.extras.ImageUtils;
import com.akjava.gwt.three.client.extras.animation.Animation;
import com.akjava.gwt.three.client.extras.animation.AnimationHandler;
import com.akjava.gwt.three.client.extras.loaders.JSONLoader;
import com.akjava.gwt.three.client.extras.loaders.JSONLoader.LoadHandler;
import com.akjava.gwt.three.client.gwt.Clock;
import com.akjava.gwt.three.client.gwt.GWTGeometryUtils;
import com.akjava.gwt.three.client.gwt.GWTThreeUtils;
import com.akjava.gwt.three.client.gwt.SimpleDemoEntryPoint;
import com.akjava.gwt.three.client.gwt.animation.AnimationBone;
import com.akjava.gwt.three.client.gwt.animation.AnimationData;
import com.akjava.gwt.three.client.gwt.animation.AnimationHierarchyItem;
import com.akjava.gwt.three.client.gwt.animation.WeightBuilder;
import com.akjava.gwt.three.client.gwt.collada.ColladaData;
import com.akjava.gwt.three.client.lights.Light;
import com.akjava.gwt.three.client.materials.Material;
import com.akjava.gwt.three.client.objects.Mesh;
import com.akjava.gwt.three.client.objects.SkinnedMesh;
import com.akjava.gwt.three.client.renderers.WebGLRenderer;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.core.client.JsArrayNumber;
import com.google.gwt.core.client.JsArrayString;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.MouseMoveEvent;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.http.client.URL;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.FileUpload;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.StackLayoutPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public class GWTModelWeight extends SimpleDemoEntryPoint{
@Override
protected void beforeUpdate(WebGLRenderer renderer) {
if(root!=null){
boneAndVertex.getRotation().set(Math.toRadians(rotX),Math.toRadians(rotY),0);
boneAndVertex.getPosition().set(posX,posY,0);
root.setPosition(positionXRange.getValue(), positionYRange.getValue(), positionZRange.getValue());
root.getRotation().set(Math.toRadians(rotationRange.getValue()),Math.toRadians(rotationYRange.getValue()),Math.toRadians(rotationZRange.getValue()));
}
long delta=clock.delta();
//log(""+animation.getCurrentTime());
double v=(double)delta/1000;
if(!paused && animation!=null){
AnimationHandler.update(v);
currentTime=animation.getCurrentTime();
//log(""+currentTime+","+delta);
String check=""+currentTime;
if(check.equals("NaN")){
currentTime=0;
}
if(currentTime<0.25){
//animation.setCurrentTime(0.25);
//AnimationHandler.update(v);
//skinnedMesh.setVisible(false);
}else{
skinnedMesh.setVisible(true);
}
}else{
currentTime=animation.getCurrentTime();
}
}
double currentTime;
private Clock clock=new Clock();
@Override
protected void initializeOthers(WebGLRenderer renderer) {
scene.add(THREE.AmbientLight(0xffffff));
Light pointLight = THREE.DirectionalLight(0xffffff,1);
pointLight.setPosition(0, 10, 300);
scene.add(pointLight);
Light pointLight2 = THREE.DirectionalLight(0xffffff,1);//for fix back side dark problem
pointLight2.setPosition(0, 10, -300);
scene.add(pointLight2);
projector=THREE.Projector();
/*
//write test
Geometry g=THREE.CubeGeometry(1, 1, 1);
log(g);
Geometry g2=THREE.CubeGeometry(1, 1, 1);
Matrix4 mx=THREE.Matrix4();
mx.setPosition(THREE.Vector3(0,10,0));
//g2.applyMatrix(mx);
Mesh tmpM=THREE.Mesh(g2, THREE.MeshBasicMaterial().build());
tmpM.setPosition(0, 10, 0);
GeometryUtils.merge(g, tmpM);
JSONModelFile model=JSONModelFile.create();
model.setVertices(g.vertices());
model.setFaces(g.faces());
//JSONArray vertices=new JSONArray(nums);
JSONObject js=new JSONObject(model);
log(js.toString());
scene.add(THREE.AmbientLight(0x888888));
Light pointLight = THREE.PointLight(0xffffff);
pointLight.setPosition(0, 10, 300);
scene.add(pointLight);
*/
//loadBVH("14_08.bvh");
/*
JSONLoader loader=THREE.JSONLoader();
loader.load("buffalo.js", new LoadHandler() {
@Override
public void loaded(Geometry geometry) {
AnimationHandler.add(geometry.getAnimation());
log(geometry.getBones());
log(geometry.getAnimation());
//JSONObject test=new JSONObject(geometry.getAnimation());
//log(test.toString());
Geometry cube=THREE.CubeGeometry(1, 1, 1);
JsArray<Vector4> indices=(JsArray<Vector4>) JsArray.createArray();
JsArray<Vector4> weight=(JsArray<Vector4>) JsArray.createArray();
for(int i=0;i<cube.vertices().length();i++){
Vector4 v4=THREE.Vector4();
v4.set(0, 0, 0, 0);
indices.push(v4);
Vector4 v4w=THREE.Vector4();
v4w.set(1, 0, 0, 0);
weight.push(v4w);
}
cube.setSkinIndices(indices);
cube.setSkinWeight(weight);
cube.setBones(geometry.getBones());
//root=boneToCube(geometry.getBones());
//scene.add(root);
//SkinnedMesh mesh=THREE.SkinnedMesh(cube, THREE.MeshLambertMaterial().skinning(true).color(0xff0000).build());
//scene.add(mesh);
//Animation animation = THREE.Animation( mesh, "take_001" );
//log(animation);
//animation.play(); //buffalo
}
});*/
loadBVH("pose.bvh");
//loadBVH("14_08.bvh");
}
Object3D root;
List<Mesh> tmp=new ArrayList<Mesh>();
private Object3D boneToSkelton(JsArray<AnimationBone> bones){
tmp.clear();
Object3D group=THREE.Object3D();
for(int i=0;i<bones.length();i++){
AnimationBone bone=bones.get(i);
Geometry cube=THREE.CubeGeometry(.3, .3, .3);
int color=0xff0000;
if(i==0){
//color=0x00ff00;
}
Mesh mesh=THREE.Mesh(cube, THREE.MeshLambertMaterial().color(color).build());
group.add(mesh);
Vector3 pos=AnimationBone.jsArrayToVector3(bone.getPos());
if(bone.getParent()!=-1){
Vector3 half=pos.clone().multiplyScalar(.5);
Vector3 ppos=tmp.get(bone.getParent()).getPosition();
pos.addSelf(ppos);
half.addSelf(ppos);
double length=ppos.clone().subSelf(pos).length();
//half
Mesh halfMesh=THREE.Mesh(THREE.CubeGeometry(.2, .2, length), THREE.MeshLambertMaterial().color(0xaaaaaa).build());
group.add(halfMesh);
halfMesh.setPosition(half);
halfMesh.lookAt(pos);
halfMesh.setName(bones.get(bone.getParent()).getName());
}
mesh.setPosition(pos);
mesh.setName(bone.getName());
if(bone.getParent()!=-1){
//AnimationBone parent=bones.get(bone.getParent());
Vector3 ppos=tmp.get(bone.getParent()).getPosition();
Mesh line=THREE.Line(GWTGeometryUtils.createLineGeometry(pos, ppos), THREE.LineBasicMaterial().color(0x888888).build());
group.add(line);
}
tmp.add(mesh);
}
return group;
}
private List<NameAndPosition> boneToNameAndWeight(JsArray<AnimationBone> bones){
List<NameAndPosition> lists=new ArrayList<NameAndPosition>();
List<Vector3> absolutePos=new ArrayList<Vector3>();
for(int i=0;i<bones.length();i++){
AnimationBone bone=bones.get(i);
Vector3 pos=AnimationBone.jsArrayToVector3(bone.getPos());
String parentName=null;
//add start
//add center
Vector3 parentPos=null;
Vector3 endPos=null;
int parentIndex=0;
if(bone.getParent()!=-1){
parentIndex=bone.getParent();
parentName=bones.get(parentIndex).getName();
parentPos=absolutePos.get(parentIndex);
if(pos.getX()!=0 || pos.getY()!=0 || pos.getZ()!=0){
endPos=pos.clone().multiplyScalar(.9).addSelf(parentPos);
Vector3 half=pos.clone().multiplyScalar(.5).addSelf(parentPos);
lists.add(new NameAndPosition(parentName,endPos,parentIndex));//start pos
lists.add(new NameAndPosition(parentName,half,parentIndex));//half pos
Mesh mesh=THREE.Mesh(THREE.CubeGeometry(.2, .2, .2), THREE.MeshLambertMaterial().color(0x00ff00).build());
mesh.setName(parentName);
mesh.setPosition(endPos);
//boneAndVertex.add(mesh);
Mesh mesh2=THREE.Mesh(THREE.CubeGeometry(.3, .3, .2), THREE.MeshLambertMaterial().color(0x00ff00).build());
mesh2.setName(parentName);
mesh2.setPosition(half);
//boneAndVertex.add(mesh2);
}else{
}
}
//add end
if(parentPos!=null){
pos.addSelf(parentPos);
}
absolutePos.add(pos);
Mesh mesh=THREE.Mesh(THREE.CubeGeometry(.5, .5, .5), THREE.MeshLambertMaterial().color(0x00ff00).build());
mesh.setName(bone.getName());
mesh.setPosition(pos);
//boneAndVertex.add(mesh);
if(parentPos!=null){
Mesh line=GWTGeometryUtils.createLineMesh(parentPos, pos, 0xff0000);
//boneAndVertex.add(line);
}
lists.add(new NameAndPosition(bone.getName(),pos,i));//end pos
}
return lists;
}
private Projector projector;
Label debugLabel;
List<Integer> selections=new ArrayList<Integer>();
@Override
public void onMouseClick(ClickEvent event) {
int x=event.getX();
int y=event.getY();
/*
if(inEdge(x,y)){
screenMove(x,y);
return;
}*/
JsArray<Intersect> intersects=projector.gwtPickIntersects(event.getX(), event.getY(), screenWidth, screenHeight, camera,scene);
for(int i=0;i<intersects.length();i++){
Intersect sect=intersects.get(i);
Object3D target=sect.getObject();
if(!target.getName().isEmpty()){
if(target.getName().startsWith("point:")){
if(!target.getVisible()){
//not selected bone
continue;
}
String[] pv=target.getName().split(":");
int at=Integer.parseInt(pv[1]);
if(event.isShiftKeyDown()){
if(selections.contains(at)){
selections.remove(new Integer(at));
vertexMeshs.get(at).getMaterial().getColor().setHex(defaultColor);
if(lastSelection==at){
if(selections.size()>0){
//select last
selectVertex(selections.get(selections.size()-1));
}else{
indexWeightEditor.setAvailable(false);
updateWeightButton.setEnabled(false);
}
}
}else{
//plus
selections.add(lastSelection);
selectVertex(at);
}
for(int index:selections){
vertexMeshs.get(index).getMaterial().getColor().setHex(selectColor);
}
}else{
//clear cache
clearSelections();
selectVertex(at);
}
return;
}else{
if(event.isShiftKeyDown()){
continue;
}
clearSelections();
selectBone(target);
break;
}
}
}
//selectionMesh.setVisible(false);
}
private void clearSelections(){
for(int index:selections){
vertexMeshs.get(index).getMaterial().getColor().setHex(defaultColor);
}
selections.clear();
}
private Mesh selection;
private int selectionBoneIndex;
private Object3D selectVertex;
private void selectBone(Object3D target) {
if(selection==null){
selection=THREE.Mesh(THREE.CubeGeometry(1, 1, 1), THREE.MeshLambertMaterial().color(0x00ff00).build());
boneAndVertex.add(selection);
}
selection.setPosition(target.getPosition());
selectionBoneIndex=findBoneIndex(target.getName());
boneListBox.setSelectedIndex(selectionBoneIndex);
selectVertexsByBone(selectionBoneIndex);
int selectionIndex=indexWeightEditor.getArrayIndex();
if(selectionIndex!=-1 && !vertexMeshs.get(selectionIndex).getVisible()){
indexWeightEditor.setAvailable(false);
updateWeightButton.setEnabled(false);
selectionMesh.setVisible(false);
}
}
private void selectVertexsByBone(int selectedBoneIndex) {
log("selectVertexsByBone");
for(int i=0;i<bodyGeometry.vertices().length();i++){
Vector4 index=bodyIndices.get(i);
Mesh mesh=vertexMeshs.get(i);
if(index.getX()==selectedBoneIndex || index.getY()==selectedBoneIndex){
mesh.setVisible(true);
Vector4 weight=bodyWeight.get(i);
//log(weight.getX()+","+weight.getY());
}else{
mesh.setVisible(false);
mesh.getMaterial().getColor().setHex(defaultColor);
}
}
}
private int findBoneIndex(String name){
int ret=0;
for(int i=0;i<bones.length();i++){
if(bones.get(i).getName().equals(name)){
ret=i;
break;
}
}
return ret;
}
int rotX;
int rotY;
double posX;
double posY;
@Override
public void onMouseMove(MouseMoveEvent event) {
if(mouseDown){
int diffX=event.getX()-mouseDownX;
int diffY=event.getY()-mouseDownY;
mouseDownX=event.getX();
mouseDownY=event.getY();
if(event.isAltKeyDown()){
posX+=(double)diffX/2;
posY-=(double)diffY/2;
}else{
rotX=(rotX+diffY);
rotY=(rotY+diffX);
}
}
}
private HTML5InputRange positionXRange;
private HTML5InputRange positionYRange;
private HTML5InputRange positionZRange;
private HTML5InputRange rotationRange;
private HTML5InputRange rotationYRange;
private HTML5InputRange rotationZRange;
@Override
public void createControl(Panel parent) {
debugLabel=new Label();
parent.add(debugLabel);
stackPanel = new StackLayoutPanel(Unit.PX);
stackPanel.setSize("200px","400px");
parent.add(stackPanel);
VerticalPanel modelPositionAndRotation=new VerticalPanel();
modelPositionAndRotation.setWidth("100%");
stackPanel.add(modelPositionAndRotation,"Model Postion&Rotation",30);
HorizontalPanel h1=new HorizontalPanel();
rotationRange = new HTML5InputRange(-180,180,0);
modelPositionAndRotation.add(HTML5Builder.createRangeLabel("X-Rotate:", rotationRange));
modelPositionAndRotation.add(h1);
h1.add(rotationRange);
Button reset=new Button("Reset");
reset.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
rotationRange.setValue(0);
}
});
h1.add(reset);
HorizontalPanel h2=new HorizontalPanel();
rotationYRange = new HTML5InputRange(-180,180,0);
modelPositionAndRotation.add(HTML5Builder.createRangeLabel("Y-Rotate:", rotationYRange));
modelPositionAndRotation.add(h2);
h2.add(rotationYRange);
Button reset2=new Button("Reset");
reset2.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
rotationYRange.setValue(0);
}
});
h2.add(reset2);
HorizontalPanel h3=new HorizontalPanel();
rotationZRange = new HTML5InputRange(-180,180,0);
modelPositionAndRotation.add(HTML5Builder.createRangeLabel("Z-Rotate:", rotationZRange));
modelPositionAndRotation.add(h3);
h3.add(rotationZRange);
Button reset3=new Button("Reset");
reset3.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
rotationZRange.setValue(0);
}
});
h3.add(reset3);
HorizontalPanel h4=new HorizontalPanel();
positionXRange = new HTML5InputRange(-50,50,0);
modelPositionAndRotation.add(HTML5Builder.createRangeLabel("X-Position:", positionXRange));
modelPositionAndRotation.add(h4);
h4.add(positionXRange);
Button reset4=new Button("Reset");
reset4.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
positionXRange.setValue(0);
}
});
h4.add(reset4);
HorizontalPanel h5=new HorizontalPanel();
positionYRange = new HTML5InputRange(-50,50,0);
modelPositionAndRotation.add(HTML5Builder.createRangeLabel("Y-Position:", positionYRange));
modelPositionAndRotation.add(h5);
h5.add(positionYRange);
Button reset5=new Button("Reset");
reset5.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
positionYRange.setValue(0);
}
});
h5.add(reset5);
HorizontalPanel h6=new HorizontalPanel();
positionZRange = new HTML5InputRange(-50,50,0);
modelPositionAndRotation.add(HTML5Builder.createRangeLabel("Z-Position:", positionZRange));
modelPositionAndRotation.add(h6);
h6.add(positionZRange);
Button reset6=new Button("Reset");
reset6.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
positionZRange.setValue(0);
}
});
h6.add(reset6);
//move left-side
//positionYRange.setValue(-13);
positionXRange.setValue(-13);
Button bt=new Button("Pause/Play SkinnedMesh");
parent.add(bt);
bt.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
paused=!paused;
}
});
//editor
VerticalPanel boneAndWeight=new VerticalPanel();
stackPanel.add(boneAndWeight,"Bone & Weight",30);
boneListBox = new ListBox();
boneAndWeight.add(boneListBox);
boneListBox.addChangeHandler(new ChangeHandler() {
@Override
public void onChange(ChangeEvent event) {
selectVertexsByBone(boneListBox.getSelectedIndex());
}
});
HorizontalPanel prevAndNext=new HorizontalPanel();
boneAndWeight.add(prevAndNext);
Button prev=new Button("Prev");
prev.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
selectPrevVertex();
}
});
prevAndNext.add(prev);
Button next=new Button("Next");
next.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
selectNextVertex();
}
});
prevAndNext.add(next);
indexWeightEditor = new IndexAndWeightEditor();
boneAndWeight.add(indexWeightEditor);
updateWeightButton = new Button("Update Weight");
updateWeightButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
int index=indexWeightEditor.getArrayIndex();
if(index==-1){
return;
}
Vector4 in=bodyIndices.get(index);
Vector4 we=bodyWeight.get(index);
in.setX(indexWeightEditor.getIndex1());
in.setY(indexWeightEditor.getIndex2());
we.setX(indexWeightEditor.getWeight1());
we.setY(indexWeightEditor.getWeight2());
if(selections.size()>0){
for(int selectedIndex:selections){
in=bodyIndices.get(selectedIndex);
we=bodyWeight.get(selectedIndex);
in.setX(indexWeightEditor.getIndex1());
in.setY(indexWeightEditor.getIndex2());
we.setX(indexWeightEditor.getWeight1());
we.setY(indexWeightEditor.getWeight2());
}
}
//log("new-ind-weight:"+in.getX()+","+in.getY()+","+we.getX()+","+we.getY());
createSkinnedMesh();
selectVertexsByBone(selectionBoneIndex);
}
});
boneAndWeight.add(updateWeightButton);
//DONT need?
useBasicMaterial = new CheckBox();
useBasicMaterial.setText("Use Basic Material");
//parent.add(useBasicMaterial);
VerticalPanel loadAndExport=new VerticalPanel();
stackPanel.add(loadAndExport,"Load & Export",30);
loadAndExport.add(new Label("BVH Bone"));
FileUpload bvhUpload=new FileUpload();
loadAndExport.add(bvhUpload);
bvhUpload.addChangeHandler(new ChangeHandler() {
@Override
public void onChange(ChangeEvent event) {
JsArray<File> files = FileUtils.toFile(event.getNativeEvent());
final FileReader reader=FileReader.createFileReader();
reader.setOnLoad(new FileHandler() {
@Override
public void onLoad() {
//log("load:"+Benchmark.end("load"));
//GWT.log(reader.getResultAsString());
parseBVH(reader.getResultAsString());
}
});
reader.readAsText(files.get(0),"utf-8");
}
});
loadAndExport.add(new Label("Mesh"));
FileUpload meshUpload=new FileUpload();
loadAndExport.add(meshUpload);
meshUpload.addChangeHandler(new ChangeHandler() {
@Override
public void onChange(ChangeEvent event) {
JsArray<File> files = FileUtils.toFile(event.getNativeEvent());
final FileReader reader=FileReader.createFileReader();
reader.setOnLoad(new FileHandler() {
@Override
public void onLoad() {
//log("load:"+Benchmark.end("load"));
//GWT.log(reader.getResultAsString());
loadJsonModel(reader.getResultAsString(),new LoadHandler() {
@Override
public void loaded(Geometry geometry) {
initializeObject();
loadedGeometry=geometry;
autoWeight();
//log(bodyIndices);
//log(bodyWeight);
createSkinnedMesh();
createWireBody();
}
});
}
});
reader.readAsText(files.get(0),"utf-8");
}
});
loadAndExport.add(new Label("Texture Image"));
FileUpload textureUpload=new FileUpload();
loadAndExport.add(textureUpload);
textureUpload.addChangeHandler(new ChangeHandler() {
@Override
public void onChange(ChangeEvent event) {
JsArray<File> files = FileUtils.toFile(event.getNativeEvent());
final FileReader reader=FileReader.createFileReader();
reader.setOnLoad(new FileHandler() {
@Override
public void onLoad() {
//log("load:"+Benchmark.end("load"));
//GWT.log(reader.getResultAsString());
textureUrl=reader.getResultAsString();
createSkinnedMesh();
}
});
reader.readAsDataURL(files.get(0));
}
});
loadAndExport.add(textureUpload);
HorizontalPanel exports=new HorizontalPanel();
loadAndExport.add(exports);
Button json=new Button("json export");
json.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
exportAsJson();
}
});
exports.add(json);
withAnimation = new CheckBox("with Animation");
withAnimation.setValue(false); //dont work collectly
exports.add(withAnimation);
showControl();
}
protected void selectPrevVertex() {
int currentSelection=indexWeightEditor.getArrayIndex();
for(int i=currentSelection-1;i>=0;i
if(vertexMeshs.get(i).getVisible()){
selectVertex(i);
return;
}
}
for(int i=vertexMeshs.size()-1;i>currentSelection;i
if(vertexMeshs.get(i).getVisible()){
selectVertex(i);
return;
}
}
}
protected void selectNextVertex() {
int currentSelection=indexWeightEditor.getArrayIndex();
for(int i=currentSelection+1;i<vertexMeshs.size();i++){
if(vertexMeshs.get(i).getVisible()){
selectVertex(i);
return;
}
}
for(int i=0;i<currentSelection;i++){
if(vertexMeshs.get(i).getVisible()){
selectVertex(i);
return;
}
}
}
private int lastSelection=-1;
private void selectVertex(int index){
if(lastSelection!=-1){
vertexMeshs.get(lastSelection).getMaterial().getColor().setHex(defaultColor);
}
Vector4 in=bodyIndices.get(index);
Vector4 we=bodyWeight.get(index);
vertexMeshs.get(index).getMaterial().getColor().setHex(selectColor);
indexWeightEditor.setAvailable(true);
updateWeightButton.setEnabled(true);
indexWeightEditor.setValue(index, in, we);
selectionMesh.setVisible(true);
selectionMesh.setPosition(vertexMeshs.get(index).getPosition());
stackPanel.showWidget(1);
lastSelection=index;
}
private void exportAsJson(){
//set bone
JsArray<AnimationBone> clonedBone=cloneBones(bones);
JSONArray arrays=new JSONArray(clonedBone);
lastJsonObject.put("bones", arrays);
//AnimationBoneConverter.setBoneAngles(clonedBone, rawAnimationData, 0); //TODO
if(withAnimation.getValue()){
lastJsonObject.put("animation", new JSONObject(rawAnimationData));
}
//private JsArray<Vector4> bodyIndices;
//private JsArray<Vector4> bodyWeight;
JsArrayNumber indices=(JsArrayNumber) JsArrayNumber.createArray();
for(int i=0;i<bodyIndices.length();i++){
indices.push(bodyIndices.get(i).getX());
indices.push(bodyIndices.get(i).getY());
}
lastJsonObject.put("skinIndices", new JSONArray(indices));
JsArrayNumber weights=(JsArrayNumber) JsArrayNumber.createArray();
for(int i=0;i<bodyWeight.length();i++){
weights.push(bodyWeight.get(i).getX());
weights.push(bodyWeight.get(i).getY());
}
lastJsonObject.put("skinWeights", new JSONArray(weights));
exportTextChrome(lastJsonObject.toString(),"WeightTool"+exportIndex);
exportIndex++;
}
int exportIndex;
public native final void exportTextChrome(String text,String wname)/*-{
win = $wnd.open("", wname)
win.document.body.innerText =""+text+"";
}-*/;
private boolean paused=true;
private void loadBVH(String path){
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(path));
try {
builder.sendRequest(null, new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
String bvhText=response.getText();
//log("loaded:"+Benchmark.end("load"));
//useless spend allmost time with request and spliting.
parseBVH(bvhText);
}
@Override
public void onError(Request request, Throwable exception) {
Window.alert("load faild:");
}
});
} catch (RequestException e) {
log(e.getMessage());
e.printStackTrace();
}
}
private JsArray<Vector4> bodyIndices;
private JsArray<Vector4> bodyWeight;
private BVH bvh;
private Animation animation;
private Geometry bodyGeometry;
private Object3D boneAndVertex;
private JsArray<AnimationBone> bones;
private SkinnedMesh skinnedMesh;
private ColladaData rawCollada;
private AnimationData rawAnimationData;
private void updateBoneListBox(){
boneListBox.clear();
for(int i=0;i<bones.length();i++){
boneListBox.addItem(bones.get(i).getName());
}
}
public JsArray<AnimationBone> cloneBones(JsArray<AnimationBone> bones){
JsArray<AnimationBone> array=(JsArray<AnimationBone>) JsArray.createArray();
for(int i=0;i<bones.length();i++){
AnimationBone bone=bones.get(i);
AnimationBone cloned=(AnimationBone) AnimationBone.createObject();
cloned.setName(bone.getName());
cloned.setParent(bone.getParent());
if(bone.getPos()!=null){
cloned.setPos(GWTThreeUtils.clone(bone.getPos()));
}
if(bone.getRotq()!=null){
cloned.setRotq(GWTThreeUtils.clone(bone.getRotq()));
}
if(bone.getRot()!=null){
cloned.setRot(GWTThreeUtils.clone(bone.getRot()));
}
if(bone.getScl()!=null){
cloned.setScl(GWTThreeUtils.clone(bone.getScl()));
}
array.push(cloned);
}
return array;
}
private void parseBVH(String bvhText){
final BVHParser parser=new BVHParser();
parser.parseAsync(bvhText, new ParserListener() {
private AnimationData animationData;
@Override
public void onSuccess(BVH bv) {
bvh=bv;
//bvh.setSkips(10);
//bvh.setSkips(skipFrames);
AnimationBoneConverter converter=new AnimationBoneConverter();
bones = converter.convertJsonBone(bvh);
updateBoneListBox();
indexWeightEditor.setBones(bones);
/*
for(int i=0;i<bones.length();i++){
// log(i+":"+bones.get(i).getName());
}
GWT.log("parsed");
*/
/*
for(int i=0;i<bones.length();i++){
Mesh mesh=THREE.Mesh(THREE.CubeGeometry(.5, .5, .5), THREE.MeshLambertMaterial().color(0x0000ff).build());
scene.add(mesh);
JsArrayNumber pos=bones.get(i).getPos();
mesh.setPosition(pos.get(0),pos.get(1),pos.get(2));
}
*/
AnimationDataConverter dataConverter=new AnimationDataConverter();
if(bvh.getFrames()==1){
dataConverter.setSkipFirst(false);
}
animationData = dataConverter.convertJsonAnimation(bones,bvh);
//for(int i=0;i<animationData.getHierarchy().length();i++){
AnimationHierarchyItem item=animationData.getHierarchy().get(0);
for(int j=0;j<item.getKeys().length();j++){
item.getKeys().get(j).setPos(0, 0, 0);//dont move;
}
rawAnimationData=dataConverter.convertJsonAnimation(bones,bvh);//for json
animationName=animationData.getName();
JsArray<AnimationHierarchyItem> hitem=animationData.getHierarchy();
/*
for(int i=0;i<hitem.length();i++){
AnimationHierarchyItem item=hitem.get(i);
AnimationHierarchyItem parent=null;
if(item.getParent()!=-1){
parent=hitem.get(item.getParent());
}
AnimationKey key=item.getKeys().get(keyIndex);
Mesh mesh=THREE.Mesh(THREE.CubeGeometry(.5, .5, .5), THREE.MeshLambertMaterial().color(0x00ff00).build());
scene.add(mesh);
Vector3 meshPos=AnimationUtils.getPosition(key);
mesh.setPosition(meshPos);
if(parent!=null){
Vector3 parentPos=AnimationUtils.getPosition(parent.getKeys().get(keyIndex));
Geometry lineG = THREE.Geometry();
lineG.vertices().push(THREE.Vertex(meshPos));
lineG.vertices().push(THREE.Vertex(parentPos));
Mesh line=THREE.Line(lineG, THREE.LineBasicMaterial().color(0xffffff).build());
scene.add(line);
}
Quaternion q=key.getRot();
Matrix4 rot=THREE.Matrix4();
rot.setRotationFromQuaternion(q);
Vector3 rotV=THREE.Vector3();
rotV.setRotationFromMatrix(rot);
mesh.setRotation(rotV);
}
*/
/*
Geometry cube=THREE.CubeGeometry(1, 1, 1);
JsArray<Vector4> indices=(JsArray<Vector4>) JsArray.createArray();
JsArray<Vector4> weight=(JsArray<Vector4>) JsArray.createArray();
for(int i=0;i<cube.vertices().length();i++){
Vector4 v4=THREE.Vector4();
v4.set(0, 0, 0, 0);
indices.push(v4);
Vector4 v4w=THREE.Vector4();
v4w.set(1, 0, 0, 0);
weight.push(v4w);
}
List<Vector3> parentPos=new ArrayList<Vector3>();
parentPos.add(THREE.Vector3());
for(int j=1;j<bones.length();j++){
Geometry cbone=THREE.CubeGeometry(1, 1, 1);
AnimationBone ab=bones.get(j);
Vector3 pos=AnimationBone.jsArrayToVector3(ab.getPos());
pos.addSelf(parentPos.get(ab.getParent()));
parentPos.add(pos);
Matrix4 m4=THREE.Matrix4();
m4.setPosition(pos);
cbone.applyMatrix(m4);
GeometryUtils.merge(cube, cbone);
for(int i=0;i<cbone.vertices().length();i++){
Vector4 v4=THREE.Vector4();
v4.set(j, j, 0, 0);
// v4.set(0, 0, 0, 0);
indices.push(v4);
Vector4 v4w=THREE.Vector4();
v4w.set(1, 0, 0, 0);
weight.push(v4w);
}
}
log("cube");
log(cube);
cube.setSkinIndices(indices);
cube.setSkinWeight(weight);
cube.setBones(bones);
*/
final List<Vector3> bonePositions=new ArrayList<Vector3>();
for(int j=0;j<bones.length();j++){
AnimationBone bone=bones.get(j);
Vector3 pos=AnimationBone.jsArrayToVector3(bone.getPos());
if(bone.getParent()!=-1){
pos.addSelf(bonePositions.get(bone.getParent()));
}
bonePositions.add(pos);
}
//overwrite same name
AnimationHandler.add(animationData);
//log(data);
//log(bones);
JSONArray array=new JSONArray(bones);
//log(array.toString());
JSONObject test=new JSONObject(animationData);
//log(test.toString());
initializeObject();
if(loadedGeometry==null){//initial load
loadModel("miku.js",
new LoadHandler() {
//loader.load("men3smart.js", new LoadHandler() {
@Override
public void loaded(Geometry geometry) {
// SubdivisionModifier modifier=THREE.SubdivisionModifier(3);
// modifier.modify(geometry);
log(geometry);
for(int i=0;i<bones.length();i++){
if(bones.get(i).getParent()!=-1)
log(bones.get(i).getName()+",parent="+bones.get(bones.get(i).getParent()).getName());
}
//findIndex(geometry);
//auto weight
loadedGeometry=geometry;
autoWeight();
//log(bodyIndices);
//log(bodyWeight);
createSkinnedMesh();
createWireBody();
}
});
}else{
autoWeight();
createSkinnedMesh();
createWireBody();
}
//log("before create");
//Mesh mesh=THREE.Mesh(cube, THREE.MeshLambertMaterial().skinning(false).color(0xff0000).build());
//log("create-mesh");
//scene.add(mesh);
/*
ColladaLoader loader=THREE.ColladaLoader();
loader.load("men3smart_hair.dae#1", new ColladaLoadHandler() {
public void colladaReady(ColladaData collada) {
rawCollada=collada;
log(collada);
boneNameMaps=new HashMap<String,Integer>();
for(int i=0;i<bones.length();i++){
boneNameMaps.put(bones.get(i).getName(), i);
log(i+":"+bones.get(i).getName());
}
Geometry geometry=collada.getGeometry();
colladaJoints=collada.getJoints();
Vector3 xup=THREE.Vector3(Math.toRadians(-90),0,0);
Matrix4 mx=THREE.Matrix4();
mx.setRotationFromEuler(xup, "XYZ");
geometry.applyMatrix(mx);
*/
}
@Override
public void onFaild(String message) {
log(message);
}
});
}
private String animationName;
private Geometry loadedGeometry;
private Mesh selectionMesh;
private void initializeObject(){
currentTime=0;
//for skinned mesh
if(root!=null){
scene.remove(root);
}
root=THREE.Object3D();
scene.add(root);
if(boneAndVertex!=null){
scene.remove(boneAndVertex);
}
boneAndVertex = THREE.Object3D();
boneAndVertex.setPosition(-15, 0, 0);
scene.add(boneAndVertex);
Object3D bo=boneToSkelton(bones);
//bo.setPosition(-30, 0, 0);
boneAndVertex.add(bo);
selectionMesh=THREE.Mesh(THREE.CubeGeometry(.5, .5, .5), THREE.MeshBasicMaterial().color(selectColor).wireFrame(true).build());
boneAndVertex.add(selectionMesh);
selectionMesh.setVisible(false);
}
private int selectColor=0xccffcc;
private int defaultColor=0xffff00;
private void createWireBody(){
bodyGeometry=GeometryUtils.clone(loadedGeometry);
Mesh wireBody=THREE.Mesh(bodyGeometry, THREE.MeshBasicMaterial().wireFrame(true).color(0xffffff).build());
boneAndVertex.add(wireBody);
selectVertex=THREE.Object3D();
vertexMeshs.clear();
boneAndVertex.add(selectVertex);
Geometry cube=THREE.CubeGeometry(.3, .3, .3);
for(int i=0;i<bodyGeometry.vertices().length();i++){
Material mt=THREE.MeshBasicMaterial().color(defaultColor).build();
Vector3 vx=bodyGeometry.vertices().get(i).getPosition();
Mesh point=THREE.Mesh(cube, mt);
point.setVisible(false);
point.setName("point:"+i);
point.setPosition(vx);
selectVertex.add(point);
vertexMeshs.add(point);
}
}
private void autoWeight(){
bodyIndices = (JsArray<Vector4>) JsArray.createArray();
bodyWeight = (JsArray<Vector4>) JsArray.createArray();
if(loadedGeometry.getSkinIndices().length()!=0 && loadedGeometry.getSkinWeight().length()!=0){
log("auto-weight from geometry:");
WeightBuilder.autoWeight(loadedGeometry, bones, WeightBuilder.MODE_FROM_GEOMETRY, bodyIndices, bodyWeight);
}else{
//TODO support multiple autoWeight
WeightBuilder.autoWeight(loadedGeometry, bones, WeightBuilder.MODE_NearParentAndChildren, bodyIndices, bodyWeight);
}
}
private void loadJsonModel(String jsonText,LoadHandler handler){
JSONLoader loader=THREE.JSONLoader();
JSONValue lastJsonValue = JSONParser.parseLenient(jsonText);
JSONObject object=lastJsonValue.isObject();
if(object==null){
log("invalid-json object");
}
lastJsonObject=object;
log(object.getJavaScriptObject());
loader.createModel(object.getJavaScriptObject(), handler, "");
loader.onLoadComplete();
}
private void loadModel(String path,final LoadHandler handler){
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(path));
try {
builder.sendRequest(null, new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
loadJsonModel(response.getText(),handler);
}
@Override
public void onError(Request request, Throwable exception) {
Window.alert("load faild:");
}
});
} catch (RequestException e) {
log(e.getMessage());
e.printStackTrace();
}
}
private String textureUrl="female_texture1.png";
private void createSkinnedMesh(){
log(bones);
JsArray<AnimationBone> clonedBone=cloneBones(bones);
//this is not work fine.just remove root moving to decrese flicking
AnimationBoneConverter.setBoneAngles(clonedBone, rawAnimationData, 0);
log(clonedBone);
Geometry newgeo=GeometryUtils.clone(loadedGeometry);
newgeo.setSkinIndices(bodyIndices);
newgeo.setSkinWeight(bodyWeight);
newgeo.setBones(clonedBone);
if(skinnedMesh!=null){
root.remove(skinnedMesh);
}
Material material=null;
if(useBasicMaterial.getValue()){
material=THREE.MeshBasicMaterial().skinning(true).color(0xffffff).map(ImageUtils.loadTexture(textureUrl)).build();
}else{
material=THREE.MeshLambertMaterial().skinning(true).color(0xffffff).map(ImageUtils.loadTexture(textureUrl)).build();
}
skinnedMesh = THREE.SkinnedMesh(newgeo, material);
root.add(skinnedMesh);
if(animation!=null){
AnimationHandler.removeFromUpdate(animation);
}
animation = THREE.Animation( skinnedMesh, animationName );
animation.play(true,currentTime);
}
private List<Mesh> vertexMeshs=new ArrayList<Mesh>();
private IndexAndWeightEditor indexWeightEditor;
//simple simple near positions only use end point,this is totall not good
private int findNear(List<Vector3> bonePositions,Vector3 pos){
Vector3 pt=THREE.Vector3();
Vector3 near=pt.sub(bonePositions.get(0),pos);
int index=0;
double length=pt.length();
for(int i=1;i<bonePositions.size();i++){
Vector3 npt=THREE.Vector3();
near=npt.sub(bonePositions.get(i),pos);
double l=near.length();
if(l<length){
index=i;
length=l;
}
}
return index;
}
private Map<Integer,Integer> createChildMap(JsArray<AnimationBone> bones){
Map<Integer,Integer> childMap=new HashMap<Integer,Integer>();
for(int i=0;i<bones.length();i++){
List<Integer> children=new ArrayList<Integer>();
for(int j=0;j<bones.length();j++){
AnimationBone child=bones.get(j);
if(child.getParent()==i){
children.add(j);
}
}
if(children.size()==1){
childMap.put(i, children.get(0));
}
}
return childMap;
}
List<List<GWTWeightData>> wdatas;
/*
* some point totally wrong?or only work on multiple weight points
*
*/
JsArrayString colladaJoints;
Map<String,Integer> boneNameMaps;
private CheckBox useBasicMaterial;
private JSONObject lastJsonObject;
private CheckBox withAnimation;
private StackLayoutPanel stackPanel;
private ListBox boneListBox;
private Button updateWeightButton;
private Vector4 convertWeight(int index,ColladaData collada){
if(wdatas==null){
//wdatas=new WeighDataParser().parse(Bundles.INSTANCE.weight().getText());
wdatas=new WeighDataParser().convert(collada.getWeights());
for(List<GWTWeightData> wd:wdatas){
String log="";
for(GWTWeightData w:wd){
log+=w.getBoneIndex()+":"+w.getWeight()+",";
}
//log(log);
}
}
List<GWTWeightData> wd=wdatas.get(index);
if(wd.size()<2){
int id=wd.get(0).getBoneIndex();
String fname=colladaJoints.get(id);
id=boneNameMaps.get(fname);
return THREE.Vector4(id,id,1,0);
}else{
int fid=wd.get(0).getBoneIndex();
int sid=wd.get(1).getBoneIndex();
String fname=colladaJoints.get(fid);
fid=boneNameMaps.get(fname);
String sname=colladaJoints.get(sid);
sid=boneNameMaps.get(sname);
double fw=wd.get(0).getWeight();
double sw=wd.get(1).getWeight();
//log(fid+":"+fw+","+sid+":"+sw);
//fw=1;
return THREE.Vector4(fid,sid,fw,sw);
}
}
private Vector4 findNearSpecial(List<NameAndPosition> nameAndPositions,Vector3 pos,JsArray<AnimationBone> bones,int vindex){
Vector3 pt=nameAndPositions.get(0).getPosition().clone();
Vector3 near=pt.subSelf(pos);
int index1=nameAndPositions.get(0).getIndex();
double near1=near.length();
int index2=index1;
double near2=near1;
int nameIndex1=0;
int nameIndex2=0;
for(int i=1;i<nameAndPositions.size();i++){
Vector3 npt=nameAndPositions.get(i).getPosition().clone();
Vector3 subPos=npt.subSelf(pos);
double l=subPos.length();
//if(vindex==250)log(nameAndPositions.get(i).getName()+","+l);
if(l<near1){
int tmp=index1;
double tmpL=near1;
int tmpName=nameIndex1;
index1=nameAndPositions.get(i).getIndex();
near1=l;
nameIndex1=i;
if(tmpL<near2){
index2=tmp;
near2=tmpL;
nameIndex2=tmpName;
}
}else if(l<near2){
index2=nameAndPositions.get(i).getIndex();
near2=l;
nameIndex2=i;
}
}
Map<Integer,Double> totalLength=new HashMap<Integer,Double>();
Map<Integer,Integer> totalIndex=new HashMap<Integer,Integer>();
//zero is largest
Vector3 rootNear=nameAndPositions.get(0).getPosition().clone();
rootNear.subSelf(pos);
for(int i=0;i<nameAndPositions.size();i++){
int index=nameAndPositions.get(i).getIndex();
Vector3 nearPos=nameAndPositions.get(i).getPosition().clone();
nearPos.subSelf(pos);
double l=nearPos.length();
Double target=totalLength.get(index);
double cvalue=0;
if(target!=null){
cvalue=target.doubleValue();
}
cvalue+=l;
totalLength.put(index,cvalue);
Integer count=totalIndex.get(index);
int countV=0;
if(count!=null){
countV=count;
}
countV++;
totalIndex.put(index, countV);
}
//do average for end like head
Integer[] keys=totalLength.keySet().toArray(new Integer[0]);
for(int i=0;i<keys.length;i++){
int index=keys[i];
int count=totalIndex.get(index);
totalLength.put(index, totalLength.get(index)/count);
}
if(index1==index2){
log(""+vindex+","+nameIndex1+":"+nameIndex2);
if(vindex==250){
// log(nameAndPositions.get(nameIndex1).getPosition());
// log(nameAndPositions.get(nameIndex2).getPosition());
}
return THREE.Vector4(index1,index1,1,0);
}else{
double near1Length=totalLength.get(index1);
double near2Length=totalLength.get(index2);
double total=near1Length+near2Length;
return THREE.Vector4(index1,index2,(total-near1Length)/total,(total-near2Length)/total);
}
}
private Vector4 findNearThreeBone(List<NameAndPosition> nameAndPositions,Vector3 pos,JsArray<AnimationBone> bones,int vindex){
Map<Integer,Double> totalLength=new HashMap<Integer,Double>();
Map<Integer,Integer> totalIndex=new HashMap<Integer,Integer>();
log("find-near:"+vindex);
for(int i=0;i<nameAndPositions.size();i++){
int index=nameAndPositions.get(i).getIndex();
Vector3 near=nameAndPositions.get(i).getPosition().clone();
near.subSelf(pos);
double l=near.length();
Double target=totalLength.get(index);
double cvalue=0;
if(target!=null){
cvalue=target.doubleValue();
}
cvalue+=l;
totalLength.put(index,cvalue);
Integer count=totalIndex.get(index);
int countV=0;
if(count!=null){
countV=count;
}
countV++;
totalIndex.put(index, countV);
}
Integer[] keys=totalLength.keySet().toArray(new Integer[0]);
for(int i=0;i<keys.length;i++){
int index=keys[i];
int count=totalIndex.get(index);
totalLength.put(index, totalLength.get(index)/count);
}
int index1=0;
double near1=totalLength.get(keys[0]);
int index2=0;
double near2=totalLength.get(keys[0]);
for(int i=1;i<keys.length;i++){
double l=totalLength.get(keys[i]);
if(l<near1){
int tmp=index1;
double tmpL=near1;
index1=keys[i];
near1=l;
if(tmpL<near2){
index2=tmp;
near2=tmpL;
}
}else if(l<near2){
index2=keys[i];
near2=l;
}
}
if(index1==index2){
return THREE.Vector4(index1,index1,1,0);
}else{
double total=near1+near2;
log("xx:"+index1+","+index2);
return THREE.Vector4(index1,index2,(total-near1)/total,(total-near2)/total);
}
}
//use start,center and end position,choose near 2point
private Vector4 findNearBoneAggresive(List<NameAndPosition> nameAndPositions,Vector3 pos,JsArray<AnimationBone> bones){
Vector3 pt=nameAndPositions.get(0).getPosition().clone();
Vector3 near=pt.subSelf(pos);
int index1=nameAndPositions.get(0).getIndex();
double near1=pt.length();
int index2=nameAndPositions.get(0).getIndex();
double near2=pt.length();
for(int i=1;i<nameAndPositions.size();i++){
Vector3 npt=nameAndPositions.get(i).getPosition().clone();
near=npt.subSelf(pos);
double l=near.length();
if(l<near1){
int tmp=index1;
double tmpL=near1;
index1=nameAndPositions.get(i).getIndex();
near1=l;
if(tmpL<near2){
index2=tmp;
near2=tmpL;
}
}else if(l<near2){
index2=nameAndPositions.get(i).getIndex();
near2=l;
}
}
near1*=near1*near1*near1;
near2*=near2*near2*near2;
if(index1==index2){
return THREE.Vector4(index1,index1,1,0);
}else{
double total=near1+near2;
return THREE.Vector4(index1,index2,(total-near1)/total,(total-near2)/total);
}
}
/*
* find near ,but from three point
*/
private Vector4 findNearSingleBone(List<NameAndPosition> nameAndPositions,Vector3 pos,JsArray<AnimationBone> bones){
Vector3 pt=nameAndPositions.get(0).getPosition().clone();
Vector3 near=pt.subSelf(pos);
int index1=nameAndPositions.get(0).getIndex();
double near1=pt.length();
for(int i=1;i<nameAndPositions.size();i++){
Vector3 npt=nameAndPositions.get(i).getPosition().clone();
near=npt.subSelf(pos);
double l=near.length();
if(l<near1){
index1=nameAndPositions.get(i).getIndex();
near1=l;
}
}
return THREE.Vector4(index1,index1,1,0);
}
//find neard point,choose second from parent or children which near than
private Vector4 findNearParentAndChildren(List<Vector3> bonePositions, Vector3 pos,JsArray<AnimationBone> bones){
Map<Integer,Integer> cm=createChildMap(bones);
Vector3 pt=THREE.Vector3();
Vector3 near=pt.sub(bonePositions.get(0),pos);
int index=0;
double length=pt.length();
for(int i=1;i<bonePositions.size();i++){
Vector3 npt=THREE.Vector3();
near=npt.sub(bonePositions.get(i),pos);
double l=near.length();
if(l<length){
index=i;
length=l;
}
}
if(index!=0){
Vector3 parentPt=THREE.Vector3();
int parentIndex=bones.get(index).getParent();
parentPt=parentPt.sub(bonePositions.get(parentIndex),pos);
double plength=parentPt.length();
Integer child=cm.get(index);
if(child!=null){
Vector3 childPt=THREE.Vector3();
childPt=childPt.sub(bonePositions.get(child),pos);
double clength=childPt.length();
if(clength<plength){
double total=length+clength;
return THREE.Vector4(index,child,(total-length)/total,(total-clength)/total);
}else{
double total=length+plength;
return THREE.Vector4(index,parentIndex,(total-length)/total,(total-plength)/total);
}
}else{
double total=length+plength;
return THREE.Vector4(index,parentIndex,(total-length)/total,(total-plength)/total);
}
}else{
return THREE.Vector4(index,index,1,0);//root
}
}
/*
* find near and choose parent
*/
private Vector4 findNearParent(List<Vector3> bonePositions, Vector3 pos,JsArray<AnimationBone> bones){
Vector3 pt=THREE.Vector3();
Vector3 near=pt.sub(bonePositions.get(0),pos);
int index=0;
double length=pt.length();
for(int i=1;i<bonePositions.size();i++){
Vector3 npt=THREE.Vector3();
near=npt.sub(bonePositions.get(i),pos);
double l=near.length();
if(l<length){
index=i;
length=l;
}
}
if(index!=0){
Vector3 parentPt=THREE.Vector3();
int parentIndex=bones.get(index).getParent();
parentPt=parentPt.sub(bonePositions.get(parentIndex),pos);
double plength=parentPt.length();
double total=length+plength;
return THREE.Vector4(index,parentIndex,(total-length)/total,(total-plength)/total);
}else{
return THREE.Vector4(index,index,1,0);//root
}
}
//choose two point but only near about first * value
private Vector4 findNearDouble(List<Vector3> bonePositions, Vector3 pos,double value){
Vector3 pt=THREE.Vector3();
Vector3 near=pt.sub(bonePositions.get(0),pos);
int index1=0;
double near1=pt.length();
int index2=0;
double near2=pt.length();
for(int i=1;i<bonePositions.size();i++){
Vector3 npt=THREE.Vector3();
near=npt.sub(bonePositions.get(i),pos);
double l=near.length();
if(l<near1){
int tmp=index1;
double tmpL=near1;
index1=i;
near1=l;
if(tmpL<near2){
index2=tmp;
near2=tmpL;
}
}else if(l<near2){
index2=i;
near2=l;
}
}
if(index1==index2){
return THREE.Vector4(index1,index1,1,0);
}else if(near2>near1*value){
//too fa near2
return THREE.Vector4(index1,index1,1,0);
}else{
double total=near1+near2;
return THREE.Vector4(index1,index2,near1/total,near2/total);
}
}
}
|
package org.jetel.component;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Map.Entry;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jetel.data.formatter.DelimitedDataFormatter;
import org.jetel.exception.ComponentNotReadyException;
import org.jetel.exception.ConfigurationProblem;
import org.jetel.exception.ConfigurationStatus;
import org.jetel.exception.JetelException;
import org.jetel.exception.XMLConfigurationException;
import org.jetel.graph.InputPort;
import org.jetel.graph.Node;
import org.jetel.graph.Result;
import org.jetel.graph.TransformationGraph;
import org.jetel.metadata.DataFieldMetadata;
import org.jetel.metadata.DataRecordMetadata;
import org.jetel.util.exec.LoggerDataConsumer;
import org.jetel.util.exec.ProcBox;
import org.jetel.util.property.ComponentXMLAttributes;
import org.jetel.util.string.StringUtils;
import org.w3c.dom.Element;
public class PostgreSqlDataWriter extends BulkLoader {
private static Log logger = LogFactory.getLog(PostgreSqlDataWriter.class);
/** Description of the Field */
// attributes for psql client
private static final String XML_PSQL_PATH_ATTRIBUTE = "psqlPath";
private static final String XML_COMMAND_URL_ATTRIBUTE = "commandURL";
private static final String XML_HOST_ATTRIBUTE = "host";
// params for psql client
private static final String PSQL_ECHO_ALL_PARAM = "echoAll";
private static final String PSQL_ECHO_QUERIES_PARAM = "echoQueries";
private static final String PSQL_ECHO_HIDDEN_PARAM = "echoHidden";
private static final String PSQL_LOG_FILE_PARAM = "logFile";
private static final String PSQL_OUTPUT_PARAM = "output";
private static final String PSQL_PORT_PARAM = "port";
private static final String PSQL_PSET_PARAM = "pset";
private static final String PSQL_QUIET_PARAM = "quiet";
private static final String PSQL_NO_PSQLRC_PARAM = "noPsqlrc";
private static final String PSQL_SINGLE_TRANSACTION_PARAM = "singleTransaction";
// params for copy statement
private static final String COPY_COLUMNS_PARAM = "columns";
private static final String COPY_BINARY_PARAM = "binary";
private static final String COPY_OIDS_PARAM = "oids";
private static final String COPY_NULL_PARAM = "null";
private static final String COPY_CSV_PARAM = "csv";
private static final String COPY_CSV_HEADER_PARAM = "csvHeader";
private static final String COPY_CSV_QUOTE_PARAM = "csvQuote";
private static final String COPY_CSV_ESCAPE_PARAM = "csvEscape";
private static final String COPY_CSV_FORCE_NOT_NULL_PARAM = "csvForceNotNull";
// switches for psql client,these switches have own xml attributes
private static final String PSQL_DATABASE_SWITCH = "dbname";
private static final String PSQL_COMMAND_URL_SWITCH = "file";
private static final String PSQL_HOST_SWITCH = "host";
private static final String PSQL_USER_SWITCH = "username";
// switches for psql client
private static final String PSQL_ECHO_ALL_SWITCH = "echo-all";
private static final String PSQL_ECHO_QUERIES_SWITCH = "echo-queries";
private static final String PSQL_ECHO_HIDDEN_SWITCH = "echo-hidden";
private static final String PSQL_LOG_FILE_SWITCH = "log-file";
private static final String PSQL_OUTPUT_SWITCH = "output";
private static final String PSQL_PORT_SWITCH = "port";
private static final String PSQL_PSET_SWITCH = "pset";
private static final String PSQL_QUIET_SWITCH = "quiet";
private static final String PSQL_NO_PSQLRC_SWITCH = "no-psqlrc";
private static final String PSQL_SINGLE_TRANSACTION_SWITCH = "single-transaction";
// keywords for copy statement
private final static String COPY_STDIN_KEYWORD = "pstdin";
public final static String COMPONENT_TYPE = "POSTGRESQL_DATA_WRITER";
private final static String POSTGRESQL_FILE_NAME_PREFIX = "postgresql";
private final static String DEFAULT_COLUMN_DELIMITER = "\t";
private final static String DEFAULT_COLUMN_DELIMITER_IN_CSV_MODE = ",";
private final static String DEFAULT_RECORD_DELIMITER = "\n";
private final static String DEFAULT_DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
private final static String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
private final static String DEFAULT_TIME_FORMAT = "HH:mm:ss";
private final static String DEFAULT_NULL_VALUE = "";
private final static String DEFAULT_NULL_VALUE_IN_TEXT_MODE = "\\N";
// variables for psql client
private String commandURL;
// variables for copy statement
private File commandFile;
private String[] commandLine; // command line of psql
private boolean csvMode; // true if CSV mode is used for loading data
/**
* Constructor for the PostgreSqlDataWriter object
*
* @param id Description of the Parameter
*/
public PostgreSqlDataWriter(String id, String psqlPath, String database) {
super(id, psqlPath, database);
}
/**
* Main processing method for the PsqlDataWriter object
*
* @since April 4, 2002
*/
public Result execute() throws Exception {
ProcBox box;
int processExitValue = 0;
if (isDataReadFromPort) {
if (dataURL != null) {
// dataFile is used for exchange data
readFromPortAndWriteByFormatter(new FileOutputStream(dataFile));
box = createProcBox();
} else {
Process process = Runtime.getRuntime().exec(commandLine);
box = createProcBox(process);
// stdin is used for exchange data - set data target to stdin of process
OutputStream processIn = new BufferedOutputStream(process.getOutputStream());
readFromPortAndWriteByFormatter(processIn);
}
processExitValue = box.join();
} else {
processExitValue = readDataDirectlyFromFile();
}
if (processExitValue != 0) {
throw new JetelException(getErrorMsg(processExitValue));
}
return runIt ? Result.FINISHED_OK : Result.ABORTED;
}
/**
* Return error message according to error code.
* @param exitValue error code of psql utility
* @return textual error message
*/
private String getErrorMsg(int exitValue) {
String errorMsg;
switch (exitValue) {
case 1:
errorMsg = "a fatal error of its own (out of memory, file not found) occurs";
break;
case 2:
errorMsg = "the connection to the server went bad and the session was not interactive";
break;
case 3:
errorMsg = "an error occurred in a script and the variable ON_ERROR_STOP was set";
break;
default:
errorMsg = "unknown error";
}
return "psql utility has failed - " + errorMsg + ".";
}
/**
* Create instance of ProcBox.
*
* @param process running process; when process is null, default process is created
* @return instance of ProcBox
* @throws IOException
*/
// TODO this method will be deleted from this class after removing commandLine attribute to superclass
protected ProcBox createProcBox(Process process) throws IOException {
if (process == null) {
process = Runtime.getRuntime().exec(commandLine);
}
return new ProcBox(process, null, consumer, errConsumer);
}
/**
* Create command line for process, where psql utility is running.
* Example: psql --dbname=testdb --file=/tmp/command.ctl
*
* @return array, first field is name of psql utility and the others fields are parameters
* @throws ComponentNotReadyException when command file isn't created
*/
private String[] createCommandLineForDbLoader() throws ComponentNotReadyException {
if (ProcBox.isWindowsPlatform()) {
loadUtilityPath = StringUtils.backslashToSlash(loadUtilityPath);
}
PsqlCommandBuilder command = new PsqlCommandBuilder(loadUtilityPath, properties);
command.addParam(null, PSQL_DATABASE_SWITCH, database);
command.addParam(null, PSQL_COMMAND_URL_SWITCH, createCommandFile());
command.addParam(null, PSQL_HOST_SWITCH, host);
command.addParam(null, PSQL_USER_SWITCH, user);
command.addBooleanParam(PSQL_ECHO_ALL_PARAM, PSQL_ECHO_ALL_SWITCH);
command.addBooleanParam(PSQL_ECHO_QUERIES_PARAM, PSQL_ECHO_QUERIES_SWITCH);
command.addBooleanParam(PSQL_ECHO_HIDDEN_PARAM, PSQL_ECHO_HIDDEN_SWITCH);
command.addParam(PSQL_LOG_FILE_PARAM, PSQL_LOG_FILE_SWITCH, null);
command.addParam(PSQL_OUTPUT_PARAM, PSQL_OUTPUT_SWITCH, null);
command.addParam(PSQL_PORT_PARAM, PSQL_PORT_SWITCH, null);
command.addParam(PSQL_PSET_PARAM, PSQL_PSET_SWITCH, null);
command.addBooleanParam(PSQL_QUIET_PARAM, PSQL_QUIET_SWITCH);
command.addBooleanParam(PSQL_NO_PSQLRC_PARAM, PSQL_NO_PSQLRC_SWITCH);
command.addBooleanParam(PSQL_SINGLE_TRANSACTION_PARAM, PSQL_SINGLE_TRANSACTION_SWITCH);
return command.getCommand();
}
/**
* Create file that contains <i>copy</i> statement and return its name.
*
* @return name of the command file
* @throws ComponentNotReadyException when command file isn't created
*/
String createCommandFile() throws ComponentNotReadyException {
try {
if (commandURL != null) {
commandFile = new File(commandURL);
if (commandFile.exists()) {
return commandFile.getCanonicalPath();
} else {
commandFile.createNewFile();
}
} else {
commandFile = File.createTempFile(POSTGRESQL_FILE_NAME_PREFIX,
CONTROL_FILE_NAME_SUFFIX, TMP_DIR);
}
saveCommandToFile(commandFile, getDefaultCommandFileContent());
return commandFile.getCanonicalPath();
} catch (IOException ioe) {
throw new ComponentNotReadyException(this,
"Can't create command file for psql utility.", ioe);
}
}
/**
* Save <i>copy</i> statement to the file.
* @param commandFile file where the copy statement will be saved.
* @param command copy statement to save
* @throws IOException when error occured
*/
private void saveCommandToFile(File commandFile, String command) throws IOException {
FileWriter commandWriter = new FileWriter(commandFile);
printCommandToLog(command);
commandWriter.write(command);
commandWriter.close();
}
/**
* Print <i>copy</i> statement to log.
*
* @param command command to be printed
*/
private void printCommandToLog(String command) {
// There is the statement split to two parts, first contains //copy.
// It's due to converting special chars to string - first part (//copy)
// already has correct format for printing.
String[] commandArray = command.split(" ", 2);
logger.debug("Command file content: " + commandArray[0] + " " +
StringUtils.specCharToString(commandArray[1]));
}
/**
* Create and return string that contains <i>copy</i> statement.
* @return string that contains <i>copy</i> statement
* @throws IOException
*/
private String getDefaultCommandFileContent() throws IOException {
CopyCommandBuilder command = new CopyCommandBuilder("\\copy", properties);
// \copy table [ ( column_list ) ]
command.append(table);
if (properties.containsKey(COPY_COLUMNS_PARAM)) {
command.append("(" + properties.getProperty(COPY_COLUMNS_PARAM) + ")");
}
// from { filename | pstdin }
command.append("from");
if (dataFile != null) {
command.append(dataFile.getCanonicalPath());
} else {
command.append(COPY_STDIN_KEYWORD);
}
// [ with ] [ binary ] [ oids ] [ delimiter [ as ] 'character' ] [ null [ as ] 'string' ]
if (isWithKeywordUsed()) {
command.append("with");
command.addBooleanParam(COPY_BINARY_PARAM, COPY_BINARY_PARAM);
command.addBooleanParam(COPY_OIDS_PARAM, COPY_OIDS_PARAM);
if (isColumnDelimiterUsed()) {
command.append("delimiter '" + columnDelimiter + "'");
}
String nullValue = getNullValue();
if (nullValue != null) {
command.addSingleQuotedParam(null, COPY_NULL_PARAM, nullValue);
// warning that user defined value is ignored - default nullValue is used
if (isDataReadFromPort && properties.containsKey(COPY_NULL_PARAM) &&
!DEFAULT_NULL_VALUE.equals(properties.getProperty(COPY_NULL_PARAM))) {
logger.warn("Parameter " + StringUtils.quote(COPY_NULL_PARAM) + " at " +
StringUtils.quote(XML_PARAMETERS_ATTRIBUTE) +
" attribute is ignored. Default null value is used.");
}
}
}
// [ csv [ header ] [ quote [ as ] 'character' ] [ escape [ as ] 'character' ] [ force not null column_list ] ]
if (csvMode) {
command.append("csv");
command.addBooleanParam(COPY_CSV_HEADER_PARAM, "header");
command.addSingleQuotedParam(COPY_CSV_QUOTE_PARAM, "quote");
command.addSingleQuotedParam(COPY_CSV_ESCAPE_PARAM, "escape");
command.addParam(COPY_CSV_FORCE_NOT_NULL_PARAM, "force not null");
}
return command.toString();
}
/**
* Return true if <i>with</i> keyword is used in copy statement.
* @return true if <i>with</i> keyword is used in copy statement
*/
private boolean isWithKeywordUsed() {
return csvMode ||
properties.containsKey(COPY_BINARY_PARAM) ||
properties.containsKey(COPY_OIDS_PARAM) ||
isColumnDelimiterUsed() ||
getNullValue() != null;
}
/**
* Return true if <i>columnDelimiter</i> is used in copy statement.
* @return true if <i>columnDelimiter</i> is used in copy statement
*/
private boolean isColumnDelimiterUsed() {
return (csvMode && !columnDelimiter.equals(DEFAULT_COLUMN_DELIMITER_IN_CSV_MODE)) ||
(!csvMode && !columnDelimiter.equals(DEFAULT_COLUMN_DELIMITER));
}
/**
* If nullValue is used in copy statement then string is returned, else null is returned.
* if data is read from port then nullValue == DEFAULT_NULL_VALUE
* if data is read directly from flat file then nullValue can be defined by user
* @return string represents nullValuu or null if nullValue isn't used in copy statement.
*/
private String getNullValue() {
if (isDataReadFromPort) {
return DEFAULT_NULL_VALUE;
} else {
if (properties.containsKey(COPY_NULL_PARAM)) {
String nullValue = properties.getProperty(COPY_NULL_PARAM);
if ((csvMode && !nullValue.equals(DEFAULT_NULL_VALUE)) ||
(!csvMode && !nullValue.equals(DEFAULT_NULL_VALUE_IN_TEXT_MODE))) {
return nullValue;
}
}
}
return null;
}
/**
* Description of the Method
*
* @exception ComponentNotReadyException Description of the Exception
* @since April 4, 2002
*/
public void init() throws ComponentNotReadyException {
if (isInitialized()) return;
super.init();
csvMode = isCsvModeUsed(properties);
setDefaultColumnDelimiter(csvMode);
checkParams();
// prepare (temporary) data file
if (isDataReadFromPort) {
if (dataURL != null) {
dataFile = new File(dataURL);
dataFile.delete();
}
} else {
try {
if (!fileExists(dataURL)) {
free();
throw new ComponentNotReadyException(this,
"Data file " + StringUtils.quote(dataURL) + " not exists.");
}
} catch (Exception e) {
throw new ComponentNotReadyException(this, e);
}
dataFile = new File(dataURL);
}
commandLine = createCommandLineForDbLoader();
printCommandLineToLog(commandLine);
if (isDataReadFromPort) {
InputPort inPort = getInputPort(READ_FROM_PORT);
dbMetadata = createPsqlMetadata(inPort.getMetadata());
// init of data formatter
formatter = new DelimitedDataFormatter(CHARSET_NAME);
formatter.init(dbMetadata);
}
errConsumer = new LoggerDataConsumer(LoggerDataConsumer.LVL_ERROR, 0);
consumer = new LoggerDataConsumer(LoggerDataConsumer.LVL_DEBUG, 0);
}
/**
* Print system command with it's parameters to log.
* @param command
*/
private void printCommandLineToLog(String[] command) {
StringBuilder msg = new StringBuilder("System command: \"");
msg.append(command[0]).append("\" with parameters:\n");
for (int idx = 1; idx < command.length; idx++) {
msg.append(idx).append(": ").append(command[idx]).append("\n");
}
logger.debug(msg.toString());
}
/**
* If no columnDelimiter is set then default column delimiter is set.
* @param csvModeUsed
*/
private void setDefaultColumnDelimiter(boolean csvModeUsed) {
if (columnDelimiter == null) {
if (csvModeUsed) {
columnDelimiter = DEFAULT_COLUMN_DELIMITER_IN_CSV_MODE;
} else {
columnDelimiter = DEFAULT_COLUMN_DELIMITER;
}
}
}
/**
* Return true if csv mode is used for loading data.
* @param prop properties with info about loading data
* @return true if csv mode is used for loading data else false
*/
private boolean isCsvModeUsed(Properties prop) {
return prop.containsKey(COPY_CSV_PARAM) ||
prop.containsKey(COPY_CSV_HEADER_PARAM) ||
prop.containsKey(COPY_CSV_QUOTE_PARAM) ||
prop.containsKey(COPY_CSV_ESCAPE_PARAM) ||
prop.containsKey(COPY_CSV_FORCE_NOT_NULL_PARAM);
}
/**
* Checks if mandatory attributes are defined.
* And check combination of some parameters.
*
* @throws ComponentNotReadyException if any of conditions isn't fulfilled
*/
private void checkParams() throws ComponentNotReadyException {
if (StringUtils.isEmpty(loadUtilityPath)) {
throw new ComponentNotReadyException(this, StringUtils.quote(XML_PSQL_PATH_ATTRIBUTE)
+ " attribute have to be set.");
}
if (StringUtils.isEmpty(database)) {
throw new ComponentNotReadyException(this,
StringUtils.quote(XML_DATABASE_ATTRIBUTE) + " attribute have to be set.");
}
if (StringUtils.isEmpty(table) && !fileExists(commandURL)) {
throw new ComponentNotReadyException(this,
StringUtils.quote(XML_TABLE_ATTRIBUTE) + " attribute has to be specified or " +
StringUtils.quote(XML_COMMAND_URL_ATTRIBUTE) +
" attribute has to be specified and file at the URL must exists.");
}
if (!isDataReadFromPort && !fileExists(dataURL) && !fileExists(commandURL)) {
throw new ComponentNotReadyException(this, "Input port or " +
StringUtils.quote(XML_FILE_URL_ATTRIBUTE) +
" attribute or " + StringUtils.quote(XML_COMMAND_URL_ATTRIBUTE) +
" attribute have to be specified and specified file must exist.");
}
if (columnDelimiter.length() != 1) {
throw new ComponentNotReadyException(this, XML_COLUMN_DELIMITER_ATTRIBUTE,
"Max. length of column delimiter is one.");
}
if (properties.containsKey(COPY_BINARY_PARAM) &&
(isColumnDelimiterUsed() || getNullValue() != null || csvMode)) {
throw new ComponentNotReadyException(this, "You cannot specify the " +
StringUtils.quote(XML_COLUMN_DELIMITER_ATTRIBUTE) + " attribute, " +
StringUtils.quote(COPY_NULL_PARAM) + " param or " +
StringUtils.quote("csv") + " param in binary mode (" +
StringUtils.quote(COPY_BINARY_PARAM) + ").");
}
}
/**
* Modify metadata so that they correspond to psql input format.
* Each field is delimited and it has the same delimiter.
* Only last field has different delimiter.
*
* @param oldMetadata original metadata
* @return modified metadata
*/
private DataRecordMetadata createPsqlMetadata(DataRecordMetadata originalMetadata) {
DataRecordMetadata metadata = originalMetadata.duplicate();
metadata.setRecType(DataRecordMetadata.DELIMITED_RECORD);
for (int idx = 0; idx < metadata.getNumFields() - 1; idx++) {
metadata.getField(idx).setDelimiter(columnDelimiter);
metadata.getField(idx).setSize((short)0);
setPsqlDateFormat(metadata.getField(idx));
}
int lastIndex = metadata.getNumFields() - 1;
metadata.getField(lastIndex).setDelimiter(DEFAULT_RECORD_DELIMITER);
metadata.getField(lastIndex).setSize((short)0);
metadata.setRecordDelimiters("");
setPsqlDateFormat(metadata.getField(lastIndex));
return metadata;
}
/**
* If field has format of date or time then default psql format is set.
*
* @param field
*/
private void setPsqlDateFormat(DataFieldMetadata field) {
if (field.getType() == DataFieldMetadata.DATE_FIELD ||
field.getType() == DataFieldMetadata.DATETIME_FIELD) {
boolean isDate = field.isDateFormat();
boolean isTime = field.isTimeFormat();
// if formatStr is undefined then DEFAULT_DATETIME_FORMAT is assigned
if ((isDate && isTime) || (StringUtils.isEmpty(field.getFormatStr()))) {
field.setFormatStr(DEFAULT_DATETIME_FORMAT);
} else if (isDate) {
field.setFormatStr(DEFAULT_DATE_FORMAT);
} else {
field.setFormatStr(DEFAULT_TIME_FORMAT);
}
}
}
@Override
public synchronized void free() {
if(!isInitialized()) return;
super.free();
deleteCommandFile();
}
/**
* If command file isn't temporary then it is deleted.
*/
private void deleteCommandFile() {
if (commandFile == null) {
return;
}
if (commandURL == null) {
if (!commandFile.delete()) {
logger.warn("Temp command data file was not deleted.");
}
}
}
/**
* Description of the Method
*
* @param nodeXML
* Description of Parameter
* @return Description of the Returned Value
* @since May 21, 2002
*/
public static Node fromXML(TransformationGraph graph, Element xmlElement) throws XMLConfigurationException {
ComponentXMLAttributes xattribs = new ComponentXMLAttributes(xmlElement, graph);
try {
PostgreSqlDataWriter postgreSQLDataWriter = new PostgreSqlDataWriter(
xattribs.getString(XML_ID_ATTRIBUTE),
xattribs.getString(XML_PSQL_PATH_ATTRIBUTE),
xattribs.getString(XML_DATABASE_ATTRIBUTE));
if (xattribs.exists(XML_COMMAND_URL_ATTRIBUTE)) {
postgreSQLDataWriter.setCommandURL((xattribs.getString(XML_COMMAND_URL_ATTRIBUTE)));
}
if (xattribs.exists(XML_HOST_ATTRIBUTE)) {
postgreSQLDataWriter.setHost(xattribs.getString(XML_HOST_ATTRIBUTE));
}
if (xattribs.exists(XML_USER_ATTRIBUTE)) {
postgreSQLDataWriter.setUser(xattribs.getString(XML_USER_ATTRIBUTE));
}
if (xattribs.exists(XML_TABLE_ATTRIBUTE)) {
postgreSQLDataWriter.setTable(xattribs.getString(XML_TABLE_ATTRIBUTE));
}
if (xattribs.exists(XML_FILE_URL_ATTRIBUTE)) {
postgreSQLDataWriter.setFileUrl(xattribs.getString(XML_FILE_URL_ATTRIBUTE));
}
if (xattribs.exists(XML_COLUMN_DELIMITER_ATTRIBUTE)) {
postgreSQLDataWriter.setColumnDelimiter(xattribs.getString(XML_COLUMN_DELIMITER_ATTRIBUTE));
}
if (xattribs.exists(XML_PARAMETERS_ATTRIBUTE)) {
postgreSQLDataWriter.setParameters(xattribs.getString(XML_PARAMETERS_ATTRIBUTE));
}
return postgreSQLDataWriter;
} catch (Exception ex) {
throw new XMLConfigurationException(COMPONENT_TYPE + ":" +
xattribs.getString(XML_ID_ATTRIBUTE, " unknown ID ") +
":" + ex.getMessage(), ex);
}
}
@Override
public void toXML(Element xmlElement) {
super.toXML(xmlElement);
xmlElement.setAttribute(XML_PSQL_PATH_ATTRIBUTE, loadUtilityPath);
xmlElement.setAttribute(XML_DATABASE_ATTRIBUTE, database);
if (!StringUtils.isEmpty(commandURL)) {
xmlElement.setAttribute(XML_COMMAND_URL_ATTRIBUTE, commandURL);
}
if (!StringUtils.isEmpty(host)) {
xmlElement.setAttribute(XML_HOST_ATTRIBUTE, host);
}
if (!StringUtils.isEmpty(user)) {
xmlElement.setAttribute(XML_USER_ATTRIBUTE, user);
}
if (!StringUtils.isEmpty(table)) {
xmlElement.setAttribute(XML_TABLE_ATTRIBUTE, table);
}
if (!StringUtils.isEmpty(dataURL)) {
xmlElement.setAttribute(XML_FILE_URL_ATTRIBUTE, dataURL);
}
if (!DEFAULT_COLUMN_DELIMITER.equals(columnDelimiter)) {
xmlElement.setAttribute(XML_COLUMN_DELIMITER_ATTRIBUTE, columnDelimiter);
}
if (!StringUtils.isEmpty(parameters)) {
xmlElement.setAttribute(XML_PARAMETERS_ATTRIBUTE, parameters);
} else if (!properties.isEmpty()) {
StringBuilder props = new StringBuilder();
for (Iterator iter = properties.entrySet().iterator(); iter.hasNext();) {
Entry<String, String> element = (Entry<String, String>) iter.next();
props.append(element.getKey());
props.append('=');
props.append(StringUtils.isQuoted(element.getValue()) ? element.getValue() : StringUtils
.quote(element.getValue()));
props.append(';');
}
xmlElement.setAttribute(XML_PARAMETERS_ATTRIBUTE, props.toString());
}
}
/** Description of the Method */
@Override
public ConfigurationStatus checkConfig(ConfigurationStatus status) {
super.checkConfig(status);
if(!checkInputPorts(status, 0, 1)
|| !checkOutputPorts(status, 0, 0)) {
return status;
}
try {
init();
} catch (ComponentNotReadyException e) {
ConfigurationProblem problem = new ConfigurationProblem(e.getMessage(),
ConfigurationStatus.Severity.ERROR, this,ConfigurationStatus.Priority.NORMAL);
if (!StringUtils.isEmpty(e.getAttributeName())) {
problem.setAttributeName(e.getAttributeName());
}
status.add(problem);
} finally {
free();
}
return status;
}
public String getType() {
return COMPONENT_TYPE;
}
public void setCommandURL(String commandURL) {
this.commandURL = commandURL;
}
private class PsqlCommandBuilder {
private final static String SWITCH_MARK = "
private Properties params;
private List<String> cmdList;
private PsqlCommandBuilder(String command, Properties properties) {
this.params = properties;
cmdList = new ArrayList<String>();
cmdList.add(command);
}
/**
* If paramName is in properties and doesn't equal "false" adds:
* "<i><b>switchMark</b>switchString</i>"<br>
* for exmaple: --compress
*
* @param paramName
* @param switchString
*/
private void addBooleanParam(String paramName, String switchString) {
if (params.containsKey(paramName) && !"false".equalsIgnoreCase(params.getProperty(paramName))) {
cmdList.add(SWITCH_MARK + switchString);
}
}
/**
* if paramValue isn't null or paramName is in properties adds:
* "<i><b>switchMark</b>switchString</i>=paramValue"<br>
* for exmaple: --host=localhost
*
* @param paramName
* @param switchString
* @param paramValue
*/
private void addParam(String paramName, String switchString, String paramValue) {
if (paramValue == null && (paramName == null || !params.containsKey(paramName))) {
return;
}
String param = SWITCH_MARK + switchString + EQUAL_CHAR;
if (paramValue != null) {
param += StringUtils.specCharToString(paramValue);
} else {
param += StringUtils.specCharToString(params.getProperty(paramName));
}
cmdList.add(param);
}
/**
* Return command line where each parameter is one field in array.
* @return command line
*/
private String[] getCommand() {
return cmdList.toArray(new String[cmdList.size()]);
}
}
private class CopyCommandBuilder {
private StringBuilder command;
private Properties properties;
public CopyCommandBuilder(String command, Properties properties) {
this.command = new StringBuilder(command);
this.properties = properties;
}
public StringBuilder append(String str) {
return command.append(" " + str);
}
public String toString() {
return command.toString();
}
/**
* If paramName is contained in properties and it's value
* doesn't equal "false" then param is added to command.
*
* @param paramName name of param in properties
* @param param name of param in command
*/
public void addBooleanParam(String paramName, String param) {
if (properties.containsKey(paramName) &&
!"false".equalsIgnoreCase(properties.getProperty(paramName))) {
append(param);
}
}
/**
* Add single quoted param at the end of command.
* If <i>paramName</i> is contained in properties then <i>param</i> and
* single quoted value of <i>paramName</i> are added to command.
*
* @param paramName name of param in properties
* @param param name of param in command
*/
public void addSingleQuotedParam(String paramName, String param) {
addSingleQuotedParam(paramName, param, null);
}
/**
* Add single quoted param at the end of command.
* If <i>paramName</i> is contained in properties then <i>param</i> and
* single quoted value of <i>paramName</i> are added to command.
* If paramName is null or isn't in properties then default value is
* used instead of value of <i>paramName</i>
*
* @param paramName name of param in properties
* @param param name of param in command
* @param defaultValue value that is used when paramName isn't in properties
*/
public void addSingleQuotedParam(String paramName, String param, String defaultValue) {
if (paramName != null && properties.containsKey(paramName)) {
append(param + " '" + properties.getProperty(paramName) + "'");
return;
}
if (defaultValue != null) {
append(param + " '" + defaultValue + "'");
}
}
/**
* If <i>paramName</i> is contained in properties then <i>param</i> and
* value of <i>paramName</i> are added to command.
*
* @param paramName name of param in properties
* @param param name of param in command
*/
public void addParam(String paramName, String param) {
if (properties.containsKey(paramName)) {
append(param + " " + properties.getProperty(paramName));
}
}
}
}
|
package org.jgroups.stack;
import org.jgroups.annotations.GuardedBy;
/**
* Manages retransmission timeouts. Always returns the next timeout, until the last timeout in the
* array is reached. Returns the last timeout from then on. Note that this class is <em?not</em> immutable,
* so it shouldn't be shared between instances, as {@link #next()} will modify the state.
* @author John Giorgiadis
* @author Bela Ban
* @version $Id: StaticInterval.java,v 1.3 2007/08/10 12:47:38 belaban Exp $
*/
public class StaticInterval implements Interval {
private int next=0;
private final long[] values;
public StaticInterval(long ... vals) {
if (vals.length == 0)
throw new IllegalArgumentException("zero length array passed as argument");
this.values=vals;
}
public Interval copy() {
return new StaticInterval(values);
}
/** @return the next interval */
@GuardedBy("interval")
public long next() {
// we don't need to synchronize because this method won't be called concurrently; each entry has its own copy
// of StaticInterval
// synchronized(values) {
if (next >= values.length)
return(values[values.length-1]);
else
return(values[next++]);
}
}
|
package com.xlythe.dao;
import android.content.Context;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricGradleTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
import org.robolectric.shadows.ShadowLog;
import java.util.List;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertTrue;
@RunWith(RobolectricGradleTestRunner.class)
@Config(sdk=23, shadows={}, constants = BuildConfig.class)
public class RemoteModelTest {
private Context mContext;
private MockServer mMockServer;
@Before
public void setup() {
// Set up the server
mMockServer = new MockServer();
MockRemoteModel.setServer(mMockServer);
// Print out logs to the console
ShadowLog.stream = System.out;
// Grab the context
mContext = RuntimeEnvironment.application;
// Clear the cache
new MockRemoteModel(mContext).dropTable();
}
@Test
public void cache() {
// There should be nothing in the cache by default
MockRemoteModel result = new MockRemoteModel.Query(mContext).id(1).first();
assertEquals(null, result);
// After we talk to the server, there should be a cache.
mMockServer.setResponse(200, "[{\"id\":1,\"title\":\"\",\"my_long\":0,\"my_bool\":\"false\",\"my_int\":0}]");
new MockRemoteModel.Query(mContext).id(1).first(new RemoteModel.Callback<MockRemoteModel>() {
@Override
public void onSuccess(MockRemoteModel object) {
MockRemoteModel result = new MockRemoteModel.Query(mContext).id(1).first();
assertNotNull(result);
}
@Override
public void onFailure(Throwable throwable) {
throw new IllegalStateException(throwable);
}
});
Robolectric.flushForegroundThreadScheduler();
}
@Test
public void get() {
mMockServer.setResponse(200, "[{\"id\":1,\"title\":\"Hello World\",\"my_long\":1000,\"my_bool\":\"true\",\"my_int\":1}]");
// After we talk to the server, there should be a cache.
new MockRemoteModel.Query(mContext).id(1).all(new RemoteModel.Callback<List<MockRemoteModel>>() {
@Override
public void onSuccess(List<MockRemoteModel> object) {
assertEquals(1, object.size());
assertEquals("Hello World", object.get(0).title);
}
@Override
public void onFailure(Throwable throwable) {
throw new IllegalStateException(throwable);
}
});
Robolectric.flushForegroundThreadScheduler();
}
@Test
public void getFirst() {
mMockServer.setResponse(200, "[{\"id\":1,\"title\":\"Hello World\",\"my_long\":1000,\"my_bool\":\"true\",\"my_int\":1}]");
// After we talk to the server, there should be a cache.
new MockRemoteModel.Query(mContext).id(1).first(new RemoteModel.Callback<MockRemoteModel>() {
@Override
public void onSuccess(MockRemoteModel object) {
assertEquals(1, object.id);
assertEquals("Hello World", object.title);
assertEquals(1000, object.my_long);
assertEquals(true, object.my_bool);
assertEquals(1, object.my_int);
}
@Override
public void onFailure(Throwable throwable) {
throw new IllegalStateException(throwable);
}
});
Robolectric.flushForegroundThreadScheduler();
}
@Test
public void insert() {
mMockServer.setResponse(201, "{\"id\":1,\"title\":\"\",\"my_long\":0,\"my_bool\":\"false\",\"my_int\":0}");
// After we talk to the server, there should be a cache.
new MockRemoteModel.Query(mContext).id(1).insert(new RemoteModel.Callback<MockRemoteModel>() {
@Override
public void onSuccess(MockRemoteModel object) {
assertEquals(1, object.id);
assertEquals("", object.title);
assertEquals(0, object.my_long);
assertEquals(false, object.my_bool);
assertEquals(0, object.my_int);
}
@Override
public void onFailure(Throwable throwable) {
throw new IllegalStateException(throwable);
}
});
Robolectric.flushForegroundThreadScheduler();
}
@Test
public void update() {
mMockServer.setResponse(201, "{\"id\":1,\"title\":\"\",\"my_long\":0,\"my_bool\":\"false\",\"my_int\":0}");
MockRemoteModel model = new MockRemoteModel(mContext);
model.save(new RemoteModel.Callback<MockRemoteModel>() {
@Override
public void onSuccess(MockRemoteModel object) {
assertEquals(1, object.id);
assertEquals("", object.title);
assertEquals(0, object.my_long);
assertEquals(false, object.my_bool);
assertEquals(0, object.my_int);
}
@Override
public void onFailure(Throwable throwable) {
throw new IllegalStateException(throwable);
}
});
}
@Test
public void delete() {
mMockServer.setResponse(204, "Success");
MockRemoteModel model = new MockRemoteModel(mContext);
model.delete(new RemoteModel.Callback<Void>() {
@Override
public void onSuccess(Void object) {
assertTrue(true);
}
@Override
public void onFailure(Throwable throwable) {
throw new IllegalStateException(throwable);
}
});
Robolectric.flushForegroundThreadScheduler();
}
}
|
package org.jetel.data.primitive;
import java.math.BigDecimal;
import java.nio.ByteBuffer;
import junit.framework.TestCase;
import org.jetel.data.Defaults;
public class DecimalNumericTest extends TestCase {
Decimal anInt,aLong,aFloat,aDouble,aDefault,aDoubleIntInt,aDecimalIntInt,anIntInt;
protected void setUp() throws Exception {
super.setUp();
Defaults.init();
anInt=DecimalFactory.getDecimal(0);
aLong=DecimalFactory.getDecimal((long)0);
aFloat=DecimalFactory.getDecimal(0f);
aDouble=DecimalFactory.getDecimal(0);
aDefault=DecimalFactory.getDecimal();
aDoubleIntInt=DecimalFactory.getDecimal(0,9,2);
aDecimalIntInt=DecimalFactory.getDecimal(aDoubleIntInt,6,1);
anIntInt=DecimalFactory.getDecimal(12,4);
}
public void test_values1(){
System.out.println("\nTests for integer:");
for (int i=0;i<5;i++){
int value=0;
switch (i) {
case 1:value=Integer.MIN_VALUE;
break;
case 2:value=Integer.MAX_VALUE;
break;
case 3:value=123;
break;
case 4:value=-123;
break;
}
int less=value-1;
int more=value+1;
anInt.setValue(value);
System.out.println("value set to "+value);
System.out.println("less set to "+less);
System.out.println("more set to "+more);
assertEquals(value,anInt.getInt());
System.out.println("Test for getInt passed");
if (!anInt.isNaN()) assertEquals(new Double(value),new Double(anInt.getDouble()));
System.out.println("Test for getDouble passed (isNaN="+anInt.isNaN()+")");
if (!anInt.isNaN()) assertEquals(value,anInt.getLong());
System.out.println("Test for getLong passed (isNaN="+anInt.isNaN()+")");
if (!anInt.isNaN()) assertEquals(DecimalFactory.getDecimal(value),anInt.getDecimal());
System.out.println("Test for getDecimal passed (isNaN="+anInt.isNaN()+")");
assertNotSame(DecimalFactory.getDecimal(value),anInt.getDecimal());
assertEquals(10,anInt.getPrecision());
assertEquals(0,anInt.getScale());
if (anInt.getInt()==Integer.MAX_VALUE) anInt.setNaN(true);
if (!anInt.isNaN()) assertEquals(-1,anInt.compareTo(DecimalFactory.getDecimal(more)));
if (!anInt.isNaN()) assertEquals(-1,anInt.compareTo(new Integer(more)));
if (!anInt.isNaN()) assertEquals(0,anInt.compareTo(DecimalFactory.getDecimal(value)));
if (!anInt.isNaN()) assertEquals(0,anInt.compareTo(new Integer(value)));
if (!anInt.isNaN()) assertEquals(1,anInt.compareTo(DecimalFactory.getDecimal(less)));
if (!anInt.isNaN()) assertEquals(1,anInt.compareTo(new Integer(less)));
System.out.println("Test for compareTo passed (isNaN="+anInt.isNaN()+")");
}
}
public void test_values2(){
System.out.println("\nTests for long:");
for (int i=0;i<5;i++){
long value=0;
switch (i) {
case 1:value=(long)Integer.MIN_VALUE;
break;
case 2:value=(long)Integer.MAX_VALUE;
break;
case 3:value=Long.MIN_VALUE;
break;
case 4:value=Long.MAX_VALUE;
break;
}
long less=value-1;
long more=value+1;
System.out.println("value set to "+value);
System.out.println("less set to "+less);
System.out.println("more set to "+more);
aLong.setValue(value);
if (Integer.MIN_VALUE<=value && value<=Integer.MAX_VALUE) {
assertEquals(value,aLong.getInt());
System.out.println("Test for getInt passed");
}else{
System.out.println("Test for getInt skipped");
}
if (!aLong.isNaN()) assertEquals(new Double(value),new Double(aLong.getDouble()));
System.out.println("Test for getDouble passed (isNaN="+anInt.isNaN()+")");
if (!aLong.isNaN()) assertEquals(value,aLong.getLong());
System.out.println("Test for getLong passed (isNaN="+anInt.isNaN()+")");
if (!aLong.isNaN()) assertEquals(DecimalFactory.getDecimal(value),aLong.getDecimal());
System.out.println("Test for getDecimal passed (isNaN="+anInt.isNaN()+")");
assertNotSame(DecimalFactory.getDecimal(value),aLong.getDecimal());
assertEquals(19,aLong.getPrecision());
assertEquals(0,aLong.getScale());
if (!aLong.isNaN()&&!(value==Long.MAX_VALUE)) assertEquals(-1,aLong.compareTo(DecimalFactory.getDecimal(more)));
if (!aLong.isNaN()&&!(value==Long.MAX_VALUE)) assertEquals(-1,aLong.compareTo(new Long(more)));
if (!aLong.isNaN()) assertEquals(0,aLong.compareTo(DecimalFactory.getDecimal(value)));
if (!aLong.isNaN()) assertEquals(0,aLong.compareTo(new Long(value)));
if (!aLong.isNaN()) assertEquals(1,aLong.compareTo(DecimalFactory.getDecimal(less)));
if (!aLong.isNaN()) assertEquals(1,aLong.compareTo(new Long(less)));
System.out.println("Test for compareTo passed (isNaN="+anInt.isNaN()+")");
}
}
public void test_values3(){
System.out.println("\nTests for float:");
for (int i=0;i<7;i++){
float value=0;
float less=-0.1f;
float more=0.1f;
switch (i) {
case 1:aFloat=DecimalFactory.getDecimal((float)Long.MIN_VALUE);
value=Long.MIN_VALUE;
less=value-1e19f;
break;
case 2:aFloat=DecimalFactory.getDecimal((float)Long.MAX_VALUE);
value=Long.MAX_VALUE;
more=(float)Long.MAX_VALUE+1e18f;
break;
case 3:aFloat=DecimalFactory.getDecimal(0.000001f);
value=0.000001f;
more=0.000002f;
break;
case 4:aFloat=DecimalFactory.getDecimal(-0.000001f);
value=-0.000001f;
less=-1;
break;
case 5:aFloat=DecimalFactory.getDecimal(Float.MAX_VALUE);
value=Float.MAX_VALUE;
break;
case 6:aFloat=DecimalFactory.getDecimal(Float.MIN_VALUE);
value=Float.MIN_VALUE;
break;
}
System.out.println("value set to "+value);
System.out.println("less set to "+less);
System.out.println("more set to "+more);
if (Integer.MIN_VALUE<=value && value<=Integer.MAX_VALUE) {
assertEquals(new Float(value).intValue(),aFloat.getInt());
System.out.println("Test for getInt passed");
}else{
System.out.println("Test for getInt skipped");
}
if (!aFloat.isNaN()) {
assertEquals(new Double(value),new Double(aFloat.getDouble()));
}
System.out.println("Test for getDouble passed (isNaN="+anInt.isNaN()+")");
if (Long.MIN_VALUE<value && value<Long.MAX_VALUE) {
assertEquals(new Float(value).longValue(),aFloat.getLong());
System.out.println("Test for getLong passed");
}else{
System.out.println("Test for getLong skipped");
}
if (!aFloat.isNaN()) assertEquals(DecimalFactory.getDecimal(value),aFloat.getDecimal());
System.out.println("Test for getDecimal passed (isNaN="+anInt.isNaN()+")");
assertNotSame(DecimalFactory.getDecimal(value),aFloat.getDecimal());
if (!aFloat.isNaN()&&!(value==Float.MAX_VALUE)) assertEquals(-1,aFloat.compareTo(DecimalFactory.getDecimal(more)));
if (!aFloat.isNaN()&&!(value==Float.MAX_VALUE)) assertEquals(-1,aFloat.compareTo(new Double(more)));
if (!aFloat.isNaN()) assertEquals(0,aFloat.compareTo(DecimalFactory.getDecimal(value)));
if (!aFloat.isNaN()) assertEquals(0,aFloat.compareTo(new Double(value)));
if (!aFloat.isNaN()) assertEquals(1,aFloat.compareTo(DecimalFactory.getDecimal(less)));
if (!aFloat.isNaN()) assertEquals(1,aFloat.compareTo(new Double(less)));
System.out.println("Test for compareTo passed (isNaN="+anInt.isNaN()+")");
}
}
public void test_values4(){
System.out.println("\nTests for double:");
for (int i=0;i<7;i++){
double value=0;
double less=-0.1;
double more=0.1;
switch (i) {
case 1:aDouble=DecimalFactory.getDecimal((double)Long.MIN_VALUE);
value=Long.MIN_VALUE;
less=value-1e10;
break;
case 2:aDouble=DecimalFactory.getDecimal((double)Long.MAX_VALUE);
value=Long.MAX_VALUE;
more=value+1e10;
break;
case 3:aDouble=DecimalFactory.getDecimal(Double.MIN_VALUE);
value=Double.MIN_VALUE;
break;
case 4:aDouble=DecimalFactory.getDecimal(-Double.MIN_VALUE);
value=-Double.MIN_VALUE;
break;
case 5:aDouble=DecimalFactory.getDecimal(Double.MAX_VALUE);
value=Double.MAX_VALUE;
break;
case 6:aDouble=DecimalFactory.getDecimal(-(Double.MAX_VALUE));
value=-(Double.MAX_VALUE);
break;
}
System.out.println("value set to "+value);
System.out.println("less set to "+less);
System.out.println("more set to "+more);
if (Integer.MIN_VALUE<value && value<Integer.MAX_VALUE) {
assertEquals(new Double(value).intValue(),aDouble.getInt());
System.out.println("Test for getInt passed");
}else{
System.out.println("Test for getInt skipped");
}
if (!aDouble.isNaN()) assertEquals(new Double(value),new Double(aDouble.getDouble()));
System.out.println("Test for getDouble passed (isNaN="+anInt.isNaN()+")");
if (Long.MIN_VALUE<value && value<Long.MAX_VALUE) {
assertEquals(new Double(value).longValue(),aDouble.getLong());
System.out.println("Test for getLong passed");
}else{
System.out.println("Test for getLong skipped");
}
if (!aDouble.isNaN()) assertEquals(DecimalFactory.getDecimal(value),aDouble.getDecimal());
System.out.println("Test for getDecimal passed (isNaN="+anInt.isNaN()+")");
assertNotSame(DecimalFactory.getDecimal(value),aDouble.getDecimal());
if (!aDouble.isNaN()&&!(value==Double.MAX_VALUE)) assertEquals(-1,aDouble.compareTo(DecimalFactory.getDecimal(more)));
if (!aDouble.isNaN()&&!(value==Double.MAX_VALUE)) assertEquals(-1,aDouble.compareTo(new Double(more)));
if (!aDouble.isNaN()) assertEquals(0,aDouble.compareTo(DecimalFactory.getDecimal(value)));
if (!aDouble.isNaN()) assertEquals(0,aDouble.compareTo(new Double(value)));
if (!aDouble.isNaN()&&!(value==-Double.MAX_VALUE)) assertEquals(1,aDouble.compareTo(DecimalFactory.getDecimal(less)));
if (!aDouble.isNaN()&&!(value==-Double.MAX_VALUE)) assertEquals(1,aDouble.compareTo(new Double(less)));
System.out.println("Test for compareTo passed (isNaN="+anInt.isNaN()+")");
}
}
public void test_values5(){
System.out.println("\nTests for default:");
for (int i=0;i<5;i++){
double value=0;
double d_value=0;
double less=-0.1;
double more=0.1;
switch (i) {
case 1:value=Double.MIN_VALUE;
d_value=0;
break;
case 2:value=-Double.MIN_VALUE;
d_value=0;
break;
case 3:value=999999.99;
d_value=value;
more=999999.999;
break;
case 4:value=-999999.99;
d_value=value;
less=-999999.999;
break;
}
aDefault.setValue(value);
System.out.println("value set to "+value);
System.out.println("less set to "+less);
System.out.println("more set to "+more);
if (Integer.MIN_VALUE<value && value<Integer.MAX_VALUE) {
assertEquals(new Double(d_value).intValue(),aDefault.getInt());
System.out.println("Test for getInt passed");
}else{
System.out.println("Test for getInt skipped");
}
if (!aDefault.isNaN()) {
assertEquals(new Double(d_value),new Double(aDefault.getDouble()));
}
System.out.println("Test for getDouble passed (isNaN="+anInt.isNaN()+")");
if (Long.MIN_VALUE<value && value<Long.MAX_VALUE) {
assertEquals(new Double(d_value).longValue(),aDefault.getLong());
System.out.println("Test for getLong passed");
}else{
System.out.println("Test for getLong skipped");
}
if (!aDefault.isNaN()) assertEquals(DecimalFactory.getDecimal(value,8,2),aDefault.getDecimal());
System.out.println("Test for getDecimal passed (isNaN="+anInt.isNaN()+")");
assertNotSame(DecimalFactory.getDecimal(value),aDefault.getDecimal());
if (!aDefault.isNaN()&&!(value==999999.99)) assertEquals(-1,aDefault.compareTo(DecimalFactory.getDecimal(more)));
if (!aDefault.isNaN()&&!(value==999999.99)) assertEquals(-1,aDefault.compareTo(new Double(more)));
if (!(aDefault.isNaN() || aDefault.getDouble()==0)) assertEquals(0,aDefault.compareTo(DecimalFactory.getDecimal(value)));
if (!(aDefault.isNaN() || aDefault.getDouble()==0)) assertEquals(0,aDefault.compareTo(new Double(value)));
if (!aDefault.isNaN()&&!(value==-999999.99)) assertEquals(1,aDefault.compareTo(DecimalFactory.getDecimal(less)));
if (!aDefault.isNaN()&&!(value==-999999.99)) assertEquals(1,aDefault.compareTo(new Double(less)));
System.out.println("Test for compareTo passed (isNaN="+anInt.isNaN()+")");
}
}
public void test_values6(){
System.out.println("\nTests for (9,2):");
for (int i=0;i<5;i++){
double value=0;
double d_value=0;
double less=-0.1;
double more=0.1;
switch (i) {
case 1:value=Double.MIN_VALUE;
d_value=0;
break;
case 2:value=-Double.MIN_VALUE;
d_value=0;
break;
case 3:value=9999999.99;
d_value=value;
break;
case 4:value=-9999999.99;
d_value=value;
break;
}
aDoubleIntInt.setValue(value);
System.out.println("value set to "+value);
System.out.println("less set to "+less);
System.out.println("more set to "+more);
if (Integer.MIN_VALUE<value && value<Integer.MAX_VALUE) {
assertEquals(new Double(d_value).intValue(),aDoubleIntInt.getInt());
System.out.println("Test for getInt passed");
}else{
System.out.println("Test for getInt skipped");
}
if (!aDoubleIntInt.isNaN()) assertEquals(new Double(d_value),new Double(aDoubleIntInt.getDouble()));
System.out.println("Test for getDouble passed (isNaN="+anInt.isNaN()+")");
if (Long.MIN_VALUE<value && value<Long.MAX_VALUE) {
assertEquals(new Double(d_value).longValue(),aDoubleIntInt.getLong());
System.out.println("Test for getLong passed");
}else{
System.out.println("Test for getLong skipped");
}
if (!aDoubleIntInt.isNaN()) assertEquals(DecimalFactory.getDecimal(value,9,2),aDoubleIntInt.getDecimal());
System.out.println("Test for getDecimal passed (isNaN="+anInt.isNaN()+")");
assertNotSame(DecimalFactory.getDecimal(value),aDoubleIntInt.getDecimal());
if (!aDoubleIntInt.isNaN()&&!(value==9999999.99)) assertEquals(-1,aDoubleIntInt.compareTo(DecimalFactory.getDecimal(more)));
if (!aDoubleIntInt.isNaN()&&!(value==9999999.99)) assertEquals(-1,aDoubleIntInt.compareTo(new Double(more)));
if (!(aDoubleIntInt.isNaN() || aDoubleIntInt.getDouble()==0)) assertEquals(0,aDoubleIntInt.compareTo(DecimalFactory.getDecimal(value)));
if (!(aDoubleIntInt.isNaN() || aDoubleIntInt.getDouble()==0)) assertEquals(0,aDoubleIntInt.compareTo(new Double(value)));
if (!aDoubleIntInt.isNaN()&&!(value==-9999999.99)) assertEquals(1,aDoubleIntInt.compareTo(DecimalFactory.getDecimal(less)));
if (!aDoubleIntInt.isNaN()&&!(value==-9999999.99)) assertEquals(1,aDoubleIntInt.compareTo(new Double(less)));
System.out.println("Test for compareTo passed (isNaN="+anInt.isNaN()+")");
}
}
public void test_values7(){
System.out.println("\nTests for (6,1) from Decimal:");
for (int i=0;i<4;i++){
switch (i) {
case 0:aDoubleIntInt=DecimalFactory.getDecimal(0,9,2);
break;
case 1:aDoubleIntInt=DecimalFactory.getDecimal(0,9,0);
break;
case 2:aDoubleIntInt=DecimalFactory.getDecimal(0.1,9,2);
break;
case 3:aDoubleIntInt=DecimalFactory.getDecimal(111.1,4,1);
break;
}
aDecimalIntInt=DecimalFactory.getDecimal(aDoubleIntInt,6,1);
System.out.println("Oryginal decimal:"+aDoubleIntInt.toString());
System.out.println("My decimal:"+aDecimalIntInt.toString());
assertEquals(aDoubleIntInt.getInt(),aDecimalIntInt.getInt());
System.out.println("Test for getInt passed");
assertEquals(new Double(aDoubleIntInt.getDouble()),new Double(aDecimalIntInt.getDouble()));
System.out.println("Test for getDouble passed (isNaN="+anInt.isNaN()+")");
assertEquals(aDoubleIntInt.getLong(),aDecimalIntInt.getLong());
System.out.println("Test for getLong passed");
assertEquals(DecimalFactory.getDecimal(aDoubleIntInt,6,1),aDecimalIntInt.getDecimal());
System.out.println("Test for getDecimal passed (isNaN="+anInt.isNaN()+")");
assertNotSame(DecimalFactory.getDecimal(aDoubleIntInt,6,1),aDecimalIntInt.getDecimal());
assertEquals(-1,aDecimalIntInt.compareTo(DecimalFactory.getDecimal(aDoubleIntInt.getDouble()+0.2,6,1)));
assertEquals(-1,aDecimalIntInt.compareTo(new Double(aDoubleIntInt.getDouble()+0.2)));
assertEquals(0,aDecimalIntInt.compareTo(DecimalFactory.getDecimal(aDoubleIntInt.getDouble(),6,1)));
assertEquals(0,aDecimalIntInt.compareTo(new Double(aDoubleIntInt.getDouble())));
assertEquals(1,aDecimalIntInt.compareTo(DecimalFactory.getDecimal(aDoubleIntInt.getDouble()-0.1,6,1)));
assertEquals(1,aDecimalIntInt.compareTo(new Double(aDoubleIntInt.getDouble()-0.1)));
System.out.println("Test for compareTo passed (isNaN="+anInt.isNaN()+")");
}
}
public void test_values8(){
System.out.println("\nTests for HugeDecimal:");
for (int i=0;i<1;i++){
double value=0;
switch (i) {
case 0:value=0;
break;
case 1:aDoubleIntInt=DecimalFactory.getDecimal(0,9,0);
break;
case 2:aDoubleIntInt=DecimalFactory.getDecimal(0.1,9,2);
break;
case 3:aDoubleIntInt=DecimalFactory.getDecimal(111.1,4,1);
break;
}
anIntInt.setValue(value);
System.out.println("value="+value);
System.out.println("decimal:"+anIntInt.toString());
assertEquals(new Double(value).intValue(),anIntInt.getInt());
System.out.println("Test for getInt passed");
assertEquals(new Double(aDoubleIntInt.getDouble()),new Double(anIntInt.getDouble()));
System.out.println("Test for getDouble passed (isNaN="+anInt.isNaN()+")");
assertEquals(aDoubleIntInt.getLong(),anIntInt.getLong());
System.out.println("Test for getLong passed");
assertEquals(DecimalFactory.getDecimal(aDoubleIntInt,6,1),anIntInt.getDecimal());
System.out.println("Test for getDecimal passed (isNaN="+anInt.isNaN()+")");
assertNotSame(DecimalFactory.getDecimal(aDoubleIntInt,6,1),anIntInt.getDecimal());
assertEquals(-1,anIntInt.compareTo(DecimalFactory.getDecimal(aDoubleIntInt.getDouble()+0.2,6,1)));
assertEquals(-1,anIntInt.compareTo(new Double(aDoubleIntInt.getDouble()+0.2)));
assertEquals(0,anIntInt.compareTo(DecimalFactory.getDecimal(aDoubleIntInt.getDouble(),6,1)));
assertEquals(0,anIntInt.compareTo(new Double(aDoubleIntInt.getDouble())));
assertEquals(1,anIntInt.compareTo(DecimalFactory.getDecimal(aDoubleIntInt.getDouble()-0.1,6,1)));
assertEquals(1,anIntInt.compareTo(new Double(aDoubleIntInt.getDouble()-0.1)));
System.out.println("Test for compareTo passed (isNaN="+anInt.isNaN()+")");
}
}
public void test_maths_add(){
aDouble=DecimalFactory.getDecimal(0,6,2);
anInt=DecimalFactory.getDecimal(123,6,3);
aDouble.add(anInt);
assertEquals(new Double(123),new Double(aDouble.getDouble()));
double value=(long)Integer.MIN_VALUE-100;
aDouble=DecimalFactory.getDecimal(0,6,2);
aLong=DecimalFactory.getDecimal(value,20,2);
aLong.add(aDouble);
assertEquals(new Double(value),new Double(aLong.getDouble()));
}
public void test_maths_div(){
aDouble=DecimalFactory.getDecimal(-0.1,6,2);
aDouble.abs();
assertEquals(new Double(0.1),new Double(aDouble.getDouble()));
aDouble.abs();
assertEquals(new Double(0.1),new Double(aDouble.getDouble()));
anInt=DecimalFactory.getDecimal(2,6,3);
aDouble.div(anInt);
assertEquals(new Double(0.05),new Double(aDouble.getDouble()));
aLong=DecimalFactory.getDecimal((long)Integer.MAX_VALUE+10);
aDouble.div(aLong);
assertEquals(new Double(0),new Double(aDouble.getDouble()));
aDouble=DecimalFactory.getDecimal(1,6,2);
aLong.neg();
aDouble.div(aLong);
assertEquals(new Double(0),new Double(aDouble.getDouble()));
}
public void test_maths_mod(){
aDouble=DecimalFactory.getDecimal(10,6,2);
anInt=DecimalFactory.getDecimal(3,6,3);
aDouble.mod(anInt);
assertEquals(new Double(1),new Double(aDouble.getDouble()));
aDouble=DecimalFactory.getDecimal(10,6,2);
anInt=DecimalFactory.getDecimal(3);
aDouble.mod(anInt);
assertEquals(new Double(1),new Double(aDouble.getDouble()));
aDouble=DecimalFactory.getDecimal(10);
anInt=DecimalFactory.getDecimal(3,6,2);
aDouble.mod(anInt);
assertEquals(new Double(1),new Double(aDouble.getDouble()));
}
public void test_maths_mul(){
System.out.println("\nTests for multipling:");
aDouble=DecimalFactory.getDecimal(0.1,6,2);
anInt=DecimalFactory.getDecimal(3,6,3);
aDouble.mul(anInt);
assertEquals(new Double(0.3),new Double(aDouble.getDouble()));
aDouble.neg();
assertEquals(new Double(-0.3),new Double(aDouble.getDouble()));
aDouble.mul(DecimalFactory.getDecimal(0));
assertEquals(new Double(0),new Double(aDouble.getDouble()));
}
public void test_maths_sub(){
aDouble=DecimalFactory.getDecimal(0,6,2);
anInt=DecimalFactory.getDecimal(123,6,3);
aDouble.sub(anInt);
assertEquals(new Double(-123),new Double(aDouble.getDouble()));
aLong=DecimalFactory.getDecimal((long)Integer.MAX_VALUE+100);
aLong.sub(anInt);
assertEquals(new Double(Integer.MAX_VALUE-23),new Double(aLong.getDouble()));
aDouble=DecimalFactory.getDecimal(0,6,2);
anInt=DecimalFactory.getDecimal(0,25,0);
aDouble.sub(anInt);
assertEquals(new Double(0),new Double(aDouble.getDouble()));
}
public void test_fromString(){
aDouble.fromString("123.45",null);
aDouble.setValue(123.45);
assertEquals(new Double(123),new Double(aDouble.getDouble()));
aDouble=DecimalFactory.getDecimal(10,5);
aDouble.fromString(".12345",null);
assertEquals(new Double(0.12345),new Double(aDouble.getDouble()));
aDouble.fromString("12345",null);
assertEquals(new Double(12345),new Double(aDouble.getDouble()));
}
public void test_s_ds(){
System.out.println("\nTests for serialization and deserilization:");
aDouble=DecimalFactory.getDecimal(0.2,6,2);
anInt=DecimalFactory.getDecimal(123,6,3);
aLong=DecimalFactory.getDecimal((long)Integer.MAX_VALUE+10,20,2);
Decimal d=DecimalFactory.getDecimal(aDouble.getPrecision(), aDouble.getScale());
Decimal i=DecimalFactory.getDecimal(anInt.getPrecision(), anInt.getScale());
Decimal l=DecimalFactory.getDecimal(aLong.getPrecision(), aLong.getScale());
ByteBuffer bb=ByteBuffer.allocate(1000);
aDouble.serialize(bb);
anInt.serialize(bb);
aLong.serialize(bb);
bb.rewind();
d.deserialize(bb);
System.out.println("Oryginal:"+aDouble.toString()+",copy:"+d.toString());
i.deserialize(bb);
System.out.println("Oryginal:"+anInt.toString()+",copy:"+i.toString());
l.deserialize(bb);
System.out.println("Oryginal:"+aLong.toString()+",copy:"+l.toString());
assertEquals(aDouble,d);
assertEquals(anInt,i);
assertEquals(aLong,l);
}
protected void tearDown() throws Exception {
super.tearDown();
}
}
|
/*
* $Id: IpAccessHandler.java,v 1.9 2011-06-20 07:03:30 tlipkis Exp $
*/
// $Id: IpAccessHandler.java,v 1.9 2011-06-20 07:03:30 tlipkis Exp $
package org.lockss.jetty;
import java.io.*;
import java.util.*;
import org.mortbay.http.*;
import org.mortbay.http.handler.*;
import org.lockss.util.*;
/** Handler that disallows access from IP addresses not allowed by an
* IpFilter */
public class IpAccessHandler extends AbstractHttpHandler {
// A single handler instance may run concurrently in multiple threads, so
// there must not be any per-request local state.
private static Logger log = Logger.getLogger("IpAccess");
private static String LOCAL_IP_FILTERS = "127.0.0.0/8";
// private static String LOCAL_IP_FILTERS = "127.0.0.0/8;::1";
private IpFilter filter = new IpFilter();
private String serverName;
private boolean allowLocal = false;
private IpFilter localFilter;
private boolean logForbidden;
private String _403Msg;
public IpAccessHandler(String serverName) {
this.serverName = serverName;
}
public void setFilter(IpFilter filter) {
this.filter = filter;
}
public void setLogForbidden(boolean logForbidden) {
this.logForbidden = logForbidden;
}
protected boolean isLogForbidden() {
return logForbidden;
}
public void setAllowLocal(boolean allowLocal) {
if (localFilter == null) {
IpFilter filt = new IpFilter();
try {
filt.setFilters(LOCAL_IP_FILTERS, null);
} catch (IpFilter.MalformedException e) {
log.error("Failed to allow loopback addresses" , e);
}
localFilter = filt; // set atomically
// tk - add local interfaces
}
this.allowLocal = allowLocal;
}
public void set403Msg(String text) {
_403Msg = text;
}
public boolean isIpAuthorized(String ip) throws IpFilter.MalformedException {
return (filter.isIpAllowed(ip) ||
(allowLocal && localFilter.isIpAllowed(ip)));
}
/**
* Handles the incoming request
*
* @param pathInContext
* @param pathParams
* @param request The incoming HTTP-request
* @param response The outgoing HTTP-response
*/
public void handle(String pathInContext,
String pathParams,
HttpRequest request,
HttpResponse response)
throws HttpException, IOException {
try {
String ip = request.getRemoteAddr();
boolean authorized = isIpAuthorized(ip);
if (log.isDebug3()) log.debug3("Access to " + serverName + " from " + ip);
if (!authorized) {
// The IP is NOT allowed
if (logForbidden) {
log.info("Access to " + serverName + " forbidden from " + ip);
}
if (_403Msg != null) {
response.sendError(HttpResponse.__403_Forbidden,
StringUtil.replaceString(_403Msg, "%IP%", ip));
} else {
response.sendError(HttpResponse.__403_Forbidden);
}
request.setHandled(true);
return;
} else {
// The IP is allowed
return;
}
} catch (Exception e) {
log.warning("Error checking IP", e);
response.sendError(HttpResponse.__500_Internal_Server_Error);
request.setHandled(true);
}
}
}
|
/*
* $Id: PdfBoxPage.java,v 1.6 2013-04-29 20:12:28 thib_gc Exp $
*/
package org.lockss.pdf.pdfbox;
import java.io.*;
import java.util.*;
import org.apache.pdfbox.cos.*;
import org.apache.pdfbox.pdmodel.*;
import org.apache.pdfbox.pdmodel.graphics.xobject.*;
import org.lockss.pdf.*;
import org.lockss.util.Logger;
/**
* <p>
* A {@link PdfPage} implementation based on PDFBox 1.6.0.
* </p>
* <p>
* This class acts as an adapter for the {@link PDPage} class.
* </p>
* @author Thib Guicherd-Callin
* @since 1.56
* @see PdfBoxDocumentFactory
*/
public class PdfBoxPage implements PdfPage {
/**
* <p>
* Logger for use by this class.
* </p>
* @since 1.56
*/
private static final Logger logger = Logger.getLogger(PdfBoxPage.class);
/**
* <p>
* Returns an XObject from the given resources, as a {@link PDXObject}
* instance.
* </p>
*
* @param pdResources
* A {@link PDResources} instance.
* @param name
* The name of the desired XObject.
* @return The requested XObject, or <code>null</code> if not found.
* @throws PdfException
* If PDF processing fails.
* @since 1.61
*/
protected static PDXObject getPDXObjectByName(PDResources pdResources,
String name) throws PdfException {
/*
* IMPLEMENTATION NOTE
*
* This map contains objects of type PDXObject (PDFBox 1.6.0:
* see PDResources lines 157 and 160), which are null, or of
* type either PDXObjectForm (see PDXObject line 162) or PDJpeg
* (line 140) or PDCcitt (line 144) or PDPixelMap (line 153).
* The latter three have a common supertype, PDXObjectImage.
*/
return (PDXObject)(pdResources.getXObjects().get(name));
}
/**
* <p>
* Determines if the given {@link PDXObject} instance is a byte
* stream (as opposed to a token stream).
* </p>
* @param xObject A {@link PDXObject} instance.
* @return <code>true</code> if and only if the argument is a byte
* stream.
* @since 1.56.3
* @see #isTokenStream(PDXObject)
*/
private static boolean isByteStream(PDXObject xObject) {
return !isTokenStream(xObject);
}
/**
* <p>
* Determines if the given {@link PDXObject} instance is a token
* stream (as opposed to a byte stream).
* </p>
* @param xObject A {@link PDXObject} instance.
* @return <code>true</code> if and only if the argument is a token
* stream.
* @since 1.56.3
*/
private static boolean isTokenStream(PDXObject xObject) {
/*
* IMPLEMENTATION NOTE
*
* PDXObject is an abstract class whose subtypes all represent
* image XObjects (PDJpeg, PDCcitt or PDPixelMap) i.e. a byte
* stream, except one, PDXObjectForm, which represents a form
* XObject i.e. a token stream.
*/
return xObject instanceof PDXObjectForm;
}
/**
* <p>
* The parent {@link PdfBoxDocument} instance.
* </p>
* @since 1.56
*/
protected final PdfBoxDocument pdfBoxDocument;
/**
* <p>
* The {@link PDPage) instance this instance represents.
* </p>
* @since 1.56
*/
protected final PDPage pdPage;
/**
* <p>
* This constructor is accessible to classes in this package and
* subclasses.
* </p>
* @param pdfBoxDocument The parent {@link PdfBoxDocument} instance.
* @param pdPage The {@link PDPage} instance underpinning this PDF
* page.
* @since 1.56
*/
protected PdfBoxPage(PdfBoxDocument pdfBoxDocument,
PDPage pdPage) {
this.pdfBoxDocument = pdfBoxDocument;
this.pdPage = pdPage;
}
@Override
public List<InputStream> getAllByteStreams() throws PdfException {
List<InputStream> ret = new ArrayList<InputStream>();
PdfTokenStream pageTokenStream = getPageTokenStream();
recursivelyFindByteStreams(pageTokenStream, pdPage.getResources(), ret);
return ret;
}
@Override
public List<PdfTokenStream> getAllTokenStreams() throws PdfException {
List<PdfTokenStream> ret = new ArrayList<PdfTokenStream>();
PdfTokenStream pageTokenStream = getPageTokenStream();
ret.add(pageTokenStream);
recursivelyFindTokenStreams(pageTokenStream, pdPage.getResources(), ret);
return ret;
}
@Override
public List<PdfToken> getAnnotations() {
/*
* IMPLEMENTATION NOTE
*
* Annotations are just dictionaries, but because there are many
* types, the PDFBox API defines a vast hierarchy of objects to
* represent them. At this time, this is way too much detail for
* this API, because only one type of annotation has a foreseeable
* use case (the Link type). So for now, we are only representing
* annotations as the dictionaries they are by circumventing the
* PDAnnotation factory call in getAnnotations() (PDFBox 1.6.0:
* PDPage line 780).
*/
COSDictionary pageDictionary = pdPage.getCOSDictionary();
COSArray annots = (COSArray)pageDictionary.getDictionaryObject(COSName.ANNOTS);
if (annots == null) {
return new ArrayList<PdfToken>();
}
return PdfBoxTokens.getArray(annots);
}
@Override
public PdfDocument getDocument() {
return pdfBoxDocument;
}
@Override
public PdfTokenStream getPageTokenStream() throws PdfException {
try {
return new PdfBoxPageTokenStream(this, pdPage.getContents());
}
catch (IOException ioe) {
throw new PdfException("Failed to get the page content stream", ioe);
}
}
@Override
public PdfTokenFactory getTokenFactory() throws PdfException {
return getDocument().getTokenFactory();
}
@Override
public void setAnnotations(List<PdfToken> annotations) {
pdPage.getCOSDictionary().setItem(COSName.ANNOTS, PdfBoxTokens.asCOSArray(annotations));
}
/**
* <p>
* Traverses the given token stream (and associated resources object), adding
* any embedded image data to the given list, and recursively traversing any
* referenced XObject streams.
* </p>
*
* @param pdfTokenStream
* A token stream.
* @param pdResources
* The token stream's resources object,
* @param ret
* A list into which byte streams are appended.
* @throws PdfException
* If PDF processing fails.
* @since 1.61
*/
private void recursivelyFindByteStreams(PdfTokenStream pdfTokenStream,
final PDResources pdResources,
final List<InputStream> ret)
throws PdfException {
PdfTokenStreamWorker worker = new PdfTokenStreamWorker() {
@Override public void operatorCallback() throws PdfException {
// 'ID' and 'BI'
if (isBeginImageData() || isBeginImageObject()) {
ret.add(new ByteArrayInputStream(PdfBoxTokens.asPDFOperator(getOperator()).getImageData()));
}
else if (isInvokeXObject()) {
PdfToken operand = getTokens().get(getIndex() - 1);
if (operand.isName()) {
PDXObject xObject = getPDXObjectByName(pdResources, operand.getName());
if (isByteStream(xObject)) {
try {
ret.add(xObject.getCOSStream().getUnfilteredStream());
}
catch (IOException ioe) {
logger.debug2("recursivelyFindByteStreams: Error retrieving a byte stream", ioe);
}
}
else {
PDXObjectForm pdxObjectForm = (PDXObjectForm)xObject;
PdfBoxXObjectTokenStream referencedTokenStream = new PdfBoxXObjectTokenStream(PdfBoxPage.this, pdxObjectForm);
recursivelyFindByteStreams(referencedTokenStream,
pdxObjectForm.getResources(),
ret);
}
}
else {
logger.debug2("getAllByteStreams: invalid input");
}
}
}
};
worker.process(pdfTokenStream);
}
/**
* <p>
* Traverses the given token stream (and associated resources object), adding
* any embedded XObject streams to the given list, and recursively traversing
* them. Note that the given stream itself is not appended to the list.
* </p>
*
* @param pdfTokenStream
* A token stream.
* @param pdResources
* The token stream's resources object,
* @param ret
* A list into which byte streams are appended.
* @throws PdfException
* If PDF processing fails.
* @since 1.61
*/
private void recursivelyFindTokenStreams(PdfTokenStream pdfTokenStream,
final PDResources pdResources,
final List<PdfTokenStream> ret)
throws PdfException {
PdfTokenStreamWorker worker = new PdfTokenStreamWorker() {
@Override public void operatorCallback() throws PdfException {
if (isInvokeXObject()) {
PdfToken operand = getTokens().get(getIndex() - 1);
if (operand.isName()) {
PDXObject xObject = getPDXObjectByName(pdResources, operand.getName());
if (isTokenStream(xObject)) {
PDXObjectForm pdxObjectForm = (PDXObjectForm)xObject;
PdfBoxXObjectTokenStream referencedTokenStream = new PdfBoxXObjectTokenStream(PdfBoxPage.this, pdxObjectForm);
ret.add(referencedTokenStream);
recursivelyFindTokenStreams(referencedTokenStream,
pdxObjectForm.getResources(),
ret);
}
}
else {
logger.debug2("recursivelyFindTokenStreams: invalid input");
}
}
}
};
worker.process(pdfTokenStream);
}
}
|
/*
* $Id: TreeWalkHandler.java,v 1.17 2003-04-17 02:13:25 aalto Exp $
*/
package org.lockss.state;
import java.util.*;
import org.lockss.util.*;
import org.lockss.plugin.*;
import org.lockss.crawler.CrawlManager;
import org.lockss.poller.PollSpec;
import org.lockss.daemon.Configuration;
import org.lockss.daemon.RangeCachedUrlSetSpec;
import org.lockss.app.LockssDaemon;
import org.lockss.daemon.ActivityRegulator;
/**
* The treewalk thread handler in the NodeManager. This starts a thread which
* executes treewalks on a regular basis.
*/
public class TreeWalkHandler {
public static final String TREEWALK_PREFIX =
Configuration.PREFIX + "treewalk.";
/**
* Configuration parameter name for interval, in ms, between treewalks.
*/
public static final String PARAM_TREEWALK_INTERVAL =
TREEWALK_PREFIX + "interval";
static final long DEFAULT_TREEWALK_INTERVAL = Constants.HOUR;
static final double MAX_DEVIATION = 0.1;
NodeManagerImpl manager;
private static LockssDaemon theDaemon;
private static CrawlManager theCrawlManager;
private static ActivityRegulator theRegulator;
private ArchivalUnit theAu;
private Logger logger = Logger.getLogger("TreeWalkHandler");
TreeWalkThread treeWalkThread;
long treeWalkInterval;
long topPollInterval;
long treeWalkTestDuration;
boolean treeWalkAborted;
boolean forceTreeWalk = false;
long treeWalkEstimate = -1;
Configuration.Callback configCallback;
TreeWalkHandler(NodeManagerImpl manager, LockssDaemon theDaemon) {
this.manager = manager;
this.theCrawlManager = theDaemon.getCrawlManager();
this.theRegulator = theDaemon.getActivityRegulator();
this.theDaemon = theDaemon;
theAu = manager.managedAu;
configCallback = new Configuration.Callback() {
public void configurationChanged(Configuration newConfig,
Configuration oldConfig,
Set changedKeys) {
setConfig(newConfig, oldConfig);
}
};
Configuration.registerConfigurationCallback(configCallback);
}
private void setConfig(Configuration config, Configuration oldConfig) {
treeWalkInterval = config.getTimeInterval(
PARAM_TREEWALK_INTERVAL, DEFAULT_TREEWALK_INTERVAL);
logger.debug3("treeWalkInterval reset to "+treeWalkInterval);
}
/* old version
void doTreeWalk() {
logger.debug("Attempting tree walk: " + theAu.getName());
NodeState topNode = manager.getNodeState(theAu.getAUCachedUrlSet());
if (topNode==null) {
logger.error("No NodeState found for AU.");
} else {
Iterator activePolls = topNode.getActivePolls();
// only continue if no top level poll scheduled or running
if (!activePolls.hasNext()) {
// check with crawl manager
if (!theCrawlManager.isCrawlingAU(theAu, null, null)) {
// query the AU if a top level poll should be started
if (theAu.shouldCallTopLevelPoll(manager.getAuState())) {
manager.callTopLevelPoll();
logger.debug("Requested top level poll. Aborting...");
}
else {
// do the actual treewalk
logger.debug("Tree walk started: " + theAu.getName());
long startTime = TimeBase.nowMs();
nodeTreeWalk();
long elapsedTime = TimeBase.msSince(startTime);
updateEstimate(elapsedTime);
}
}
else {
logger.debug("Crawl manager active. Aborting...");
}
}
else {
logger.debug("Top level poll active. Aborting...");
}
}
//alert the AuState (it writes through)
manager.getAuState().setLastTreeWalkTime();
logger.debug("Tree walk finished.");
}
*/
/**
* The full treewalk only proceeds if no new content crawls or top level polls
* are needed on the content. As part of checking whether it should execute,
* it triggers these actions by the CrawlManager and the NodeManager before
* aborting its treewalk attempt.
*/
void doTreeWalk() {
logger.debug("Attempting tree walk: " + theAu.getName());
//get expiration time
long expiration = treeWalkInterval;
if (getAverageTreeWalkDuration() > 0) {
expiration = 2 * getAverageTreeWalkDuration();
}
// check with regulator to see if treewalk can proceed
if (theRegulator.startAuActivity(ActivityRegulator.TREEWALK, theAu,
expiration)) {
try {
// check with crawl manager
if (theAu.shouldCrawlForNewContent(manager.getAuState())) {
theRegulator.auActivityFinished(ActivityRegulator.TREEWALK, theAu);
treeWalkAborted = true;
theCrawlManager.startNewContentCrawl(theAu, null, null);
logger.debug("Requested new content crawl. Aborting...");
}
else if (theAu.shouldCallTopLevelPoll(manager.getAuState())) {
// query the AU if a top level poll should be started
theRegulator.auActivityFinished(ActivityRegulator.TREEWALK, theAu);
treeWalkAborted = true;
manager.callTopLevelPoll();
logger.debug("Requested top level poll. Aborting...");
}
else {
// do the actual treewalk
logger.debug("Tree walk started: " + theAu.getName());
long startTime = TimeBase.nowMs();
nodeTreeWalk();
long elapsedTime = TimeBase.msSince(startTime);
updateEstimate(elapsedTime);
}
}
finally {
if (!treeWalkAborted) {
theRegulator.auActivityFinished(ActivityRegulator.TREEWALK, theAu);
} else {
treeWalkAborted = false;
}
}
}
//alert the AuState (it writes through)
manager.getAuState().setLastTreeWalkTime();
logger.debug("Tree walk finished.");
}
private void nodeTreeWalk() {
CachedUrlSet cus = theAu.getAUCachedUrlSet();
recurseTreeWalk(cus);
}
/**
* Recursive function which checks the state of a given CUS, then calls
* itself on the CUS's children. It aborts without recursing if an action
* was taken on the CUS itself.
* @param cus the {@link CachedUrlSet} to walk
*/
void recurseTreeWalk(CachedUrlSet cus) {
if (treeWalkAborted) {
// treewalk has been terminated
return;
}
// get the node state for the cus
logger.debug3("Recursing treewalk on cus: "+cus.getUrl());
NodeState state = manager.getNodeState(cus);
// walk the node
boolean pContinue = checkNodeState(state);
if (!pContinue) {
// this node is busy, so abort without walking its children
return;
}
Iterator children = cus.flatSetIterator();
while (children.hasNext()) {
CachedUrlSetNode node = (CachedUrlSetNode)children.next();
if (node.getType()==CachedUrlSetNode.TYPE_CACHED_URL_SET) {
// recurse on the child cus
//XXX recursion should be aware of total data size, and avoid
// stack overflow
recurseTreeWalk((CachedUrlSet)node);
} else if (node.getType()==CachedUrlSetNode.TYPE_CACHED_URL) {
// open a new state for the leaf and walk
state = manager.getNodeState(
theAu.makeCachedUrlSet(new RangeCachedUrlSetSpec(node.getUrl())));
if (!checkNodeState(state)) {
//XXX abort without any further walking
return;
}
}
}
}
/**
* Checks the state of a specific {@link NodeState}. Returns true if no
* state was detected (or action taken) which would interfere with continuing
* the treewalk below this node.
* @param node the {@link NodeState} to check
* @return true if treewalk can continue below
*/
boolean checkNodeState(NodeState node) {
// at each node, check for recrawl needed
if (node.getCachedUrlSet().hasContent()) {
// if (theCrawlManager.shouldRecrawl(managerAu, node)) {
// then CrawlManager.scheduleBackgroundCrawl()
// return false;
}
// check recent histories to see if something needs fixing
PollHistory lastHistory = node.getLastPollHistory();
if (lastHistory != null) {
// give the last history to the manager to check for consistency
if (manager.checkLastHistory(lastHistory, node, true)) {
logger.debug3("Calling poll on node '"+
node.getCachedUrlSet().getUrl()+"'");
// free treewalk state
theRegulator.auActivityFinished(ActivityRegulator.TREEWALK, theAu);
// take appropriate action
manager.checkLastHistory(lastHistory, node, false);
//XXX abort treewalk
treeWalkAborted = true;
return false;
}
}
return true;
}
/**
* The amount of time, in ms, before the next treewalk should start.
* @return time in ms
*/
long timeUntilTreeWalkStart() {
// if treewalk is forced
if (forceTreeWalk) {
logger.debug("Forcing treewalk start-in time of -1.");
forceTreeWalk = false;
return -1;
}
long lastTreeWalkTime = manager.getAuState().getLastTreeWalkTime();
long timeSinceLastTW = TimeBase.msSince(lastTreeWalkTime);
logger.debug3(timeSinceLastTW+" since last treewalk");
logger.debug("Treewalks should happen every "+treeWalkInterval);
return treeWalkInterval - timeSinceLastTW;
}
/**
* Ends the treewalk process.
*/
public void end() {
logger.debug3("TreeWalkHandler terminated.");
if (treeWalkThread!=null) {
treeWalkThread.end();
}
Configuration.unregisterConfigurationCallback(configCallback);
}
/**
* Starts the treewalk process.
*/
public void start() {
logger.debug3("TreeWalkHandler started.");
treeWalkAborted = false;
if (treeWalkThread==null) {
treeWalkThread = new TreeWalkThread();
treeWalkThread.start();
}
}
/**
* Used for testing. Starts a treewalk if one isn't already running.
*/
void forceTreeWalk() {
boolean threadWasNull = false;
if (treeWalkThread==null) {
treeWalkThread = new TreeWalkThread();
threadWasNull = true;
}
if (!treeWalkThread.doingTreeWalk) {
forceTreeWalk = true;
if (threadWasNull) {
treeWalkThread.start();
} else {
// just wake it up
treeWalkThread.deadline.expire();
}
}
}
/**
* The thread which handles the treewalk itself.
*/
class TreeWalkThread extends Thread {
private boolean goOn = true;
boolean doingTreeWalk = false;
boolean randomDelay = true;
Deadline deadline;
private static final long SMALL_SLEEP = Constants.SECOND;
public TreeWalkThread() {
super("TreeWalk: "+theAu.getName());
}
public void run() {
while (goOn) {
long timeToStart = timeUntilTreeWalkStart();
if (timeToStart <= 0) {
if (randomDelay) {
// only random delay the first time, to allow better test communication
deadline = Deadline.inRandomRange(SMALL_SLEEP, 10*SMALL_SLEEP);
logger.debug3("Random sleep for "+deadline.getRemainingTime()+"ms");
try {
deadline.sleep();
} catch (InterruptedException ie) { }
randomDelay = false;
} else if (!theDaemon.isDaemonRunning()) {
// if the daemon isn't up yet, do a short sleep
logger.debug2("Daemon not running yet. Sleeping...");
deadline = Deadline.in(SMALL_SLEEP);
try {
deadline.sleep();
} catch (InterruptedException ie) { }
} else {
doingTreeWalk = true;
doTreeWalk();
doingTreeWalk = false;
}
} else {
long delta = (long) ( (double) MAX_DEVIATION * timeToStart);
logger.debug3("Creating a deadline for " + timeToStart +
" with delta of " + delta);
deadline = Deadline.inRandomRange(timeToStart, timeToStart + delta);
try {
deadline.sleep();
} catch (InterruptedException ie) { }
}
}
}
public void end() {
goOn = false;
if (doingTreeWalk) {
theRegulator.auActivityFinished(ActivityRegulator.TREEWALK, theAu);
}
treeWalkAborted = true;
if (deadline != null) {
deadline.expire();
}
}
}
/*
* Returns the current treewalk average. -1 until a treewalk is run.
* @return the estimate, in ms
*/
long getAverageTreeWalkDuration() {
return treeWalkEstimate;
}
void updateEstimate(long elapsedTime) {
if (treeWalkEstimate==-1) {
treeWalkEstimate = elapsedTime;
} else {
// average with current estimate
treeWalkEstimate = (treeWalkEstimate + elapsedTime) / 2;
}
}
}
|
package org.lvcp.eepperly.expr;
import java.util.ArrayList;
import java.util.List;
public class Arccosine extends Expr {
public Arccosine(List<Expr> arguments) {
super(arguments);
}
public Expr differentiate(){
List <Expr> arccosineList = new ArrayList<>();
arccosineList.add(arguments.get(0));
arccosineList.add(Expr.TWO);
Expr argSquared= new Exponential(arccosineList);
List <Expr> sumList = new ArrayList<>();
sumList.add(Expr.ONE);
sumList.add(Product.unitaryNegation(argSquared));
Expr sum = new Sum(sumList);
List <Expr> toTheMinusOneHalfList = new ArrayList<>();
toTheMinusOneHalfList.add(sum);
toTheMinusOneHalfList.add(new NumConstant(-0.5));
Expr toTheMinusOneHalf = new Exponential(toTheMinusOneHalfList);
List <Expr> prodList = new ArrayList<>();
prodList.add(toTheMinusOneHalf);
prodList.add(arguments.get(0).differentiate());
prodList.add(Expr.MINUS_ONE);
return new Product(prodList);
}
public double evaluate(double value){
return Math.acos(arguments.get(0).evaluate(value));
}
public String toString(){
return ("arcos("+arguments.get(0).toString()+")");
}
}
|
package org.opencms.flex;
import org.opencms.flex.CmsFlexRequestKey.PathsBean;
import org.opencms.loader.I_CmsResourceLoader;
import org.opencms.main.CmsLog;
import org.opencms.util.CmsStringUtil;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import com.google.common.collect.Lists;
/**
* Key used to describe the caching behaviour of a specific resource.<p>
*
* It has a lot of variables that are directly accessed (which isn't good style, I know)
* to avoid method calling overhead (a cache is about speed, isn't it :).<p>
*
* @since 6.0.0
*/
public class CmsFlexCacheKey {
/** Flex cache keyword: always. */
private static final String CACHE_00_ALWAYS = "always";
/** Flex cache keyword: never. */
private static final String CACHE_01_NEVER = "never";
/** Flex cache keyword: uri. */
private static final String CACHE_02_URI = "uri";
/** Flex cache keyword: user. */
private static final String CACHE_03_USER = "user";
/** Flex cache keyword: params. */
private static final String CACHE_04_PARAMS = "params";
/** Flex cache keyword: no-params. */
private static final String CACHE_05_NO_PARAMS = "no-params";
/** Flex cache keyword: timeout. */
private static final String CACHE_06_TIMEOUT = "timeout";
/** Flex cache keyword: session. */
private static final String CACHE_07_SESSION = "session";
/** Flex cache keyword: schemes. */
private static final String CACHE_08_SCHEMES = "schemes";
/** Flex cache keyword: ports. */
private static final String CACHE_09_PORTS = "ports";
/** Flex cache keyword: false. */
private static final String CACHE_10_FALSE = CmsStringUtil.FALSE;
/** Flex cache keyword: parse-error. */
private static final String CACHE_11_PARSE_ERROR = "parse-error";
/** Flex cache keyword: true. */
private static final String CACHE_12_TRUE = CmsStringUtil.TRUE;
/** Flex cache keyword: ip. */
private static final String CACHE_13_IP = "ip";
/** Flex cache keyword: element. */
private static final String CACHE_14_ELEMENT = "element";
/** Flex cache keyword: locale. */
private static final String CACHE_15_LOCALE = "locale";
/** Flex cache keyword: encoding. */
private static final String CACHE_16_ENCODING = "encoding";
/** Flex cache keyword: site. */
private static final String CACHE_17_SITE = "site";
/** Flex cache keyword: attrs. */
private static final String CACHE_18_ATTRS = "attrs";
/** Flex cache keyword: no-attrs. */
private static final String CACHE_19_NO_ATTRS = "no-attrs";
/** Flex cache keyword: device. */
private static final String CACHE_20_DEVICE = "device";
/** Flex cache keyword: container-element. */
private static final String CACHE_21_CONTAINER_ELEMENT = "container-element";
/** The list of keywords of the Flex cache language. */
private static final List<String> CACHE_COMMANDS = Arrays.asList(
new String[] {
CACHE_00_ALWAYS,
CACHE_01_NEVER,
CACHE_02_URI,
CACHE_03_USER,
CACHE_04_PARAMS,
CACHE_05_NO_PARAMS,
CACHE_06_TIMEOUT,
CACHE_07_SESSION,
CACHE_08_SCHEMES,
CACHE_09_PORTS,
CACHE_10_FALSE,
CACHE_11_PARSE_ERROR,
CACHE_12_TRUE,
CACHE_13_IP,
CACHE_14_ELEMENT,
CACHE_15_LOCALE,
CACHE_16_ENCODING,
CACHE_17_SITE,
CACHE_18_ATTRS,
CACHE_19_NO_ATTRS,
CACHE_20_DEVICE,
CACHE_21_CONTAINER_ELEMENT});
/** Marker to identify use of certain String key members (uri, ip etc.). */
private static final String IS_USED = "/ /";
/** The log object for this class. */
private static final Log LOG = CmsLog.getLog(CmsFlexCacheKey.class);
/** Cache key variable: Determines if this resource can be cached alwys, never or under certain conditions. -1 = never, 0=check, 1=always. */
private int m_always;
/** Cache key variable: List of attributes. */
private Set<String> m_attrs;
/** Cache key variable: The current container element. */
private String m_containerElement;
/** Cache key variable: The current device. */
private String m_device;
/** Cache key variable: The requested element. */
private String m_element;
/** Cache key variable: The requested encoding. */
private String m_encoding;
/** Cache key variable: The ip address of the request. */
private String m_ip;
/** Cache key variable: The requested locale. */
private String m_locale;
/** Cache key variable: List of "blocking" attributes. */
private Set<String> m_noattrs;
/** Cache key variable: List of "blocking" parameters. */
private Set<String> m_noparams;
/** Cache key variable: List of parameters. */
private Set<String> m_params;
/** Flag raised in case a key parse error occurred. */
private boolean m_parseError;
/** Cache key variable: The request TCP/IP port. */
private Set<Integer> m_ports;
/** The OpenCms resource that this key is used for. */
private String m_resource;
/** Cache key variable: Distinguishes request schemes (http, https etc.). */
private Set<String> m_schemes;
/** Cache key variable: List of session variables. */
private Set<String> m_session;
/** Cache key variable: The current site root. */
private String m_site;
/** Cache key variable: Timeout of the resource. */
private long m_timeout;
/** Cache key variable: The uri of the original request. */
private String m_uri;
/** Cache key variable: The user id. */
private String m_user;
/** The cache behaviour description for the resource. */
private String m_variation;
/**
* This constructor is used when building a cache key from set of cache directives.<p>
*
* These directives are attached to the properties of the requested resource
* on a property called "cache".
* The value of this poperty that is passed in this constructor as "cacheDirectives"
* is parsed to build the keys data structure.<p>
*
* In case a parsing error occures, the value of this key is set to "cache=never",
* and the hadParseError() flag is set to true.
* This is done to ensure that a valid key is always constructed with the constructor.<p>
*
* @param resourcename the full name of the resource including site root
* @param cacheDirectives the cache directives of the resource (value of the property "cache")
* @param online must be true for an online resource, false for offline resources
*/
public CmsFlexCacheKey(String resourcename, String cacheDirectives, boolean online) {
m_resource = getKeyName(resourcename, online);
m_variation = "never";
m_always = -1;
m_timeout = -1;
if (cacheDirectives != null) {
parseFlexKey(cacheDirectives);
}
if (LOG.isDebugEnabled()) {
LOG.debug(Messages.get().getBundle().key(Messages.LOG_FLEXCACHEKEY_GENERATED_1, toString()));
}
}
/**
* Calculates the cache key name that is used as key in
* the first level of the FlexCache.<p>
*
* @param resourcename the full name of the resource including site root
* @param online must be true for an online resource, false for offline resources
*
* @return the FlexCache key name
*/
public static String getKeyName(String resourcename, boolean online) {
return resourcename.concat(online ? CmsFlexCache.CACHE_ONLINESUFFIX : CmsFlexCache.CACHE_OFFLINESUFFIX);
}
/**
* Returns resource name from given key name.<p>
*
* @param keyName given name of key.
* @return name of resource if key is valid, otherwise ""
*/
public static String getResourceName(String keyName) {
if (keyName.endsWith(CmsFlexCache.CACHE_OFFLINESUFFIX) | keyName.endsWith(CmsFlexCache.CACHE_ONLINESUFFIX)) {
return keyName.split(" ")[0];
} else {
return "";
}
}
/**
* Appends a flex cache key value to the given buffer.<p>
*
* @param str the buffer to append to
* @param key the key to append
* @param value the value to append
*/
private static void appendKeyValue(StringBuffer str, String key, String value) {
str.append(key);
if (value == IS_USED) {
str.append(";");
} else {
str.append("=(");
str.append(value);
str.append(");");
}
}
/**
* Gets the list of root paths for the cache key / request key combination which should be used to determine the set of flex cache buckets for the flex cache entry.<p>
*
* @param key the flex request key
* @return the list of paths which should be used to determine the flex cache buckets
*/
public List<String> getPathsForBuckets(CmsFlexRequestKey key) {
PathsBean pathBean = key.getPaths();
List<String> paths = Lists.newArrayList();
if (m_uri != null) {
paths.add(pathBean.getUri());
paths.add(pathBean.getDetailElement());
}
if (m_element != null) {
paths.add(pathBean.getElement());
}
if (m_site != null) {
paths.add(pathBean.getSite());
}
if (m_containerElement != null) {
paths.add(pathBean.getContainerElement());
}
paths.removeAll(Collections.singletonList(null));
return paths;
}
/**
* This flag is used to indicate that a parse error had
* occurred, which can happen if the cache directives String
* passed to the constructor using the response is
* not build according to the Flex cache language syntax.<p>
*
* @return true if a parse error did occur, false otherwise
*/
public boolean hadParseError() {
return m_parseError;
}
/**
* Compares this key to the other key passed as parameter,
* from comparing the two keys, a variation String is constructed.<p>
*
* This method is the "heart" of the key matching process.<p>
*
* The assumtion is that this key should be the one constructed for the response,
* while the parameter key should have been constructed from the request.<p>
*
* A short example how this works:
* If the cache key is "cache=user" and the request is done from a guest user
* the constructed variation will be "user=(guest)".<p>
*
* @param key the key to match this key with
* @return null if not cachable, or the Variation String if cachable
*/
public String matchRequestKey(CmsFlexRequestKey key) {
StringBuffer str = new StringBuffer(100);
if (m_always < 0) {
if (LOG.isDebugEnabled()) {
LOG.debug(Messages.get().getBundle().key(Messages.LOG_FLEXCACHEKEY_KEYMATCH_CACHE_NEVER_0));
}
return null;
}
if (LOG.isDebugEnabled()) {
LOG.debug(Messages.get().getBundle().key(Messages.LOG_FLEXCACHEKEY_KEYMATCH_CHECK_NO_PARAMS_0));
}
if ((m_noparams != null) && (key.getParams() != null)) {
if ((m_noparams.size() == 0) && (key.getParams().size() > 0)) {
return null;
}
Iterator<String> i = key.getParams().keySet().iterator();
while (i.hasNext()) {
if (m_noparams.contains(i.next())) {
return null;
}
}
}
if (LOG.isDebugEnabled()) {
LOG.debug(Messages.get().getBundle().key(Messages.LOG_FLEXCACHEKEY_KEYMATCH_CHECK_NO_ATTRS_0));
}
if ((m_noattrs != null) && (key.getAttributes() != null)) {
if ((m_noattrs.size() == 0) && (key.getAttributes().size() > 0)) {
return null;
}
Iterator<String> i = key.getAttributes().keySet().iterator();
while (i.hasNext()) {
if (m_noattrs.contains(i.next())) {
return null;
}
}
}
if (m_always > 0) {
if (LOG.isDebugEnabled()) {
LOG.debug(Messages.get().getBundle().key(Messages.LOG_FLEXCACHEKEY_KEYMATCH_CACHE_ALWAYS_0));
}
str.append(CACHE_00_ALWAYS);
return str.toString();
}
if (m_uri != null) {
appendKeyValue(str, CACHE_02_URI, key.getUri());
}
if (m_site != null) {
appendKeyValue(str, CACHE_17_SITE, key.getSite());
}
if (m_element != null) {
appendKeyValue(str, CACHE_14_ELEMENT, key.getElement());
}
if (m_device != null) {
appendKeyValue(str, CACHE_20_DEVICE, key.getDevice());
}
if (m_containerElement != null) {
appendKeyValue(str, CACHE_21_CONTAINER_ELEMENT, key.getContainerElement());
}
if (m_locale != null) {
appendKeyValue(str, CACHE_15_LOCALE, key.getLocale());
}
if (m_encoding != null) {
appendKeyValue(str, CACHE_16_ENCODING, key.getEncoding());
}
if (m_ip != null) {
appendKeyValue(str, CACHE_13_IP, key.getIp());
}
if (m_user != null) {
appendKeyValue(str, CACHE_03_USER, key.getUser());
}
if (m_params != null) {
str.append(CACHE_04_PARAMS);
str.append("=(");
Map<String, String[]> keyParams = key.getParams();
if (keyParams != null) {
if (m_params.size() > 0) {
// match only params listed in cache directives
Iterator<String> i = m_params.iterator();
while (i.hasNext()) {
Object o = i.next();
if (keyParams.containsKey(o)) {
str.append(o);
str.append("=");
// TODO: handle multiple occurrences of the same parameter value
String[] values = keyParams.get(o);
str.append(values[0]);
if (i.hasNext()) {
str.append(",");
}
}
}
} else {
// match all request params
Iterator<Map.Entry<String, String[]>> i = keyParams.entrySet().iterator();
while (i.hasNext()) {
Map.Entry<String, String[]> entry = i.next();
str.append(entry.getKey());
str.append("=");
// TODO: handle multiple occurrences of the same parameter value
String[] values = entry.getValue();
str.append(values[0]);
if (i.hasNext()) {
str.append(",");
}
}
}
}
str.append(");");
}
if (m_attrs != null) {
str.append(CACHE_18_ATTRS);
str.append("=(");
Map<String, Object> keyAttrs = key.getAttributes();
if (keyAttrs != null) {
if (m_attrs.size() > 0) {
// match only attributes listed in cache directives
Iterator<String> i = m_attrs.iterator();
while (i.hasNext()) {
String s = i.next();
if (keyAttrs.containsKey(s)) {
str.append(s);
str.append("=");
Object value = keyAttrs.get(s);
str.append(value);
if (i.hasNext()) {
str.append(",");
}
}
}
} else {
// match all request attributes
Iterator<Map.Entry<String, Object>> i = keyAttrs.entrySet().iterator();
while (i.hasNext()) {
Map.Entry<String, Object> entry = i.next();
str.append(entry.getKey());
str.append("=");
Object value = entry.getValue();
str.append(value);
if (i.hasNext()) {
str.append(",");
}
}
}
}
str.append(");");
}
if (m_session != null) {
StringBuffer buf = new StringBuffer(32);
boolean found = false;
buf.append(CACHE_07_SESSION);
buf.append("=(");
HttpSession keySession = key.getSession();
if (keySession != null) {
// match only session attributes listed in cache directives
Iterator<String> i = m_session.iterator();
while (i.hasNext()) {
String name = i.next();
Object val = keySession.getAttribute(name);
if (val != null) {
found = true;
buf.append(name);
buf.append("=");
buf.append(val);
if (i.hasNext()) {
buf.append(",");
}
}
}
}
if (found) {
buf.append(");");
str.append(buf);
}
}
if (m_schemes != null) {
String s = key.getScheme();
if ((m_schemes.size() > 0) && (!m_schemes.contains(s))) {
return null;
}
appendKeyValue(str, CACHE_08_SCHEMES, s);
}
if (m_ports != null) {
Integer i = key.getPort();
if ((m_ports.size() > 0) && (!m_ports.contains(i))) {
return null;
}
str.append(CACHE_09_PORTS);
str.append("=(");
str.append(i);
str.append(");");
}
if (m_timeout > 0) {
str.append(CACHE_06_TIMEOUT);
str.append("=(");
str.append(m_timeout);
str.append(");");
}
if (str.length() > 0) {
return str.toString();
} else {
return null;
}
}
/**
* @see java.lang.Object#toString()
*
* @return a complete String representation for this key
*/
@Override
public String toString() {
StringBuffer str = new StringBuffer(100);
if (m_always < 0) {
str.append(CACHE_01_NEVER);
if (m_parseError) {
str.append(";");
str.append(CACHE_11_PARSE_ERROR);
}
return str.toString();
}
if (m_noparams != null) {
// add "no-cachable" parameters
str.append(CACHE_05_NO_PARAMS);
if (m_noparams.size() == 0) {
str.append(";");
} else {
str.append("=(");
Iterator<String> i = m_noparams.iterator();
while (i.hasNext()) {
Object o = i.next();
str.append(o);
if (i.hasNext()) {
str.append(",");
}
}
str.append(");");
}
}
if (m_noattrs != null) {
// add "no-cachable" attributes
str.append(CACHE_19_NO_ATTRS);
if (m_noattrs.size() == 0) {
str.append(";");
} else {
str.append("=(");
Iterator<String> i = m_noattrs.iterator();
while (i.hasNext()) {
String s = i.next();
str.append(s);
if (i.hasNext()) {
str.append(",");
}
}
str.append(");");
}
}
if (m_always > 0) {
str.append(CACHE_00_ALWAYS);
if (m_parseError) {
str.append(";");
str.append(CACHE_11_PARSE_ERROR);
}
return str.toString();
}
if (m_uri != null) {
// add uri
appendKeyValue(str, CACHE_02_URI, m_uri);
}
if (m_site != null) {
// add site
appendKeyValue(str, CACHE_17_SITE, m_site);
}
if (m_element != null) {
// add element
appendKeyValue(str, CACHE_14_ELEMENT, m_element);
}
if (m_device != null) {
appendKeyValue(str, CACHE_20_DEVICE, m_device);
}
if (m_containerElement != null) {
appendKeyValue(str, CACHE_21_CONTAINER_ELEMENT, m_containerElement);
}
if (m_locale != null) {
// add locale
appendKeyValue(str, CACHE_15_LOCALE, m_locale);
}
if (m_encoding != null) {
// add encoding
appendKeyValue(str, CACHE_16_ENCODING, m_encoding);
}
if (m_ip != null) {
// add ip
appendKeyValue(str, CACHE_13_IP, m_ip);
}
if (m_user != null) {
// add user
appendKeyValue(str, CACHE_03_USER, m_user);
}
if (m_params != null) {
// add parameters
str.append(CACHE_04_PARAMS);
if (m_params.size() == 0) {
str.append(";");
} else {
str.append("=(");
Iterator<String> i = m_params.iterator();
while (i.hasNext()) {
Object o = i.next();
if (I_CmsResourceLoader.PARAMETER_ELEMENT.equals(o)) {
continue;
}
str.append(o);
if (i.hasNext()) {
str.append(",");
}
}
str.append(");");
}
}
if (m_attrs != null) {
// add attributes
str.append(CACHE_18_ATTRS);
if (m_attrs.size() == 0) {
str.append(";");
} else {
str.append("=(");
Iterator<String> i = m_attrs.iterator();
while (i.hasNext()) {
String s = i.next();
str.append(s);
if (i.hasNext()) {
str.append(",");
}
}
str.append(");");
}
}
if (m_session != null) {
// add session variables
str.append(CACHE_07_SESSION);
str.append("=(");
Iterator<String> i = m_session.iterator();
while (i.hasNext()) {
Object o = i.next();
str.append(o);
if (i.hasNext()) {
str.append(",");
}
}
str.append(");");
}
if (m_timeout >= 0) {
// add timeout
str.append(CACHE_06_TIMEOUT);
str.append("=(");
str.append(m_timeout);
str.append(");");
}
if (m_schemes != null) {
// add schemes
str.append(CACHE_08_SCHEMES);
if (m_schemes.size() == 0) {
str.append(";");
} else {
str.append("=(");
Iterator<String> i = m_schemes.iterator();
while (i.hasNext()) {
str.append(i.next());
if (i.hasNext()) {
str.append(",");
}
}
str.append(");");
}
}
if (m_ports != null) {
// add ports
str.append(CACHE_09_PORTS);
if (m_ports.size() == 0) {
str.append(";");
} else {
str.append("=(");
Iterator<Integer> i = m_ports.iterator();
while (i.hasNext()) {
str.append(i.next());
if (i.hasNext()) {
str.append(",");
}
}
str.append(");");
}
}
if (m_parseError) {
str.append(CACHE_11_PARSE_ERROR);
}
return str.toString();
}
/**
* Returns the resource.<p>
*
* @return the resource
*/
protected String getResource() {
return m_resource;
}
/**
* Returns the timeout.<p>
*
* @return the timeout
*/
protected long getTimeout() {
return m_timeout;
}
/**
* Returns the variation.<p>
*
* @return the variation
*/
protected String getVariation() {
return m_variation;
}
/**
* Sets the variation.<p>
*
* @param variation the variation to set
*/
protected void setVariation(String variation) {
m_variation = variation;
}
/**
* Parse a String in the Flex cache language and construct
* the key data structure from this.<p>
*
* @param key the String to parse (usually read from the file property "cache")
*/
private void parseFlexKey(String key) {
List<String> tokens = CmsStringUtil.splitAsList(key, ';', false);
Iterator<String> i = tokens.iterator();
try {
while (i.hasNext()) {
String t = i.next();
String k = null;
String v = null;
int idx = t.indexOf('=');
if (idx >= 0) {
k = t.substring(0, idx).trim();
if (t.length() > idx) {
v = t.substring(idx + 1).trim();
}
} else {
k = t.trim();
}
m_always = 0;
if (LOG.isDebugEnabled()) {
LOG.debug(Messages.get().getBundle().key(Messages.LOG_FLEXCACHEKEY_PARSE_FLEXKEY_3, t, k, v));
}
switch (CACHE_COMMANDS.indexOf(k)) {
case 0: // always
case 12: // true
m_always = 1;
// continue processing (make sure we find a "never" behind "always")
break;
case 1: // never
case 10: // false
m_always = -1;
// no need for any further processing
return;
case 2: // uri
m_uri = IS_USED; // marks m_uri as being used
break;
case 3: // user
m_user = IS_USED; // marks m_user as being used
break;
case 4: // params
if (v != null) {
m_params = parseValueList(v);
} else {
m_params = Collections.emptySet();
}
if (m_params.contains(I_CmsResourceLoader.PARAMETER_ELEMENT)) {
// workaround for element setting by parameter in OpenCms < 6.0
m_element = IS_USED;
m_params.remove(I_CmsResourceLoader.PARAMETER_ELEMENT);
if (m_params.size() == 0) {
m_params = null;
}
}
break;
case 5: // no-params
if (v != null) {
// no-params are present
m_noparams = parseValueList(v);
} else {
// never cache with parameters
m_noparams = Collections.emptySet();
}
break;
case 6: // timeout
m_timeout = Integer.parseInt(v);
break;
case 7: // session
m_session = parseValueList(v);
if (m_session.size() <= 0) {
// session must have at last one variable set
m_parseError = true;
}
break;
case 8: // schemes
m_schemes = parseValueList(v);
break;
case 9: // ports
Set<String> ports = parseValueList(v);
m_ports = new HashSet<Integer>(ports.size());
for (String p : ports) {
try {
m_ports.add(Integer.valueOf(p));
} catch (NumberFormatException e) {
// ignore this number
}
}
break;
case 11: // previous parse error - ignore
break;
case 13:
m_ip = IS_USED; // marks ip as being used
break;
case 14: // element
m_element = IS_USED;
break;
case 15: // locale
m_locale = IS_USED;
break;
case 16: // encoding
m_encoding = IS_USED;
break;
case 17: // site
m_site = IS_USED;
break;
case 18: // attrs
if (v != null) {
m_attrs = parseValueList(v);
} else {
m_attrs = null;
}
break;
case 19: // no-attrs
if (v != null) {
// no-attrs are present
m_noattrs = parseValueList(v);
} else {
// never cache with attributes
m_noattrs = Collections.emptySet();
}
break;
case 20: // device
m_device = IS_USED; // marks m_device as being used
break;
case 21: // container element
m_containerElement = IS_USED;
break;
default: // unknown directive, throw error
m_parseError = true;
}
}
} catch (Exception e) {
// any Exception here indicates a parsing error
if (LOG.isErrorEnabled()) {
LOG.error(Messages.get().getBundle().key(Messages.LOG_FLEXCACHEKEY_PARSE_ERROR_1, e.toString()), e);
}
m_parseError = true;
}
if (m_parseError) {
// If string is invalid set cache to "never"
m_always = -1;
}
}
/**
* A helper method for the parsing process which parses
* Strings like groups=(a, b, c).<p>
*
* @param value the String to parse
* @return a Map that contains of the parsed values, only the keyset of the Map is needed later
*/
private Set<String> parseValueList(String value) {
if (value.charAt(0) == '(') {
value = value.substring(1);
}
int len = value.length() - 1;
if (value.charAt(len) == ')') {
value = value.substring(0, len);
}
if (value.charAt(len - 1) == ',') {
value = value.substring(0, len - 1);
}
if (LOG.isDebugEnabled()) {
LOG.debug(Messages.get().getBundle().key(Messages.LOG_FLEXCACHEKEY_PARSE_VALUES_1, value));
}
List<String> tokens = CmsStringUtil.splitAsList(value, ',', true);
Set<String> result = new HashSet<String>();
result.addAll(tokens);
return result;
}
}
|
package org.opencraft.server.model;
/**
* Represents the actual level.
* @author Graham Edgecombe
*
*/
public final class Level {
/**
* The level width.
*/
private final int width = 256;
/**
* The level height.
*/
private final int height = 256;
/**
* The level depth.
*/
private final int depth = 64;
/**
* The blocks.
*/
private final byte[][][] blocks = new byte[width][height][depth];
/**
* Creates the level.
*/
public Level() {
for(int i = 0; i < (depth / 2); i++) {
for(int j = 0; j < width; j++) {
for(int k = 0; k < height; k++) {
blocks[j][k][i] = 3;
}
}
}
}
/**
* Gets all of the blocks.
* @return All of the blocks.
*/
public byte[][][] getBlocks() {
return blocks;
}
/**
* Gets the width of the level.
* @return The width of the level.
*/
public int getWidth() {
return width;
}
/**
* Gets the height of the level.
* @return The height of the level.
*/
public int getHeight() {
return height;
}
/**
* Gets the depth of the level.
* @return The depth of the level.
*/
public int getDepth() {
return depth;
}
}
|
package org.pentaho.di.trans;
import java.util.concurrent.TimeUnit;
import org.pentaho.di.core.RowSet;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.trans.step.StepInterface;
/**
* Allows you to "Inject" rows into a step.
*
* @author Matt
*
*/
public class RowProducer
{
private RowSet rowSet;
private StepInterface stepInterface;
public RowProducer(StepInterface stepInterface, RowSet rowSet)
{
this.stepInterface = stepInterface;
this.rowSet = rowSet;
}
/**
* Puts a row into the underlying row set. This will block until the row is successfully added.
*
* @see #putRow(RowMetaInterface, Object[], boolean) putRow(RowMetaInterface, Object[], true)
*/
public void putRow(RowMetaInterface rowMeta, Object[] row)
{
putRow(rowMeta, row, true);
}
/**
* Puts a row on to the underlying row set, optionally blocking until the row can be successfully put.
*
* @return true if the row was successfully added to the rowset and false if this buffer was full. If {@code block} is true this will always return true.
* @see RowSet#putRow(RowMetaInterface, Object[])
*/
public boolean putRow(RowMetaInterface rowMeta, Object[] row, boolean block) {
if (block) {
while (!rowSet.putRowWait(rowMeta, row, Long.MAX_VALUE, TimeUnit.DAYS));
return true;
}
return rowSet.putRow(rowMeta, row);
}
/**
* @see RowSet#putRowWait(RowMetaInterface, Object[], long, TimeUnit)
*/
public boolean putRowWait(RowMetaInterface rowMeta, Object[] rowData, long time, TimeUnit tu)
{
return rowSet.putRowWait(rowMeta, rowData, time, tu);
}
public void finished()
{
rowSet.setDone();
}
/**
* @return Returns the rowSet.
*/
public RowSet getRowSet()
{
return rowSet;
}
/**
* @param rowSet The rowSet to set.
*/
public void setRowSet(RowSet rowSet)
{
this.rowSet = rowSet;
}
/**
* @return Returns the stepInterface.
*/
public StepInterface getStepInterface()
{
return stepInterface;
}
/**
* @param stepInterface The stepInterface to set.
*/
public void setStepInterface(StepInterface stepInterface)
{
this.stepInterface = stepInterface;
}
}
|
package org.broadinstitute.sting.utils;
import com.google.java.contract.Requires;
import net.sf.samtools.SAMRecord;
import org.broadinstitute.sting.gatk.GenomeAnalysisEngine;
import org.broadinstitute.sting.utils.exceptions.UserException;
import java.math.BigDecimal;
import java.util.*;
/**
* MathUtils is a static class (no instantiation allowed!) with some useful math methods.
*
* @author Kiran Garimella
*/
public class MathUtils {
/** Public constants - used for the Lanczos approximation to the factorial function
* (for the calculation of the binomial/multinomial probability in logspace)
* @param LANC_SEQ[] - an array holding the constants which correspond to the product
* of Chebyshev Polynomial coefficients, and points on the Gamma function (for interpolation)
* [see A Precision Approximation of the Gamma Function J. SIAM Numer. Anal. Ser. B, Vol. 1 1964. pp. 86-96]
* @param LANC_G - a value for the Lanczos approximation to the gamma function that works to
* high precision
*/
/** Private constructor. No instantiating this class! */
private MathUtils() {}
@Requires({"d > 0.0"})
public static int fastPositiveRound(double d) {
return (int) (d + 0.5);
}
public static int fastRound(double d) {
if ( d > 0.0 ) {
return fastPositiveRound(d);
} else {
return -1*fastPositiveRound(-1*d);
}
}
public static double sum(Collection<Number> numbers) {
return sum(numbers,false);
}
public static double sum( Collection<Number> numbers, boolean ignoreNan ) {
double sum = 0;
for ( Number n : numbers ) {
if ( ! ignoreNan || ! Double.isNaN(n.doubleValue())) {
sum += n.doubleValue();
}
}
return sum;
}
public static int nonNanSize(Collection<Number> numbers) {
int size = 0;
for ( Number n : numbers) {
size += Double.isNaN(n.doubleValue()) ? 0 : 1;
}
return size;
}
public static double average( Collection<Number> numbers, boolean ignoreNan) {
if ( ignoreNan ) {
return sum(numbers,true)/nonNanSize(numbers);
} else {
return sum(numbers,false)/nonNanSize(numbers);
}
}
public static double variance( Collection<Number> numbers, Number mean, boolean ignoreNan ) {
double mn = mean.doubleValue();
double var = 0;
for ( Number n : numbers ) { var += ( ! ignoreNan || ! Double.isNaN(n.doubleValue())) ? (n.doubleValue()-mn)*(n.doubleValue()-mn) : 0; }
if ( ignoreNan ) { return var/(nonNanSize(numbers)-1); }
return var/(numbers.size()-1);
}
public static double variance(Collection<Number> numbers, Number mean) {
return variance(numbers,mean,false);
}
public static double variance(Collection<Number> numbers, boolean ignoreNan) {
return variance(numbers,average(numbers,ignoreNan),ignoreNan);
}
public static double variance(Collection<Number> numbers) {
return variance(numbers,average(numbers,false),false);
}
public static double sum(double[] values) {
double s = 0.0;
for ( double v : values) s += v;
return s;
}
/**
* Calculates the log10 cumulative sum of an array with log10 probabilities
* @param log10p the array with log10 probabilites
* @param upTo index in the array to calculate the cumsum up to
* @return the log10 of the cumulative sum
*/
public static double log10CumulativeSumLog10(double [] log10p, int upTo) {
return log10sumLog10(log10p, 0, upTo);
}
/**
* Converts a real space array of probabilities into a log10 array
* @param prRealSpace
* @return
*/
public static double[] toLog10(double[] prRealSpace) {
double[] log10s = new double[prRealSpace.length];
for ( int i = 0; i < prRealSpace.length; i++ )
log10s[i] = Math.log10(prRealSpace[i]);
return log10s;
}
public static double log10sumLog10(double[] log10p, int start) {
return log10sumLog10(log10p, start, log10p.length);
}
public static double log10sumLog10(double[] log10p, int start, int finish) {
double sum = 0.0;
double maxValue = Utils.findMaxEntry(log10p);
for ( int i = start; i < finish; i++ ) {
sum += Math.pow(10.0, log10p[i] - maxValue);
}
return Math.log10(sum) + maxValue;
}
public static double sumDoubles(List<Double> values) {
double s = 0.0;
for ( double v : values) s += v;
return s;
}
public static int sumIntegers(List<Integer> values) {
int s = 0;
for ( int v : values) s += v;
return s;
}
public static double sumLog10(double[] log10values) {
return Math.pow(10.0, log10sumLog10(log10values));
// double s = 0.0;
// for ( double v : log10values) s += Math.pow(10.0, v);
// return s;
}
public static double log10sumLog10(double[] log10values) {
return log10sumLog10(log10values, 0);
}
public static boolean wellFormedDouble(double val) {
return ! Double.isInfinite(val) && ! Double.isNaN(val);
}
public static double bound(double value, double minBoundary, double maxBoundary) {
return Math.max(Math.min(value, maxBoundary), minBoundary);
}
public static boolean isBounded(double val, double lower, double upper) {
return val >= lower && val <= upper;
}
public static boolean isPositive(double val) {
return ! isNegativeOrZero(val);
}
public static boolean isPositiveOrZero(double val) {
return isBounded(val, 0.0, Double.POSITIVE_INFINITY);
}
public static boolean isNegativeOrZero(double val) {
return isBounded(val, Double.NEGATIVE_INFINITY, 0.0);
}
public static boolean isNegative(double val) {
return ! isPositiveOrZero(val);
}
/**
* Compares double values for equality (within 1e-6), or inequality.
*
* @param a the first double value
* @param b the second double value
* @return -1 if a is greater than b, 0 if a is equal to be within 1e-6, 1 if b is greater than a.
*/
public static byte compareDoubles(double a, double b) { return compareDoubles(a, b, 1e-6); }
/**
* Compares double values for equality (within epsilon), or inequality.
*
* @param a the first double value
* @param b the second double value
* @param epsilon the precision within which two double values will be considered equal
* @return -1 if a is greater than b, 0 if a is equal to be within epsilon, 1 if b is greater than a.
*/
public static byte compareDoubles(double a, double b, double epsilon)
{
if (Math.abs(a - b) < epsilon) { return 0; }
if (a > b) { return -1; }
return 1;
}
/**
* Compares float values for equality (within 1e-6), or inequality.
*
* @param a the first float value
* @param b the second float value
* @return -1 if a is greater than b, 0 if a is equal to be within 1e-6, 1 if b is greater than a.
*/
public static byte compareFloats(float a, float b) { return compareFloats(a, b, 1e-6f); }
/**
* Compares float values for equality (within epsilon), or inequality.
*
* @param a the first float value
* @param b the second float value
* @param epsilon the precision within which two float values will be considered equal
* @return -1 if a is greater than b, 0 if a is equal to be within epsilon, 1 if b is greater than a.
*/
public static byte compareFloats(float a, float b, float epsilon)
{
if (Math.abs(a - b) < epsilon) { return 0; }
if (a > b) { return -1; }
return 1;
}
public static double NormalDistribution(double mean, double sd, double x)
{
double a = 1.0 / (sd*Math.sqrt(2.0 * Math.PI));
double b = Math.exp(-1.0 * (Math.pow(x - mean,2.0)/(2.0 * sd * sd)));
return a * b;
}
public static double binomialCoefficient (int n, int k) {
return Math.pow(10, log10BinomialCoefficient(n, k));
}
/**
* Computes a binomial probability. This is computed using the formula
*
* B(k; n; p) = [ n! / ( k! (n - k)! ) ] (p^k)( (1-p)^k )
*
* where n is the number of trials, k is the number of successes, and p is the probability of success
*
* @param n number of Bernoulli trials
* @param k number of successes
* @param p probability of success
*
* @return the binomial probability of the specified configuration. Computes values down to about 1e-237.
*/
public static double binomialProbability (int n, int k, double p) {
return Math.pow(10, log10BinomialProbability(n, k, Math.log10(p)));
}
/**
* Performs the cumulative sum of binomial probabilities, where the probability calculation is done in log space.
* @param start - start of the cumulant sum (over hits)
* @param end - end of the cumulant sum (over hits)
* @param total - number of attempts for the number of hits
* @param probHit - probability of a successful hit
* @return - returns the cumulative probability
*/
public static double binomialCumulativeProbability(int start, int end, int total, double probHit) {
double cumProb = 0.0;
double prevProb;
BigDecimal probCache = BigDecimal.ZERO;
for(int hits = start; hits < end; hits++) {
prevProb = cumProb;
double probability = binomialProbability(total, hits, probHit);
cumProb += probability;
if ( probability > 0 && cumProb - prevProb < probability/2 ) { // loss of precision
probCache = probCache.add(new BigDecimal(prevProb));
cumProb = 0.0;
hits--; // repeat loop
// prevProb changes at start of loop
}
}
return probCache.add(new BigDecimal(cumProb)).doubleValue();
}
/**
* Computes a multinomial coefficient efficiently avoiding overflow even for large numbers.
* This is computed using the formula:
*
* M(x1,x2,...,xk; n) = [ n! / (x1! x2! ... xk!) ]
*
* where xi represents the number of times outcome i was observed, n is the number of total observations.
* In this implementation, the value of n is inferred as the sum over i of xi.
*
* @param k an int[] of counts, where each element represents the number of times a certain outcome was observed
* @return the multinomial of the specified configuration.
*/
public static double multinomialCoefficient (int [] k) {
int n = 0;
for (int xi : k) {
n += xi;
}
return Math.pow(10, log10MultinomialCoefficient(n, k));
}
/**
* Computes a multinomial probability efficiently avoiding overflow even for large numbers.
* This is computed using the formula:
*
* M(x1,x2,...,xk; n; p1,p2,...,pk) = [ n! / (x1! x2! ... xk!) ] (p1^x1)(p2^x2)(...)(pk^xk)
*
* where xi represents the number of times outcome i was observed, n is the number of total observations, and
* pi represents the probability of the i-th outcome to occur. In this implementation, the value of n is
* inferred as the sum over i of xi.
*
* @param k an int[] of counts, where each element represents the number of times a certain outcome was observed
* @param p a double[] of probabilities, where each element represents the probability a given outcome can occur
* @return the multinomial probability of the specified configuration.
*/
public static double multinomialProbability (int[] k, double[] p) {
if (p.length != k.length)
throw new UserException.BadArgumentValue("p and k", "Array of log10 probabilities must have the same size as the array of number of sucesses: " + p.length + ", " + k.length);
int n = 0;
double [] log10P = new double[p.length];
for (int i=0; i<p.length; i++) {
log10P[i] = Math.log10(p[i]);
n += k[i];
}
return Math.pow(10,log10MultinomialProbability(n, k, log10P));
}
/**
* calculate the Root Mean Square of an array of integers
* @param x an byte[] of numbers
* @return the RMS of the specified numbers.
*/
public static double rms(byte[] x) {
if ( x.length == 0 )
return 0.0;
double rms = 0.0;
for (int i : x)
rms += i * i;
rms /= x.length;
return Math.sqrt(rms);
}
/**
* calculate the Root Mean Square of an array of integers
* @param x an int[] of numbers
* @return the RMS of the specified numbers.
*/
public static double rms(int[] x) {
if ( x.length == 0 )
return 0.0;
double rms = 0.0;
for (int i : x)
rms += i * i;
rms /= x.length;
return Math.sqrt(rms);
}
/**
* calculate the Root Mean Square of an array of doubles
* @param x a double[] of numbers
* @return the RMS of the specified numbers.
*/
public static double rms(Double[] x) {
if ( x.length == 0 )
return 0.0;
double rms = 0.0;
for (Double i : x)
rms += i * i;
rms /= x.length;
return Math.sqrt(rms);
}
public static double rms(Collection<Integer> l) {
if (l.size() == 0)
return 0.0;
double rms = 0.0;
for (int i : l)
rms += i*i;
rms /= l.size();
return Math.sqrt(rms);
}
public static double distanceSquared( final double[] x, final double[] y ) {
double dist = 0.0;
for(int iii = 0; iii < x.length; iii++) {
dist += (x[iii] - y[iii]) * (x[iii] - y[iii]);
}
return dist;
}
public static double round(double num, int digits) {
double result = num * Math.pow(10.0, (double)digits);
result = Math.round(result);
result = result / Math.pow(10.0, (double)digits);
return result;
}
/**
* normalizes the log10-based array. ASSUMES THAT ALL ARRAY ENTRIES ARE <= 0 (<= 1 IN REAL-SPACE).
*
* @param array the array to be normalized
* @param takeLog10OfOutput if true, the output will be transformed back into log10 units
*
* @return a newly allocated array corresponding the normalized values in array, maybe log10 transformed
*/
public static double[] normalizeFromLog10(double[] array, boolean takeLog10OfOutput) {
return normalizeFromLog10(array, takeLog10OfOutput, false);
}
public static double[] normalizeFromLog10(double[] array, boolean takeLog10OfOutput, boolean keepInLogSpace) {
// for precision purposes, we need to add (or really subtract, since they're
// all negative) the largest value; also, we need to convert to normal-space.
double maxValue = Utils.findMaxEntry(array);
// we may decide to just normalize in log space with converting to linear space
if (keepInLogSpace) {
for (int i = 0; i < array.length; i++)
array[i] -= maxValue;
return array;
}
// default case: go to linear space
double[] normalized = new double[array.length];
for (int i = 0; i < array.length; i++)
normalized[i] = Math.pow(10, array[i] - maxValue);
// normalize
double sum = 0.0;
for (int i = 0; i < array.length; i++)
sum += normalized[i];
for (int i = 0; i < array.length; i++) {
double x = normalized[i] / sum;
if ( takeLog10OfOutput ) x = Math.log10(x);
normalized[i] = x;
}
return normalized;
}
public static double[] normalizeFromLog10(List<Double> array, boolean takeLog10OfOutput) {
double[] normalized = new double[array.size()];
// for precision purposes, we need to add (or really subtract, since they're
// all negative) the largest value; also, we need to convert to normal-space.
double maxValue = MathUtils.arrayMaxDouble( array );
for (int i = 0; i < array.size(); i++)
normalized[i] = Math.pow(10, array.get(i) - maxValue);
// normalize
double sum = 0.0;
for (int i = 0; i < array.size(); i++)
sum += normalized[i];
for (int i = 0; i < array.size(); i++) {
double x = normalized[i] / sum;
if ( takeLog10OfOutput ) x = Math.log10(x);
normalized[i] = x;
}
return normalized;
}
/**
* normalizes the log10-based array. ASSUMES THAT ALL ARRAY ENTRIES ARE <= 0 (<= 1 IN REAL-SPACE).
*
* @param array the array to be normalized
*
* @return a newly allocated array corresponding the normalized values in array
*/
public static double[] normalizeFromLog10(double[] array) {
return normalizeFromLog10(array, false);
}
public static double[] normalizeFromLog10(List<Double> array) {
return normalizeFromLog10(array, false);
}
public static int maxElementIndex(double[] array) {
if ( array == null ) throw new IllegalArgumentException("Array cannot be null!");
int maxI = -1;
for ( int i = 0; i < array.length; i++ ) {
if ( maxI == -1 || array[i] > array[maxI] )
maxI = i;
}
return maxI;
}
public static int maxElementIndex(int[] array) {
if ( array == null ) throw new IllegalArgumentException("Array cannot be null!");
int maxI = -1;
for ( int i = 0; i < array.length; i++ ) {
if ( maxI == -1 || array[i] > array[maxI] )
maxI = i;
}
return maxI;
}
public static double arrayMax(double[] array) {
return array[maxElementIndex(array)];
}
public static double arrayMin(double[] array) {
return array[minElementIndex(array)];
}
public static byte arrayMin(byte[] array) {
return array[minElementIndex(array)];
}
public static int minElementIndex(double[] array) {
if ( array == null ) throw new IllegalArgumentException("Array cannot be null!");
int minI = -1;
for ( int i = 0; i < array.length; i++ ) {
if ( minI == -1 || array[i] < array[minI] )
minI = i;
}
return minI;
}
public static int minElementIndex(byte[] array) {
if ( array == null ) throw new IllegalArgumentException("Array cannot be null!");
int minI = -1;
for ( int i = 0; i < array.length; i++ ) {
if ( minI == -1 || array[i] < array[minI] )
minI = i;
}
return minI;
}
public static int arrayMaxInt(List<Integer> array) {
if ( array == null ) throw new IllegalArgumentException("Array cannot be null!");
if ( array.size() == 0 ) throw new IllegalArgumentException("Array size cannot be 0!");
int m = array.get(0);
for ( int e : array ) m = Math.max(m, e);
return m;
}
public static double arrayMaxDouble(List<Double> array) {
if ( array == null ) throw new IllegalArgumentException("Array cannot be null!");
if ( array.size() == 0 ) throw new IllegalArgumentException("Array size cannot be 0!");
double m = array.get(0);
for ( double e : array ) m = Math.max(m, e);
return m;
}
public static double average(List<Long> vals, int maxI) {
long sum = 0L;
int i = 0;
for (long x : vals) {
if (i > maxI)
break;
sum += x;
i++;
//System.out.printf(" %d/%d", sum, i);
}
//System.out.printf("Sum = %d, n = %d, maxI = %d, avg = %f%n", sum, i, maxI, (1.0 * sum) / i);
return (1.0 * sum) / i;
}
public static double averageDouble(List<Double> vals, int maxI) {
double sum = 0.0;
int i = 0;
for (double x : vals) {
if (i > maxI)
break;
sum += x;
i++;
}
return (1.0 * sum) / i;
}
public static double average(List<Long> vals) {
return average(vals, vals.size());
}
public static byte average(byte[] vals) {
int sum = 0;
for (byte v : vals) {
sum += v;
}
return (byte) Math.floor(sum/vals.length);
}
public static double averageDouble(List<Double> vals) {
return averageDouble(vals, vals.size());
}
// Java Generics can't do primitive types, so I had to do this the simplistic way
public static Integer[] sortPermutation(final int[] A) {
class comparator implements Comparator<Integer> {
public int compare(Integer a, Integer b) {
if (A[a.intValue()] < A[b.intValue()]) {
return -1;
}
if (A[a.intValue()] == A[b.intValue()]) {
return 0;
}
if (A[a.intValue()] > A[b.intValue()]) {
return 1;
}
return 0;
}
}
Integer[] permutation = new Integer[A.length];
for (int i = 0; i < A.length; i++) {
permutation[i] = i;
}
Arrays.sort(permutation, new comparator());
return permutation;
}
public static Integer[] sortPermutation(final double[] A) {
class comparator implements Comparator<Integer> {
public int compare(Integer a, Integer b) {
if (A[a.intValue()] < A[b.intValue()]) {
return -1;
}
if (A[a.intValue()] == A[b.intValue()]) {
return 0;
}
if (A[a.intValue()] > A[b.intValue()]) {
return 1;
}
return 0;
}
}
Integer[] permutation = new Integer[A.length];
for (int i = 0; i < A.length; i++) {
permutation[i] = i;
}
Arrays.sort(permutation, new comparator());
return permutation;
}
public static <T extends Comparable> Integer[] sortPermutation(List<T> A) {
final Object[] data = A.toArray();
class comparator implements Comparator<Integer> {
public int compare(Integer a, Integer b) {
return ((T) data[a]).compareTo(data[b]);
}
}
Integer[] permutation = new Integer[A.size()];
for (int i = 0; i < A.size(); i++) {
permutation[i] = i;
}
Arrays.sort(permutation, new comparator());
return permutation;
}
public static int[] permuteArray(int[] array, Integer[] permutation) {
int[] output = new int[array.length];
for (int i = 0; i < output.length; i++) {
output[i] = array[permutation[i]];
}
return output;
}
public static double[] permuteArray(double[] array, Integer[] permutation) {
double[] output = new double[array.length];
for (int i = 0; i < output.length; i++) {
output[i] = array[permutation[i]];
}
return output;
}
public static Object[] permuteArray(Object[] array, Integer[] permutation) {
Object[] output = new Object[array.length];
for (int i = 0; i < output.length; i++) {
output[i] = array[permutation[i]];
}
return output;
}
public static String[] permuteArray(String[] array, Integer[] permutation) {
String[] output = new String[array.length];
for (int i = 0; i < output.length; i++) {
output[i] = array[permutation[i]];
}
return output;
}
public static <T> List<T> permuteList(List<T> list, Integer[] permutation) {
List<T> output = new ArrayList<T>();
for (int i = 0; i < permutation.length; i++) {
output.add(list.get(permutation[i]));
}
return output;
}
/** Draw N random elements from list. */
public static <T> List<T> randomSubset(List<T> list, int N) {
if (list.size() <= N) {
return list;
}
int idx[] = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
idx[i] = GenomeAnalysisEngine.getRandomGenerator().nextInt();
}
Integer[] perm = sortPermutation(idx);
List<T> ans = new ArrayList<T>();
for (int i = 0; i < N; i++) {
ans.add(list.get(perm[i]));
}
return ans;
}
public static double percentage(double x, double base) {
return (base > 0 ? (x / base) * 100.0 : 0);
}
public static double percentage(int x, int base) {
return (base > 0 ? ((double) x / (double) base) * 100.0 : 0);
}
public static double percentage(long x, long base) {
return (base > 0 ? ((double) x / (double) base) * 100.0 : 0);
}
public static int countOccurrences(char c, String s) {
int count = 0;
for (int i = 0; i < s.length(); i++) {
count += s.charAt(i) == c ? 1 : 0;
}
return count;
}
public static <T> int countOccurrences(T x, List<T> l) {
int count = 0;
for (T y : l) {
if (x.equals(y)) count++;
}
return count;
}
public static int countOccurrences(byte element, byte [] array) {
int count = 0;
for (byte y : array) {
if (element == y)
count++;
}
return count;
}
/**
* Returns the top (larger) N elements of the array. Naive n^2 implementation (Selection Sort).
* Better than sorting if N (number of elements to return) is small
*
* @param array the array
* @param n number of top elements to return
* @return the n larger elements of the array
*/
public static Collection<Double> getNMaxElements(double [] array, int n) {
ArrayList<Double> maxN = new ArrayList<Double>(n);
double lastMax = Double.MAX_VALUE;
for (int i=0; i<n; i++) {
double max = Double.MIN_VALUE;
for (double x : array) {
max = Math.min(lastMax, Math.max(x, max));
}
maxN.add(max);
lastMax = max;
}
return maxN;
}
/**
* Returns n random indices drawn with replacement from the range 0..(k-1)
*
* @param n the total number of indices sampled from
* @param k the number of random indices to draw (with replacement)
* @return a list of k random indices ranging from 0 to (n-1) with possible duplicates
*/
static public ArrayList<Integer> sampleIndicesWithReplacement(int n, int k) {
ArrayList<Integer> chosen_balls = new ArrayList <Integer>(k);
for (int i=0; i< k; i++) {
//Integer chosen_ball = balls[rand.nextInt(k)];
chosen_balls.add(GenomeAnalysisEngine.getRandomGenerator().nextInt(n));
//balls.remove(chosen_ball);
}
return chosen_balls;
}
/**
* Returns n random indices drawn without replacement from the range 0..(k-1)
*
* @param n the total number of indices sampled from
* @param k the number of random indices to draw (without replacement)
* @return a list of k random indices ranging from 0 to (n-1) without duplicates
*/
static public ArrayList<Integer> sampleIndicesWithoutReplacement(int n, int k) {
ArrayList<Integer> chosen_balls = new ArrayList<Integer>(k);
for (int i = 0; i < n; i++) {
chosen_balls.add(i);
}
Collections.shuffle(chosen_balls, GenomeAnalysisEngine.getRandomGenerator());
//return (ArrayList<Integer>) chosen_balls.subList(0, k);
return new ArrayList<Integer>(chosen_balls.subList(0, k));
}
/**
* Given a list of indices into a list, return those elements of the list with the possibility of drawing list elements multiple times
* @param indices the list of indices for elements to extract
* @param list the list from which the elements should be extracted
* @param <T> the template type of the ArrayList
* @return a new ArrayList consisting of the elements at the specified indices
*/
static public <T> ArrayList<T> sliceListByIndices(List<Integer> indices, List<T> list) {
ArrayList<T> subset = new ArrayList<T>();
for (int i : indices) {
subset.add(list.get(i));
}
return subset;
}
public static Comparable orderStatisticSearch(int orderStat, List<Comparable> list) {
// this finds the order statistic of the list (kth largest element)
// the list is assumed *not* to be sorted
final Comparable x = list.get(orderStat);
ListIterator iterator = list.listIterator();
ArrayList lessThanX = new ArrayList();
ArrayList equalToX = new ArrayList();
ArrayList greaterThanX = new ArrayList();
for(Comparable y : list) {
if(x.compareTo(y) > 0) {
lessThanX.add(y);
} else if(x.compareTo(y) < 0) {
greaterThanX.add(y);
} else
equalToX.add(y);
}
if(lessThanX.size() > orderStat)
return orderStatisticSearch(orderStat, lessThanX);
else if(lessThanX.size() + equalToX.size() >= orderStat)
return orderStat;
else
return orderStatisticSearch(orderStat - lessThanX.size() - equalToX.size(), greaterThanX);
}
public static Object getMedian(List<Comparable> list) {
return orderStatisticSearch((int) Math.ceil(list.size()/2), list);
}
public static byte getQScoreOrderStatistic(List<SAMRecord> reads, List<Integer> offsets, int k) {
// version of the order statistic calculator for SAMRecord/Integer lists, where the
// list index maps to a q-score only through the offset index
// returns the kth-largest q-score.
if( reads.size() == 0) {
return 0;
}
ArrayList lessThanQReads = new ArrayList();
ArrayList equalToQReads = new ArrayList();
ArrayList greaterThanQReads = new ArrayList();
ArrayList lessThanQOffsets = new ArrayList();
ArrayList greaterThanQOffsets = new ArrayList();
final byte qk = reads.get(k).getBaseQualities()[offsets.get(k)];
for(int iter = 0; iter < reads.size(); iter ++) {
SAMRecord read = reads.get(iter);
int offset = offsets.get(iter);
byte quality = read.getBaseQualities()[offset];
if(quality < qk) {
lessThanQReads.add(read);
lessThanQOffsets.add(offset);
} else if(quality > qk) {
greaterThanQReads.add(read);
greaterThanQOffsets.add(offset);
} else {
equalToQReads.add(reads.get(iter));
}
}
if(lessThanQReads.size() > k)
return getQScoreOrderStatistic(lessThanQReads, lessThanQOffsets, k);
else if(equalToQReads.size() + lessThanQReads.size() >= k)
return qk;
else
return getQScoreOrderStatistic(greaterThanQReads, greaterThanQOffsets, k - lessThanQReads.size() - equalToQReads.size());
}
public static byte getQScoreMedian(List<SAMRecord> reads, List<Integer> offsets) {
return getQScoreOrderStatistic(reads, offsets, (int)Math.floor(reads.size()/2.));
}
public static class RunningAverage {
private double mean = 0.0;
private double s = 0.0;
private long obs_count = 0;
public void add(double obs) {
obs_count++;
double oldMean = mean;
mean += ( obs - mean ) / obs_count; // update mean
s += ( obs - oldMean ) * ( obs - mean );
}
public void addAll(Collection<Number> col) {
for ( Number o : col ) {
add(o.doubleValue());
}
}
public double mean() { return mean; }
public double stddev() { return Math.sqrt(s/(obs_count - 1)); }
public double var() { return s/(obs_count - 1); }
public long observationCount() { return obs_count; }
public RunningAverage clone() {
RunningAverage ra = new RunningAverage();
ra.mean = this.mean;
ra.s = this.s;
ra.obs_count = this.obs_count;
return ra;
}
public void merge(RunningAverage other) {
if ( this.obs_count > 0 || other.obs_count > 0 ) { // if we have any observations at all
this.mean = ( this.mean * this.obs_count + other.mean * other.obs_count ) / ( this.obs_count + other.obs_count );
this.s += other.s;
}
this.obs_count += other.obs_count;
}
}
// useful common utility routines
public static double rate(long n, long d) { return n / (1.0 * Math.max(d, 1)); }
public static double rate(int n, int d) { return n / (1.0 * Math.max(d, 1)); }
public static long inverseRate(long n, long d) { return n == 0 ? 0 : d / Math.max(n, 1); }
public static long inverseRate(int n, int d) { return n == 0 ? 0 : d / Math.max(n, 1); }
public static double ratio(int num, int denom) { return ((double)num) / (Math.max(denom, 1)); }
public static double ratio(long num, long denom) { return ((double)num) / (Math.max(denom, 1)); }
public static final double[] log10Cache;
public static final double[] jacobianLogTable;
public static final int JACOBIAN_LOG_TABLE_SIZE = 101;
public static final double JACOBIAN_LOG_TABLE_STEP = 0.1;
public static final double INV_JACOBIAN_LOG_TABLE_STEP = 1.0/JACOBIAN_LOG_TABLE_STEP;
public static final double MAX_JACOBIAN_TOLERANCE = 10.0;
private static final int MAXN = 11000;
private static final int LOG10_CACHE_SIZE = 4 * MAXN; // we need to be able to go up to 2*(2N) when calculating some of the coefficients
static {
log10Cache = new double[LOG10_CACHE_SIZE];
jacobianLogTable = new double[JACOBIAN_LOG_TABLE_SIZE];
log10Cache[0] = Double.NEGATIVE_INFINITY;
for (int k=1; k < LOG10_CACHE_SIZE; k++)
log10Cache[k] = Math.log10(k);
for (int k=0; k < JACOBIAN_LOG_TABLE_SIZE; k++) {
jacobianLogTable[k] = Math.log10(1.0+Math.pow(10.0,-((double)k)
* JACOBIAN_LOG_TABLE_STEP));
}
}
static public double softMax(final double[] vec) {
double acc = vec[0];
for (int k=1; k < vec.length; k++)
acc = softMax(acc,vec[k]);
return acc;
}
static public double max(double x0, double x1, double x2) {
double a = Math.max(x0,x1);
return Math.max(a,x2);
}
static public double softMax(final double x0, final double x1, final double x2) {
// compute naively log10(10^x[0] + 10^x[1]+...)
// return Math.log10(MathUtils.sumLog10(vec));
// better approximation: do Jacobian logarithm function on data pairs
double a = softMax(x0,x1);
return softMax(a,x2);
}
static public double softMax(final double x, final double y) {
// we need to compute log10(10^x + 10^y)
// By Jacobian logarithm identity, this is equal to
// max(x,y) + log10(1+10^-abs(x-y))
// we compute the second term as a table lookup
// with integer quantization
// return Math.log10(Math.pow(10.0,x) + Math.pow(10.0,y));
double diff = x-y;
if (diff > MAX_JACOBIAN_TOLERANCE)
return x;
else if (diff < -MAX_JACOBIAN_TOLERANCE)
return y;
else if (diff >= 0) {
int ind = (int)(diff*INV_JACOBIAN_LOG_TABLE_STEP+0.5);
return x + jacobianLogTable[ind];
}
else {
int ind = (int)(-diff*INV_JACOBIAN_LOG_TABLE_STEP+0.5);
return y + jacobianLogTable[ind];
}
}
public static double phredScaleToProbability (byte q) {
return Math.pow(10,(-q)/10.0);
}
public static double phredScaleToLog10Probability (byte q) {
return ((-q)/10.0);
}
/**
* Returns the phred scaled value of probability p
* @param p probability (between 0 and 1).
* @return phred scaled probability of p
*/
public static byte probabilityToPhredScale (double p) {
return (byte) ((-10) * Math.log10(p));
}
public static double log10ProbabilityToPhredScale (double log10p) {
return (-10) * log10p;
}
/**
* Converts LN to LOG10
* @param ln log(x)
* @return log10(x)
*/
public static double lnToLog10 (double ln) {
return ln * Math.log10(Math.exp(1));
}
/**
* Constants to simplify the log gamma function calculation.
*/
private static final double
zero = 0.0,
one = 1.0,
half = .5,
a0 = 7.72156649015328655494e-02,
a1 = 3.22467033424113591611e-01,
a2 = 6.73523010531292681824e-02,
a3 = 2.05808084325167332806e-02,
a4 = 7.38555086081402883957e-03,
a5 = 2.89051383673415629091e-03,
a6 = 1.19270763183362067845e-03,
a7 = 5.10069792153511336608e-04,
a8 = 2.20862790713908385557e-04,
a9 = 1.08011567247583939954e-04,
a10 = 2.52144565451257326939e-05,
a11 = 4.48640949618915160150e-05,
tc = 1.46163214496836224576e+00,
tf = -1.21486290535849611461e-01,
tt = -3.63867699703950536541e-18,
t0 = 4.83836122723810047042e-01,
t1 = -1.47587722994593911752e-01,
t2 = 6.46249402391333854778e-02,
t3 = -3.27885410759859649565e-02,
t4 = 1.79706750811820387126e-02,
t5 = -1.03142241298341437450e-02,
t6 = 6.10053870246291332635e-03,
t7 = -3.68452016781138256760e-03,
t8 = 2.25964780900612472250e-03,
t9 = -1.40346469989232843813e-03,
t10 = 8.81081882437654011382e-04,
t11 = -5.38595305356740546715e-04,
t12 = 3.15632070903625950361e-04,
t13 = -3.12754168375120860518e-04,
t14 = 3.35529192635519073543e-04,
u0 = -7.72156649015328655494e-02,
u1 = 6.32827064025093366517e-01,
u2 = 1.45492250137234768737e+00,
u3 = 9.77717527963372745603e-01,
u4 = 2.28963728064692451092e-01,
u5 = 1.33810918536787660377e-02,
v1 = 2.45597793713041134822e+00,
v2 = 2.12848976379893395361e+00,
v3 = 7.69285150456672783825e-01,
v4 = 1.04222645593369134254e-01,
v5 = 3.21709242282423911810e-03,
s0 = -7.72156649015328655494e-02,
s1 = 2.14982415960608852501e-01,
s2 = 3.25778796408930981787e-01,
s3 = 1.46350472652464452805e-01,
s4 = 2.66422703033638609560e-02,
s5 = 1.84028451407337715652e-03,
s6 = 3.19475326584100867617e-05,
r1 = 1.39200533467621045958e+00,
r2 = 7.21935547567138069525e-01,
r3 = 1.71933865632803078993e-01,
r4 = 1.86459191715652901344e-02,
r5 = 7.77942496381893596434e-04,
r6 = 7.32668430744625636189e-06,
w0 = 4.18938533204672725052e-01,
w1 = 8.33333333333329678849e-02,
w2 = -2.77777777728775536470e-03,
w3 = 7.93650558643019558500e-04,
w4 = -5.95187557450339963135e-04,
w5 = 8.36339918996282139126e-04,
w6 = -1.63092934096575273989e-03;
/**
* Efficient rounding functions to simplify the log gamma function calculation
* double to long with 32 bit shift
*/
private static final int HI (double x) {
return (int)(Double.doubleToLongBits(x) >> 32);
}
/**
* Efficient rounding functions to simplify the log gamma function calculation
* double to long without shift
*/
private static final int LO (double x) {
return (int)Double.doubleToLongBits(x);
}
/**
* Most efficent implementation of the lnGamma (FDLIBM)
* Use via the log10Gamma wrapper method.
*/
private static double lnGamma (double x) {
double t,y,z,p,p1,p2,p3,q,r,w;
int i;
int hx = HI(x);
int lx = LO(x);
/* purge off +-inf, NaN, +-0, and negative arguments */
int ix = hx&0x7fffffff;
if (ix >= 0x7ff00000) return Double.POSITIVE_INFINITY;
if ((ix|lx)==0 || hx < 0) return Double.NaN;
if (ix<0x3b900000) { /* |x|<2**-70, return -log(|x|) */
return -Math.log(x);
}
/* purge off 1 and 2 */
if((((ix-0x3ff00000)|lx)==0)||(((ix-0x40000000)|lx)==0)) r = 0;
/* for x < 2.0 */
else if(ix<0x40000000) {
if(ix<=0x3feccccc) { /* lgamma(x) = lgamma(x+1)-log(x) */
r = -Math.log(x);
if(ix>=0x3FE76944) {y = one-x; i= 0;}
else if(ix>=0x3FCDA661) {y= x-(tc-one); i=1;}
else {y = x; i=2;}
} else {
r = zero;
if(ix>=0x3FFBB4C3) {y=2.0-x;i=0;} /* [1.7316,2] */
else if(ix>=0x3FF3B4C4) {y=x-tc;i=1;} /* [1.23,1.73] */
else {y=x-one;i=2;}
}
switch(i) {
case 0:
z = y*y;
p1 = a0+z*(a2+z*(a4+z*(a6+z*(a8+z*a10))));
p2 = z*(a1+z*(a3+z*(a5+z*(a7+z*(a9+z*a11)))));
p = y*p1+p2;
r += (p-0.5*y); break;
case 1:
z = y*y;
w = z*y;
p1 = t0+w*(t3+w*(t6+w*(t9 +w*t12))); /* parallel comp */
p2 = t1+w*(t4+w*(t7+w*(t10+w*t13)));
p3 = t2+w*(t5+w*(t8+w*(t11+w*t14)));
p = z*p1-(tt-w*(p2+y*p3));
r += (tf + p); break;
case 2:
p1 = y*(u0+y*(u1+y*(u2+y*(u3+y*(u4+y*u5)))));
p2 = one+y*(v1+y*(v2+y*(v3+y*(v4+y*v5))));
r += (-0.5*y + p1/p2);
}
}
else if(ix<0x40200000) { /* x < 8.0 */
i = (int)x;
t = zero;
y = x-(double)i;
p = y*(s0+y*(s1+y*(s2+y*(s3+y*(s4+y*(s5+y*s6))))));
q = one+y*(r1+y*(r2+y*(r3+y*(r4+y*(r5+y*r6)))));
r = half*y+p/q;
z = one; /* lgamma(1+s) = log(s) + lgamma(s) */
switch(i) {
case 7: z *= (y+6.0); /* FALLTHRU */
case 6: z *= (y+5.0); /* FALLTHRU */
case 5: z *= (y+4.0); /* FALLTHRU */
case 4: z *= (y+3.0); /* FALLTHRU */
case 3: z *= (y+2.0); /* FALLTHRU */
r += Math.log(z); break;
}
/* 8.0 <= x < 2**58 */
} else if (ix < 0x43900000) {
t = Math.log(x);
z = one/x;
y = z*z;
w = w0+z*(w1+y*(w2+y*(w3+y*(w4+y*(w5+y*w6)))));
r = (x-half)*(t-one)+w;
} else
/* 2**58 <= x <= inf */
r = x*(Math.log(x)-one);
return r;
}
/**
* Calculates the log10 of the gamma function for x using the efficient FDLIBM
* implementation to avoid overflows and guarantees high accuracy even for large
* numbers.
*
* @param x the x parameter
* @return the log10 of the gamma function at x.
*/
public static double log10Gamma (double x) {
return lnToLog10(lnGamma(x));
}
/**
* Calculates the log10 of the binomial coefficient. Designed to prevent
* overflows even with very large numbers.
*
* @param n total number of trials
* @param k number of successes
* @return the log10 of the binomial coefficient
*/
public static double log10BinomialCoefficient (int n, int k) {
return log10Gamma(n+1) - log10Gamma(k+1) - log10Gamma(n-k+1);
}
public static double log10BinomialProbability (int n, int k, double log10p) {
double log10OneMinusP = Math.log10(1-Math.pow(10,log10p));
return log10BinomialCoefficient(n, k) + log10p*k + log10OneMinusP*(n-k);
}
/**
* Calculates the log10 of the multinomial coefficient. Designed to prevent
* overflows even with very large numbers.
*
* @param n total number of trials
* @param k array of any size with the number of successes for each grouping (k1, k2, k3, ..., km)
* @return
*/
public static double log10MultinomialCoefficient (int n, int [] k) {
double denominator = 0.0;
for (int x : k) {
denominator += log10Gamma(x+1);
}
return log10Gamma(n+1) - denominator;
}
/**
* Computes the log10 of the multinomial distribution probability given a vector
* of log10 probabilities. Designed to prevent overflows even with very large numbers.
*
* @param n number of trials
* @param k array of number of successes for each possibility
* @param log10p array of log10 probabilities
* @return
*/
public static double log10MultinomialProbability (int n, int [] k, double [] log10p) {
if (log10p.length != k.length)
throw new UserException.BadArgumentValue("p and k", "Array of log10 probabilities must have the same size as the array of number of sucesses: " + log10p.length + ", " + k.length);
double log10Prod = 0.0;
for (int i=0; i<log10p.length; i++) {
log10Prod += log10p[i]*k[i];
}
return log10MultinomialCoefficient(n, k) + log10Prod;
}
public static double factorial (int x) {
return Math.pow(10, log10Gamma(x+1));
}
public static double log10Factorial (int x) {
return log10Gamma(x+1);
}
}
|
package com.badrobots.y2012.technetium.subsystems;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.RobotDrive;
import edu.wpi.first.wpilibj.Victor;
import com.badrobots.y2012.technetium.commands.MechanumDrive;
import edu.wpi.first.wpilibj.command.Subsystem;
import com.badrobots.y2012.technetium.OI;
import com.badrobots.y2012.technetium.PacketListener;
import com.badrobots.y2012.technetium.RobotMap;
import edu.wpi.first.wpilibj.*;
/*
* @author 1014 Programming Team
*/
public class Hermes extends Subsystem
{
private static Hermes instance;
private static RobotDrive drive;
public Victor lFront, lBack, rFront, rBack;
private Gyro horizontalGyro;
private Accelerometer accel;
protected static double strafeCorrectionFactor = .165;
protected static double oneForOneDepth = 5000; // millimeters
private SoftPID rotationPID;
private PIDController pidController;
private double requestedAngle = 0;
private double orientation = 1;
private boolean changeDirection = false;
protected boolean pidEnabled = false;
protected boolean bDepressed = false;
/**
* Singleton Design getter method -- ensures that only one instance of
* DriveTrain is every used. If one has not been made, this method also
* invokes the constructor
*
* @return the single instance of DriveTrain per program
*/
public static Hermes getInstance()
{
if (instance == null)
{
instance = new Hermes();
}
return instance;
}
/*
* Initailizes four Victors, feeds them into a RobotDrive instance, and sets
* the motors in RobotDrive to the correct running direction.
*/
private Hermes()
{
super();
lFront = new Victor(RobotMap.lFront); //initializes all victors
lBack = new Victor(RobotMap.lBack);
rFront = new Victor(RobotMap.rFront);
rBack = new Victor(RobotMap.rBack);
drive = new RobotDrive(lFront, lBack, rFront, rBack); // feeds victors to RobotDrive
// drive.setInvertedMotor(RobotDrive.MotorType.kFrontRight, true);
drive.setInvertedMotor(RobotDrive.MotorType.kFrontRight, true);
drive.setInvertedMotor(RobotDrive.MotorType.kRearLeft, true);
// drive.setInvertedMotor(RobotDrive.MotorType.kRearLeft, true); //
horizontalGyro = new Gyro(RobotMap.verticalGyro); //that's wrong
drive.setSafetyEnabled(false); //because why not. Jon: because it will kill us all.
// Haven't you seen iRobot? They left their robots on
// safety enable = false
rotationPID = new SoftPID();
pidController = new PIDController(OI.getAnalogIn(1), OI.getAnalogIn(2), OI.getAnalogIn(3), horizontalGyro, rotationPID);
pidController.setTolerance(.05);
}
/*
* Takes in 3 values from the joysticks, and sends voltages to
* speedcontrollers accordingly Status:Tested
*/
public void mechanumDrive()
{
double scaledRightStrafe = OI.getUsedRightX() * OI.getSensitivity() * orientation;
double scaledLeftStrafe = OI.getUsedLeftX() * OI.getSensitivity() * orientation;
if (scaledRightStrafe > 1)
{
scaledRightStrafe = 1;
}
if (scaledLeftStrafe > 1)
{
scaledLeftStrafe = 1;
}
if (OI.rightStrafe() && scaledRightStrafe == 0)
pidEnabled = false;
else if (!OI.rightStrafe() && scaledLeftStrafe == 0)
pidEnabled = false;
else
pidEnabled = true;
if (OI.getUsedRightX() != 0)
{
requestedAngle += (OI.getUsedRightX()) * 2;
pidController.setSetpoint(requestedAngle);
}
/* else
{
pidController.setSetpoint(horizontalGyro.getAngle());
}*/
if (!pidController.isEnable())
{
pidController.enable();
}
//System.out.println("Requested Angle: " + requestedAngle + " Current Angle: " + horizontalGyro.getAngle());
//System.out.println("PID Output: " + rotationPID.getValue());
//correct for strafing code
double scaledLeftTurn = (OI.getUsedLeftX() + (strafeCorrectionFactor * scaledRightStrafe)) * OI.getSensitivity(); // forces slight turn
double scaledRightTurn = (OI.getUsedRightX() + (strafeCorrectionFactor * scaledLeftStrafe)) * OI.getSensitivity();
if (OI.primaryXboxRB())
{
changeDirection = true;
}
else if (changeDirection)
{
orientation = orientation * -1;
changeDirection = false;
}
System.out.println("PIDEnabled: " + pidEnabled);
if (OI.primaryXboxB())
{
bDepressed = true;
}
else if (bDepressed)
{
bDepressed = false;
pidEnabled = !pidEnabled;
}
if (!pidEnabled)
{
if (OI.rightStrafe())
{
drive.mecanumDrive_Cartesian(-scaledRightStrafe, (OI.getUsedRightY() * OI.getSensitivity())*orientation, OI.getUsedRightX(), 0); //if right hand stick is being used for strafing left, right, up and down
} else // if left hand stick is being used for strafing
{
drive.mecanumDrive_Cartesian(-scaledLeftStrafe, (OI.getUsedLeftY() * OI.getSensitivity())*orientation, OI.getUsedLeftX(), 0);
}
}
else
{
if (OI.rightStrafe())
{
drive.mecanumDrive_Cartesian(-scaledRightStrafe, (OI.getUsedRightY() * OI.getSensitivity())*orientation, rotationPID.getValue(), 0); //if right hand stick is being used for strafing left, right, up and down
} else // if left hand stick is being used for strafing
{
drive.mecanumDrive_Cartesian(-scaledLeftStrafe, (OI.getUsedLeftY() * OI.getSensitivity())*orientation, rotationPID.getValue(), 0);
}
}
//For PID
}
public void autoAimMechanum(PacketListener kinecter)
{
double scaledRightStrafe = OI.getUsedRightX() * 1.25 * OI.getSensitivity();
double scaledLeftStrafe = OI.getUsedLeftX() * 1.25 * OI.getSensitivity();
if (scaledRightStrafe > 1)
{
scaledRightStrafe = 1;
}
if (scaledLeftStrafe > 1)
{
scaledLeftStrafe = 1;
}
double scaledLeftTurn = 0;
double scaledRightTurn = 0;
//correct for strafing code
if (Math.abs(kinecter.getOffAxis()) > 5)
{
scaledLeftTurn = ((1 / 320) * (kinecter.getDepth() / oneForOneDepth) * kinecter.getOffAxis() * (strafeCorrectionFactor * scaledRightStrafe)); // forces slight turn
scaledRightTurn = ((1 / 320) * (kinecter.getDepth() / oneForOneDepth) * kinecter.getOffAxis() * (strafeCorrectionFactor * scaledLeftStrafe));
}
if (scaledLeftTurn > 1)
{
scaledLeftTurn = 1;
} else
{
if (scaledLeftTurn < -1)
{
scaledLeftTurn = -1;
}
}
if (scaledRightTurn > 1)
{
scaledRightTurn = 1;
} else
{
if (scaledRightTurn < -1)
{
scaledRightTurn = -1;
}
}
if (OI.rightStrafe())
{
drive.mecanumDrive_Cartesian(-scaledRightStrafe, (OI.getUsedRightY() * OI.getSensitivity()), scaledLeftTurn, 0); //if right hand stick is being used for strafing left, right, up and down
} else // if left hand stick is being used for strafing
{
drive.mecanumDrive_Cartesian(-scaledLeftStrafe, (OI.getUsedLeftY() * OI.getSensitivity()), scaledRightTurn, 0);
}
}
/*
* Used for cartesian control of a mechanum drive Status: Untested
*/
public void autoMechanumDrive(double x, double y, double rotation)
{
drive.mecanumDrive_Cartesian(x, y, rotation, 0);
if (rotation > 0)
{
horizontalGyro.reset();
}
}
/*
* @param mag the speed desired to be moved, theta the angle that the robot
* will move towards, rotation the speed at which the robot is turning
*
* Moves the robot using polar coordinates - takes in three components and
* moves the robot accordingly Status: Untested
*/
public void polarMechanum(double mag, double theta, double rotation)
{
drive.mecanumDrive_Polar(mag, theta, rotation);
}
/*
* Tank drives using joystick controls, sets left side to Y value of left
* joystick and right side as Y value of right joystick Status:Tested for
* both xbox + joysticks
*/
public void tankDrive()
{
lFront.set(OI.getUsedLeftY()); //deadzone(OI.leftJoystick.getY()));
lBack.set(-OI.getUsedLeftY()); //-deadzone(OI.leftJoystick.getY()));
rFront.set(-OI.getUsedRightY()); //deadzone(OI.rightJoystick.getY()));
rBack.set(OI.getUsedRightY()); //deadzone(OI.rightJoystick.getY()));
}
/*
* Tank drives using two doubles, left side speed and right speed Status:
* untested
*/
public void tankDrive(double left, double right)
{
lFront.set(left); //deadzone(OI.leftJoystick.getY()));
lBack.set(left); //-deadzone(OI.leftJoystick.getY()));
rFront.set(right); //deadzone(OI.rightJoystick.getY()));
rBack.set(right);
}
/*
* This method may or may not be used depending on whether we use an
* accelerometer @return the accelerometer's value
*/
public double getMovement()
{
return accel.getAcceleration();
}
/*
* Right now, this will not be called because we don't have a gyro hooked
* up. However, it will be used in autonomous, so we might as well keep it
* 2/6/12
*/
public void resetGyro()
{
horizontalGyro.reset();
}
public void resetRequestedAngle()
{
pidController.reset();
requestedAngle = 0;
rotationPID.output = 0;
pidController.enable();
}
public void initDefaultCommand()
{
setDefaultCommand(new MechanumDrive());
}
public class SoftPID implements PIDOutput
{
double output = 0;
public double getValue()
{
return this.output;
}
public void pidWrite(double output)
{
this.output = output;
}
}
}
|
package xal.tools.correlator;
import xal.tools.messaging.MessageCenter;
import javax.swing.Timer;
import java.awt.event.*;
/**
* PerodicPoster is an auxiliary class for posting correlations periodically. Unlike the TimedBroadcaster,
* it strictly only posts the most recent best correlation within a given time interval. Other correlations within
* that same time period will be dropped. The poster will repeat forever until it is stopped.
*
* @author tap
*/
public class PeriodicPoster<RecordType> implements ActionListener {
final private Correlator<?, RecordType, ? extends SourceAgent<RecordType>> CORRELATOR;
final private PassiveBroadcaster BROADCASTER;
final private javax.swing.Timer TIMER;
/**
* Creates a new instance of PeriodicPoster
* @param aCorrelator The correlator providing the correlations.
* @param period The posting period.
*/
public PeriodicPoster( final Correlator<?, RecordType, ? extends SourceAgent<RecordType>> aCorrelator, final double period ) {
CORRELATOR = aCorrelator;
BROADCASTER = CORRELATOR.usePassiveBroadcaster();
int msecPeriod = (int)(period * 1000);
TIMER = new javax.swing.Timer(msecPeriod, this);
TIMER.setRepeats(true);
TIMER.setCoalesce(true);
}
/**
* Get the associated correlator
* @return the correlator providing the correlations.
*/
public Correlator<?, RecordType, ? extends SourceAgent<RecordType>> getCorrelator() {
return CORRELATOR;
}
/**
* Get the timer period
* @return The timer period.
*/
public double getPeriod() {
int msecPeriod = TIMER.getDelay();
return ((double)(msecPeriod)) / 1000.;
}
/**
* Set the timer period
* @param period The new timer period.
*/
public void setPeriod(double period) {
int msecPeriod = (int)(period * 1000);
TIMER.setDelay(msecPeriod);
}
/**
* Determine if the poster is running
* @return true if the poster is running and false if not.
*/
public boolean isRunning() {
return TIMER.isRunning();
}
/**
* Start the timer
*/
public void start() {
TIMER.start();
}
/** Stop posting */
public void stop() {
TIMER.stop();
}
/** Restart posting */
public void restart() {
TIMER.restart();
}
/** Dispose of the poster */
public void dispose() {
TIMER.stop();
}
/**
* Add the listener of re-broadcast correlation notices.
* @param listener A listener of the correlation notice.
*/
public void addCorrelationNoticeListener( final CorrelationNotice<RecordType> listener ) {
CORRELATOR.addListener( listener );
}
/**
* Remove the listener of re-broadcast correlations
* @param listener A listener of the correlation notice.
*/
public void removeCorrelationNoticeListener( final CorrelationNotice<RecordType> listener ) {
CORRELATOR.removeListener( listener );
}
/**
* Implement ActionListener interface to rebroadcast the best correlation.
* @param event The timer event indicating that it is time to post a correlation.
*/
synchronized public void actionPerformed( final ActionEvent event ) {
BROADCASTER.postBestPartialCorrelation();
}
}
|
package com.dexode.adapter;
import android.support.v7.widget.RecyclerView;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
public class RecyclerAdapterCommandManager {
public RecyclerAdapterCommandManager(final AdapterWrapper adapterWrapper) {
_adapter = adapterWrapper;
}
public RecyclerAdapterCommandManager(final RecyclerView.Adapter adapter) {
_adapter = new AdapterWrapper() {
@Override
public void notifyItemInserted(final int position) {
adapter.notifyItemInserted(position);
}
@Override
public void notifyItemChanged(final int position) {
adapter.notifyItemChanged(position);
}
@Override
public void notifyItemRangeInserted(final int position, final int count) {
adapter.notifyItemRangeInserted(position, count);
}
@Override
public void notifyItemRemoved(final int position) {
adapter.notifyItemRemoved(position);
}
@Override
public void notifyItemRangeRemoved(final int position, final int count) {
adapter.notifyItemRangeRemoved(position, count);
}
@Override
public void notifyDataSetChanged() {
adapter.notifyDataSetChanged();
}
@Override
public void notifyItemMoved(final int fromPosition, final int toPosition) {
adapter.notifyItemMoved(fromPosition, toPosition);
}
};
}
public void pushBackOne(final int id) {
checkStartChanges();
_changes.add(id);
}
public void pushBackAll(final ArrayList<Integer> ids) {
checkStartChanges();
_changes.addAll(ids);
}
public void insert(int position, final int id) {
checkStartChanges();
_changes.add(position, id);
}
public void remove(int position) {
checkStartChanges();
_changes.remove(position);
}
public void reset() {
checkStartChanges();
_changes.clear();
_updates.clear();
}
public void update(final int position, final int id) {
_updates.add(id);
}
public void commit() {
commit(false);
}
public void commit(boolean skipProcessing) {
if (_isReady == false) {
return;
}
skipProcessing = _stable.isEmpty() || skipProcessing;
if (skipProcessing) {
if (_changes != null) {
_stable = _changes;
}
_changes = null;
_updates.clear();
_adapter.notifyDataSetChanged();
return;
}
if (_changes != null) {
process();
_stable = _changes;
}
_changes = null;
for (Integer updateId : _updates) {
final int position = _stable.indexOf(updateId);
if (position > -1) {
_adapter.notifyItemChanged(position);
}
}
_updates.clear();
}
private void process() {
ArrayList<Range> inserted = new ArrayList<>(32);
ArrayList<Range> removed = new ArrayList<>(32);
ArrayList<Integer> processed = new ArrayList<>(_stable);
int offset = 0;
//Search for removed
for (int i = 0; i < _stable.size(); ++i) {
if (_changes.contains(_stable.get(i))) {
continue;
}
processed.remove(i - offset);
appendRange(removed, i, -offset);
++offset;
}
//Search for added
for (int i = 0; i < _changes.size(); ++i) {
if (_stable.contains(_changes.get(i)) == false) {
processed.add(i, _changes.get(i));
appendRange(inserted, i, 0);
}
}
for (Range range : removed) {
if (range.start == range.end) {
_adapter.notifyItemRemoved(range.start);
} else {
_adapter.notifyItemRangeRemoved(range.start, range.end - range.start + 1);
}
}
for (Range range : inserted) {
if (range.start == range.end) {
_adapter.notifyItemInserted(range.start);
} else {
_adapter.notifyItemRangeInserted(range.start, range.end - range.start + 1);
}
}
//Search for moved
for (int i = 0; i < _changes.size(); ++i) {
for (int j = i + 1; j < processed.size(); ++j) {
if (processed.get(j) == _changes.get(i)) {
_adapter.notifyItemMoved(j, i);
break;
}
}
}
}
private void checkStartChanges() {
if (_changes == null) {
_changes = new ArrayList<>(_stable);
}
}
private void appendRange(ArrayList<Range> rangeArray, int position, final int offset) {
if (rangeArray.isEmpty()) {
rangeArray.add(new Range(position + offset, position + offset));
} else {
final Range range = rangeArray.get(rangeArray.size() - 1);
if (range.end + 1 == position) {
range.end = position;
} else {
rangeArray.add(new Range(position + offset, position + offset));
}
}
}
public void onAttachedToRecyclerView() {
_isReady = true;
commit();
}
private boolean _isReady = false;
private ArrayList<Integer> _changes = new ArrayList<>(32);
private Set<Integer> _updates = new HashSet<>(32);
private ArrayList<Integer> _stable = new ArrayList<>(32);
private AdapterWrapper _adapter;
private static class Range {
public Range(final int start, final int end) {
this.start = start;
this.end = end;
}
public int start;
public int end;
}
public interface AdapterWrapper {
void notifyItemInserted(final int position);
void notifyItemChanged(final int position);
void notifyItemRangeInserted(final int position, final int count);
void notifyItemRemoved(final int position);
void notifyItemRangeRemoved(final int position, final int count);
void notifyDataSetChanged();
void notifyItemMoved(int fromPosition, int toPosition);
}
}
|
package de.longri.cachebox3.platform_test;
import com.badlogic.gdx.utils.StringBuilder;
public class Assert {
public static void assertThat(String reason, boolean assertion) throws PlatformAssertionError {
if (!assertion) {
throw new PlatformAssertionError(reason);
}
}
public static void assertThat(boolean assertion) throws PlatformAssertionError {
if (!assertion) {
throw new PlatformAssertionError("");
}
}
public static void assertEquals(double expected, double actual, double tolerance, String reason) throws PlatformAssertionError {
double a = expected - actual;
if (a < 0)
a *= -1;
if (a > tolerance) {
StringBuilder sb = new StringBuilder(reason);
sb.appendLine("");
sb.appendLine("expected:");
sb.appendLine(String.valueOf(expected));
sb.appendLine("");
sb.appendLine("actual:");
sb.appendLine(String.valueOf(actual));
throw new PlatformAssertionError(sb.toString());
}
}
public static void assertEquals(Object expected, Object actual, String reason) throws PlatformAssertionError {
if (!objectsAreEqual(expected, actual)) {
StringBuilder sb = new StringBuilder(reason);
sb.appendLine("");
sb.appendLine("expected:");
sb.appendLine(String.valueOf(expected));
sb.appendLine("");
sb.appendLine("actual:");
sb.appendLine(String.valueOf(actual));
throw new PlatformAssertionError(sb.toString());
}
}
public static void assertEquals(Object expected, Object actual) throws PlatformAssertionError {
if (!objectsAreEqual(expected, actual)) {
StringBuilder sb = new StringBuilder();
sb.appendLine("expected:");
sb.appendLine(String.valueOf(expected));
sb.appendLine("");
sb.appendLine("actual:");
sb.appendLine(String.valueOf(actual));
throw new PlatformAssertionError(sb.toString());
}
}
static boolean objectsAreEqual(Object obj1, Object obj2) {
if (obj1 == null) {
return (obj2 == null);
}
if (obj1 instanceof Number || obj2 instanceof Number) return numberEqualse((Number) obj1, (Number) obj2);
return obj1.equals(obj2);
}
private static boolean numberEqualse(Number obj1, Number obj2) {
if (obj1 instanceof Double || obj1 instanceof Float || obj2 instanceof Double || obj2 instanceof Float)
return obj1.doubleValue() == obj2.doubleValue();
return obj1.longValue() == obj2.longValue();
}
public static void assertTrue(boolean assertion) throws PlatformAssertionError {
assertTrue(assertion, "");
}
public static void assertTrue(boolean assertion, String reason) throws PlatformAssertionError {
if (!assertion) {
throw new PlatformAssertionError(reason);
}
}
public static void assertFalse(boolean assertion) throws PlatformAssertionError {
assertFalse(assertion, "");
}
public static void assertFalse(boolean assertion, String reason) throws PlatformAssertionError {
if (assertion) {
throw new PlatformAssertionError(reason);
}
}
public static void assertNotNull(Object obj) throws PlatformAssertionError {
assertNotNull(obj, "");
}
public static void assertNotNull(Object obj, String message) throws PlatformAssertionError {
if (obj == null) throw new PlatformAssertionError(message);
}
}
|
package fr.aumgn.bukkitutils.util;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import fr.aumgn.bukkitutils.itemtype.ItemTypeDataParser;
public final class Util {
private static final Random RANDOM = new Random();
private Util() {
}
public static Random getRandom() {
return RANDOM;
}
public static <T> T pickRandom(List<T> from) {
if (from.isEmpty()) {
return null;
}
return from.get(getRandom().nextInt(from.size()));
}
public static void callEvent(Event event) {
Bukkit.getPluginManager().callEvent(event);
}
public static void broadcast(String message) {
for (Player player : Bukkit.getOnlinePlayers()) {
player.sendMessage(message);
}
}
public static void broadcast(String permission, String message) {
for (Player player : Bukkit.getOnlinePlayers()) {
if (player.hasPermission(permission)) {
player.sendMessage(message);
}
}
}
public static Material matchMaterial(String pattern) {
if (pattern.equalsIgnoreCase("dye")) {
return Material.INK_SACK;
}
return Material.matchMaterial(pattern);
}
public static Short parseDataFor(Material material, String token) {
try {
return Short.parseShort(token);
} catch (NumberFormatException exc) {
}
ItemTypeDataParser parser = ItemTypeDataParser.getFor(material);
if (parser == null) {
return null;
}
return parser.parse(token);
}
}
|
package hudson;
import hudson.model.Descriptor;
import hudson.model.Describable;
import hudson.model.Hudson;
import hudson.model.ViewDescriptor;
import hudson.model.Descriptor.FormException;
import hudson.util.Memoizer;
import hudson.slaves.NodeDescriptor;
import hudson.tasks.Publisher;
import hudson.tasks.Publisher.DescriptorExtensionListImpl;
import java.util.List;
import java.util.ArrayList;
import java.util.logging.Logger;
import java.util.concurrent.CopyOnWriteArrayList;
import java.lang.reflect.Type;
import java.lang.reflect.ParameterizedType;
import org.jvnet.tiger_types.Types;
import org.kohsuke.stapler.Stapler;
import net.sf.json.JSONObject;
/**
* {@link ExtensionList} for holding a set of {@link Descriptor}s, which is a group of descriptors for
* the same extension point.
*
* Use {@link Hudson#getDescriptorList(Class)} to obtain instances.
*
* @param <D>
* Represents the descriptor type. This is {@code Descriptor<T>} normally but often there are subtypes
* of descriptors, like {@link ViewDescriptor}, {@link NodeDescriptor}, etc, and this parameter points
* to those for better type safety of users.
*
* The actual value of 'D' is not necessary for the operation of this code, so it's purely for convenience
* of the users of this class.
*
* @since 1.286
*/
public class DescriptorExtensionList<T extends Describable<T>, D extends Descriptor<T>> extends ExtensionList<D> {
/**
* Creates a new instance.
*/
public static <T extends Describable<T>,D extends Descriptor<T>>
DescriptorExtensionList<T,D> create(Hudson hudson, Class<T> describableType) {
if(describableType==(Class)Publisher.class) // javac or IntelliJ compiler complains if I don't have this cast
return (DescriptorExtensionList)new DescriptorExtensionListImpl(hudson);
return new DescriptorExtensionList<T,D>(hudson,describableType);
}
/**
* Type of the {@link Describable} that this extension list retains.
*/
private final Class<T> describableType;
protected DescriptorExtensionList(Hudson hudson, Class<T> describableType) {
super(hudson, (Class)Descriptor.class, legacyDescriptors.get(describableType));
this.describableType = describableType;
}
/**
* Finds the descriptor that has the matching fully-qualified class name.
*
* @param fqcn
* Fully qualified name of the descriptor, not the describable.
*/
public D find(String fqcn) {
return Descriptor.find(this,fqcn);
}
/**
* Creates a new instance of a {@link Describable}
* from the structured form submission data posted
* by a radio button group.
*/
public T newInstanceFromRadioList(JSONObject config) throws FormException {
if(config.isNullObject())
return null; // none was selected
int idx = config.getInt("value");
return get(idx).newInstance(Stapler.getCurrentRequest(),config);
}
public T newInstanceFromRadioList(JSONObject parent, String name) throws FormException {
return newInstanceFromRadioList(parent.getJSONObject(name));
}
/**
* Loading the descriptors in this case means filtering the descriptor from the master {@link ExtensionList}.
*/
@Override
protected List<D> load() {
List r = new ArrayList();
for( Descriptor d : hudson.getExtensionList(Descriptor.class) ) {
Type subTyping = Types.getBaseClass(d.getClass(), Descriptor.class);
if (!(subTyping instanceof ParameterizedType)) {
LOGGER.severe(d.getClass()+" doesn't extend Descriptor with a type parameter");
continue; // skip this one
}
if(Types.getTypeArgument(subTyping,0)==describableType)
r.add(d);
}
return r;
}
/**
* Stores manually registered Descriptor instances.
*/
private static final Memoizer<Class,CopyOnWriteArrayList> legacyDescriptors = new Memoizer<Class,CopyOnWriteArrayList>() {
public CopyOnWriteArrayList compute(Class key) {
return new CopyOnWriteArrayList();
}
};
private static final Logger LOGGER = Logger.getLogger(DescriptorExtensionList.class.getName());
}
|
package hudson.tasks.junit;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* Result of one test suite.
*
* <p>
* The notion of "test suite" is rather arbitrary in JUnit ant task.
* It's basically one invocation of junit.
*
* <p>
* This object is really only used as a part of the persisted
* object tree.
*
* @author Kohsuke Kawaguchi
*/
@ExportedBean
public final class SuiteResult implements Serializable {
private final String name;
private final String stdout;
private final String stderr;
private float duration;
/**
* The 'timestamp' attribute of the test suite.
* AFAICT, this is not a required attribute in XML, so the value may be null.
*/
private String timestamp;
/**
* All test cases.
*/
private final List<CaseResult> cases = new ArrayList<CaseResult>();
private transient TestResult parent;
SuiteResult(String name, String stdout, String stderr) {
this.name = name;
this.stderr = stderr;
this.stdout = stdout;
}
/**
* Parses the JUnit XML file into {@link SuiteResult}s.
* This method returns a collection, as a single XML may have multiple <testsuite>
* elements wrapped into the top-level <testsuites>.
*/
static List<SuiteResult> parse(File xmlReport) throws DocumentException {
List<SuiteResult> r = new ArrayList<SuiteResult>();
// parse into DOM
SAXReader saxReader = new SAXReader();
XMLEntityResolver resolver = new XMLEntityResolver();
saxReader.setEntityResolver(resolver);
Document result = saxReader.read(xmlReport);
Element root = result.getRootElement();
if(root.getName().equals("testsuites")) {
// multi-suite file
for (Element suite : (List<Element>)root.elements("testsuite"))
r.add(new SuiteResult(xmlReport,suite));
} else {
// single suite file
r.add(new SuiteResult(xmlReport,root));
}
return r;
}
private SuiteResult(File xmlReport, Element suite) throws DocumentException {
String name = suite.attributeValue("name");
if(name==null)
// some user reported that name is null in their environment.
name = '('+xmlReport.getName()+')';
else {
String pkg = suite.attributeValue("package");
if(pkg!=null) name=pkg+'.'+name;
}
this.name = TestObject.safe(name);
this.timestamp = suite.attributeValue("timestamp");
stdout = suite.elementText("system-out");
stderr = suite.elementText("system-err");
Element ex = suite.element("error");
if(ex!=null) {
// according to junit-noframes.xsl l.229, this happens when the test class failed to load
addCase(new CaseResult(this,suite,"<init>"));
}
for (Element e : (List<Element>)suite.elements("testcase")) {
// when <testsuites> is present, we are better off using @classname on the
// individual testcase class.
// @classname may not exist in individual testcase elements. We now
// also test if the testsuite element has a package name that can be used
// as the class name instead of the file name which is default.
String classname = e.attributeValue("classname");
if (classname == null) {
classname = suite.attributeValue("name");
}
// http://www.nabble.com/difference-in-junit-publisher-and-ant-junitreport-tf4308604.html#a12265700
// one wants to use @name from <testsuite>,
// the other wants to use @classname from <testcase>.
addCase(new CaseResult(this,classname,e));
}
}
/*package*/ void addCase(CaseResult cr) {
cases.add(cr);
duration += cr.getDuration();
}
@Exported
public String getName() {
return name;
}
@Exported
public float getDuration() {
return duration;
}
@Exported
public String getStdout() {
return stdout;
}
@Exported
public String getStderr() {
return stderr;
}
public TestResult getParent() {
return parent;
}
@Exported
public String getTimestamp() {
return timestamp;
}
@Exported
public List<CaseResult> getCases() {
return cases;
}
public SuiteResult getPreviousResult() {
TestResult pr = parent.getPreviousResult();
if(pr==null) return null;
return pr.getSuite(name);
}
/**
* Returns the {@link CaseResult} whose {@link CaseResult#getName()}
* is the same as the given string.
*
* <p>
* Note that test name needs not be unique.
*/
public CaseResult getCase(String name) {
for (CaseResult c : cases) {
if(c.getName().equals(name))
return c;
}
return null;
}
/*package*/ boolean freeze(TestResult owner) {
if(this.parent!=null)
return false; // already frozen
this.parent = owner;
for (CaseResult c : cases)
c.freeze(this);
return true;
}
private static final long serialVersionUID = 1L;
}
|
package edu.upc.fib.wordguess.ui;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class WordGuess extends JPanel {
/**
* Create the panel.
*/
public WordGuess() {
JButton btnRabosw = new JButton("Boton1");
btnRabosw.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
add(btnRabosw);
}
}
|
package io.grpc.internal;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.lang.Math.min;
import com.google.common.io.ByteStreams;
import io.grpc.Codec;
import io.grpc.Compressor;
import io.grpc.Drainable;
import io.grpc.KnownLength;
import io.grpc.Status;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
/**
* Encodes gRPC messages to be delivered via the transport layer which implements {@link
* MessageFramer.Sink}.
*/
public class MessageFramer {
/**
* Sink implemented by the transport layer to receive frames and forward them to their
* destination.
*/
public interface Sink {
/**
* Delivers a frame via the transport.
*
* @param frame a non-empty buffer to deliver or {@code null} if the framer is being
* closed and there is no data to deliver.
* @param endOfStream whether the frame is the last one for the GRPC stream
* @param flush {@code true} if more data may not be arriving soon
*/
void deliverFrame(WritableBuffer frame, boolean endOfStream, boolean flush);
}
private static final int HEADER_LENGTH = 5;
private static final byte UNCOMPRESSED = 0;
private static final byte COMPRESSED = 1;
private final Sink sink;
private WritableBuffer buffer;
private Compressor compressor = Codec.Identity.NONE;
private boolean messageCompression;
private final OutputStreamAdapter outputStreamAdapter = new OutputStreamAdapter();
private final byte[] headerScratch = new byte[HEADER_LENGTH];
private final WritableBufferAllocator bufferAllocator;
private boolean closed;
/**
* Creates a {@code MessageFramer}.
*
* @param sink the sink used to deliver frames to the transport
* @param bufferAllocator allocates buffers that the transport can commit to the wire.
*/
public MessageFramer(Sink sink, WritableBufferAllocator bufferAllocator) {
this.sink = checkNotNull(sink, "sink");
this.bufferAllocator = checkNotNull(bufferAllocator, "bufferAllocator");
}
MessageFramer setCompressor(Compressor compressor) {
this.compressor = checkNotNull(compressor, "Can't pass an empty compressor");
return this;
}
MessageFramer setMessageCompression(boolean enable) {
messageCompression = enable;
return this;
}
/**
* Writes out a payload message.
*
* @param message contains the message to be written out. It will be completely consumed.
*/
public void writePayload(InputStream message) {
verifyNotClosed();
boolean compressed = messageCompression && compressor != Codec.Identity.NONE;
int written = -1;
int messageLength = -2;
try {
messageLength = getKnownLength(message);
if (messageLength != 0 && compressed) {
written = writeCompressed(message, messageLength);
} else {
written = writeUncompressed(message, messageLength);
}
} catch (IOException e) {
// This should not be possible, since sink#deliverFrame doesn't throw.
throw Status.INTERNAL
.withDescription("Failed to frame message")
.withCause(e)
.asRuntimeException();
} catch (RuntimeException e) {
throw Status.INTERNAL
.withDescription("Failed to frame message")
.withCause(e)
.asRuntimeException();
}
if (messageLength != -1 && written != messageLength) {
String err = String.format("Message length inaccurate %s != %s", written, messageLength);
throw Status.INTERNAL.withDescription(err).asRuntimeException();
}
}
private int writeUncompressed(InputStream message, int messageLength) throws IOException {
if (messageLength != -1) {
return writeKnownLength(message, messageLength, false);
}
BufferChainOutputStream bufferChain = new BufferChainOutputStream();
int written = writeToOutputStream(message, bufferChain);
writeBufferChain(bufferChain, false);
return written;
}
private int writeCompressed(InputStream message, int messageLength) throws IOException {
BufferChainOutputStream bufferChain = new BufferChainOutputStream();
OutputStream compressingStream = compressor.compress(bufferChain);
int written;
try {
written = writeToOutputStream(message, compressingStream);
} finally {
compressingStream.close();
}
writeBufferChain(bufferChain, true);
return written;
}
private int getKnownLength(InputStream inputStream) throws IOException {
if (inputStream instanceof KnownLength || inputStream instanceof ByteArrayInputStream) {
return inputStream.available();
}
return -1;
}
/**
* Write an unserialized message with a known length.
*/
private int writeKnownLength(InputStream message, int messageLength, boolean compressed)
throws IOException {
ByteBuffer header = ByteBuffer.wrap(headerScratch);
header.put(compressed ? COMPRESSED : UNCOMPRESSED);
header.putInt(messageLength);
// Allocate the initial buffer chunk based on frame header + payload length.
// Note that the allocator may allocate a buffer larger or smaller than this length
if (buffer == null) {
buffer = bufferAllocator.allocate(header.position() + messageLength);
}
writeRaw(headerScratch, 0, header.position());
return writeToOutputStream(message, outputStreamAdapter);
}
/**
* Write a message that has been serialized to a sequence of buffers.
*/
private void writeBufferChain(BufferChainOutputStream bufferChain, boolean compressed) {
ByteBuffer header = ByteBuffer.wrap(headerScratch);
header.put(compressed ? COMPRESSED : UNCOMPRESSED);
int messageLength = bufferChain.readableBytes();
header.putInt(messageLength);
WritableBuffer writeableHeader = bufferAllocator.allocate(HEADER_LENGTH);
writeableHeader.write(headerScratch, 0, header.position());
if (messageLength == 0) {
// the payload had 0 length so make the header the current buffer.
buffer = writeableHeader;
return;
}
// Note that we are always delivering a small message to the transport here which
// may incur transport framing overhead as it may be sent separately to the contents
// of the GRPC frame.
sink.deliverFrame(writeableHeader, false, false);
// Commit all except the last buffer to the sink
List<WritableBuffer> bufferList = bufferChain.bufferList;
for (int i = 0; i < bufferList.size() - 1; i++) {
sink.deliverFrame(bufferList.get(i), false, false);
}
// Assign the current buffer to the last in the chain so it can be used
// for future writes or written with end-of-stream=true on close.
buffer = bufferList.get(bufferList.size() - 1);
}
private static int writeToOutputStream(InputStream message, OutputStream outputStream)
throws IOException {
if (message instanceof Drainable) {
return ((Drainable) message).drainTo(outputStream);
} else {
// This makes an unnecessary copy of the bytes when bytebuf supports array(). However, we
// expect performance-critical code to support flushTo().
long written = ByteStreams.copy(message, outputStream);
checkArgument(written <= Integer.MAX_VALUE, "Message size overflow: %s", written);
return (int) written;
}
}
private void writeRaw(byte[] b, int off, int len) {
while (len > 0) {
if (buffer != null && buffer.writableBytes() == 0) {
commitToSink(false, false);
}
if (buffer == null) {
// Request a buffer allocation using the message length as a hint.
buffer = bufferAllocator.allocate(len);
}
int toWrite = min(len, buffer.writableBytes());
buffer.write(b, off, toWrite);
off += toWrite;
len -= toWrite;
}
}
/**
* Flushes any buffered data in the framer to the sink.
*/
public void flush() {
if (buffer != null && buffer.readableBytes() > 0) {
commitToSink(false, true);
}
}
/**
* Indicates whether or not this framer has been closed via a call to either
* {@link #close()} or {@link #dispose()}.
*/
public boolean isClosed() {
return closed;
}
/**
* Flushes and closes the framer and releases any buffers. After the framer is closed or
* disposed, additional calls to this method will have no affect.
*/
public void close() {
if (!isClosed()) {
closed = true;
// With the current code we don't expect readableBytes > 0 to be possible here, added
// defensively to prevent buffer leak issues if the framer code changes later.
if (buffer != null && buffer.readableBytes() == 0) {
releaseBuffer();
}
commitToSink(true, true);
}
}
/**
* Closes the framer and releases any buffers, but does not flush. After the framer is
* closed or disposed, additional calls to this method will have no affect.
*/
public void dispose() {
closed = true;
releaseBuffer();
}
private void releaseBuffer() {
if (buffer != null) {
buffer.release();
buffer = null;
}
}
private void commitToSink(boolean endOfStream, boolean flush) {
WritableBuffer buf = buffer;
buffer = null;
sink.deliverFrame(buf, endOfStream, flush);
}
private void verifyNotClosed() {
if (isClosed()) {
throw new IllegalStateException("Framer already closed");
}
}
/** OutputStream whose write()s are passed to the framer. */
private class OutputStreamAdapter extends OutputStream {
private final byte[] singleByte = new byte[1];
@Override
public void write(int b) {
singleByte[0] = (byte) b;
write(singleByte, 0, 1);
}
@Override
public void write(byte[] b, int off, int len) {
writeRaw(b, off, len);
}
}
/**
* Produce a collection of {@link WritableBuffer} instances from the data written to an
* {@link OutputStream}.
*/
private final class BufferChainOutputStream extends OutputStream {
private final byte[] singleByte = new byte[1];
private final List<WritableBuffer> bufferList = new ArrayList<WritableBuffer>();
private WritableBuffer current;
@Override
public void write(int b) {
singleByte[0] = (byte) b;
write(singleByte, 0, 1);
}
@Override
public void write(byte[] b, int off, int len) {
if (current == null) {
// Request len bytes initially from the allocator, it may give us more.
current = bufferAllocator.allocate(len);
bufferList.add(current);
}
while (len > 0) {
int canWrite = Math.min(len, current.writableBytes());
if (canWrite == 0) {
// Assume message is twice as large as previous assumption if were still not done,
// the allocator may allocate more or less than this amount.
int needed = Math.max(len, current.readableBytes() * 2);
current = bufferAllocator.allocate(needed);
bufferList.add(current);
} else {
current.write(b, off, canWrite);
off += canWrite;
len -= canWrite;
}
}
}
private int readableBytes() {
int readable = 0;
for (WritableBuffer writableBuffer : bufferList) {
readable += writableBuffer.readableBytes();
}
return readable;
}
}
}
|
package edu.sc.csce740.model;
import java.util.List;
/**
* Abstract class defining elements in a given degree or security certificate at the University of South Carolina
* @author Maximus Brandel
* @author Ibrahim Elsayed
* @author Christian Merchant
* @version 1.00 2015-11-21
*
*/
public abstract class DegreeRequirements {
/**
* The in memory data structure to store core courses
*/
private List<Course> coreCourses;
/**
* The minimum GPA required for a degree
*/
private double minGPA;
/**
* The maximum degree time in years before a degree becomes invalid
*/
private int maxDegreeTime;
/**
* Flag to see if dissertation requirement was met
*/
private boolean dissertation;
/**
* Flag to see if thesis requirement was met
*/
private boolean thesis;
/**
* Flag to see if report requirement was met(for MSE)
*/
private boolean report;
/**
* Flag to see if exam requirement was met
*/
private boolean exam;
/**
* The number of additional credit hours required for a degree
*/
private int additionalCreditHours;
/**
* The courses to exclude for required for a degree(These courses don't count towards the degree requirement)
*/
private List<String> additionalCreditExcludeCourseIDs;
/**
* The courses that a student must complete for additionalCreditHours for a degree(Used for MSE )
*/
private List<Course> additionalCreditIncludeCourses;
/**
* The number of degree based credit hours required for a degree
*/
private int degreeBasedCreditHours;
/**
* The number of allowed degree based non-CSCE credit hours for a degree
*/
private int degreeBasedNonCSCEHours;
/**
* The course that has a maximum number of hours allowed for a degree, associated with degreeBasedMaxHours
*/
private String degreeBasedMaxCourse;
/**
* The maximum number of hours allowed for a degree, associated with degreeBasedMaxCourse
*/
private int degreeBasedMaxHours;
private List<String> degreeBasedExcludeCourseIDs;
private int degreeBasedCreditHoursWithValidMasterDegree;
private int thesisCreditHours;
private List<String> thesisCourseIDs;
private String degreeName;
private int additionalCreditINFASMinHours;
/**
* The maximum non-CSCE credit hours allowed for INFAS certificate
*/
private int additionalCreditINFASMaxNonCSCEHours;
/**
* The maximum additional credit hours for INFAS certificate with a concurrent Master's degree
*/
private int additionalCreditINFASMaxIncludeMasterHours;
/**
* The years required to complete courses
*/
private int coursesInvalidYears;
/**
* Method to get the core course objects for the degree
* @return a list of course objects that define the core courses for the degree
*/
public List<Course> getCoreCourses() {
return coreCourses;
}
/**
* Method to set the core course objects for the degree
* @param coreCourses the list of core course objects to set for the degree
*/
public void setCoreCourses(List<Course> coreCourses) {
this.coreCourses = coreCourses;
}
/**
* Method to get the minimum GPA allowed for the degree
* @return the minGPA allow for the degree
*/
public double getMinGPA() {
return minGPA;
}
/**
* Method to set the minimum GPA allowed for the degree
* @param minGPA the minGPA to set for the degree
*/
public void setMinGPA(double minGPA) {
this.minGPA = minGPA;
}
/**
* Method to get the maximum degree time in contiguous years allowed to complete the degree
* @return the maxDegreeTime the max degree time allowed to complete the degree
*/
public int getMaxDegreeTime() {
return maxDegreeTime;
}
/**
* Method to set the maximum degree time in contiguous years allowed to complete the degree
* @param maxDegreeTime the maxDegreeTime to set
*/
public void setMaxDegreeTime(int maxDegreeTime) {
this.maxDegreeTime = maxDegreeTime;
}
/**
* Method to check if a dissertation is required for the degree
* @return the dissertation true if so, false else
*/
public boolean isDissertation() {
return dissertation;
}
/**
* Method to set if a dissertation is required for the degree
* @param dissertation the dissertation to set true if so, false else
*/
public void setDissertation(boolean dissertation) {
this.dissertation = dissertation;
}
/**
* Method to check if a thesis is required for the degree
* @return thesis true if so, false else
*/
public boolean isThesis() {
return thesis;
}
/**
* Method to set if a thesis is required for the degree
* @param thesis true if so, false else
*/
public void setThesis(boolean thesis) {
this.thesis = thesis;
}
/**
* Method to check if a report is required for the degree
* @return the report true if so, false else
*/
public boolean isReport() {
return report;
}
/**
* Method to set if a report is required for the degree
* @param report true if so false else
*/
public void setReport(boolean report) {
this.report = report;
}
/**
* Method to check if an exam is required for the degree
* @return the exam true if so false else
*/
public boolean isExam() {
return exam;
}
/**
* Method to set if an exam is required for the degree
* @param exam the exam to set true if so false else
*/
public void setExam(boolean exam) {
this.exam = exam;
}
/**
* Method to get the minimum additional credit hours required for the degree
* @return the additionalCreditHours
*/
public int getAdditionalCreditHours() {
return additionalCreditHours;
}
/**
* Method to set the minimum additional credit hours for a degree
* @param additionalCreditHours the additionalCreditHours to set as a double
*/
public void setAdditionalCreditHours(int additionalCreditHours) {
this.additionalCreditHours = additionalCreditHours;
}
/**Get the number of credit hours required for degree based requirements
* @return the degreeBasedCreditHours
*/
public int getDegreeBasedCreditHours() {
return degreeBasedCreditHours;
}
/**Set the number of credit hours required for degree based requirements
* @param degreeBasedCreditHours the degreeBasedCreditHours to set
*/
public void setDegreeBasedCreditHours(int degreeBasedCreditHours) {
this.degreeBasedCreditHours = degreeBasedCreditHours;
}
/**Get the number of credit hours required for degree based requirements with a previous master's degree
* @return the degreeBasedCreditHoursWithValidMasterDegree
*/
public int getDegreeBasedCreditHoursWithValidMasterDegree() {
return degreeBasedCreditHoursWithValidMasterDegree;
}
/**Set the number of credit hours required for degree based requirements with a previous master's degree
* @param degreeBasedCreditHoursWithValidMasterDegree :
* the degreeBasedCreditHoursWithValidMasterDegree to set
*/
public void setDegreeBasedCreditHoursWithValidMasterDegree(int degreeBasedCreditHoursWithValidMasterDegree) {
this.degreeBasedCreditHoursWithValidMasterDegree = degreeBasedCreditHoursWithValidMasterDegree;
}
/**Get the number of thesis credit hours for the thesis requirement
* @return the thesisCreditHours
*/
public int getThesisCreditHours() {
return thesisCreditHours;
}
/**Set the number of thesis credit hours for the thesis requirement
* @param thesisCreditHours the thesisCreditHours to set
*/
public void setThesisCreditHours(int thesisCreditHours) {
this.thesisCreditHours = thesisCreditHours;
}
/**
* Method to get the string name of the degree
* @return the degreeName as a string
*/
public String getDegreeName() {
return degreeName;
}
/**
* Method to set the string name of the degree
* @param degreeName the degreeName to set as a string
*/
public void setDegreeName(String degreeName) {
this.degreeName = degreeName;
}
/**
* Method to get the remaining core courses
* @return the remainingCoreCourses() list of remaining courses required for the degree
*/
public List<Course> getRemainingCoreCourses() {
return null;
}
/**
* Method to check if a supplied course is a core course
* @param course the course to check
* @return true if so false else
*/
public boolean checkCoreCourses(Course course) {
return false;
}
/**
* Abstract method to get the list of milestones for a particular degree
* @return the <code>List</code> of milestones for the degree
*/
public abstract List<Milestone> getMilestones();
//public abstract setMilestones();
/**
* Abstract method to add milestones to the degree
* @param milestone the milestone to add
*/
public abstract void addMilestone(Milestone milestone);
/**
* Abstract method to check if a milestone is in the degree
* @param milestone the milestone to be checked
* @return true if it is in the degree requirements, else false
*/
public abstract boolean checkMilestone(Milestone milestone);
/**
* Abstract method to get the internship course object for the degree
* @return the internship course object. Null if the degree doesn't require one
*/
public abstract Course getInternship();
/**
* Abstract class to set the internship for the degree
* @param internship the course object of the internship to set
*/
public abstract void setInternship(Course internship);
/**Get the course id's of the courses that are excluded for the additional credit hours requirement
* @return the additionalCreditExcludeCourseIDs
*/
public List<String> getAdditionalCreditExcludeCourseIDs() {
return additionalCreditExcludeCourseIDs;
}
/**Set the course id's of the courses that are excluded for the additional credit hours requirement
* @param additionalCreditExcludeCourseIDs the additionalCreditExcludeCourseIDs to set
*/
public void setAdditionalCreditExcludeCourseIDs(List<String> additionalCreditExcludeCourseIDs) {
this.additionalCreditExcludeCourseIDs = additionalCreditExcludeCourseIDs;
}
/**Get the number of additional credit hours required for a degree
* @return the additionalCreditIncludeCourses
*/
public List<Course> getAdditionalCreditIncludeCourses() {
return additionalCreditIncludeCourses;
}
/**Set the number of additional credit hours required for a degree
* @param additionalCreditIncludeCourses the additionalCreditIncludeCourses to set
*/
public void setAdditionalCreditIncludeCourses(List<Course> additionalCreditIncludeCourses) {
this.additionalCreditIncludeCourses = additionalCreditIncludeCourses;
}
/**Get the number of credit hours allowed non-CSCE courses
* @return the degreeBasedNonCSCEHours
*/
public int getDegreeBasedNonCSCEHours() {
return degreeBasedNonCSCEHours;
}
/**Set the number of credit hours allowed non-CSCE courses
* @param degreeBasedNonCSCEHours the degreeBasedNonCSCEHours to set
*/
public void setDegreeBasedNonCSCEHours(int degreeBasedNonCSCEHours) {
this.degreeBasedNonCSCEHours = degreeBasedNonCSCEHours;
}
/**Get the course that has a maximum limit of how many hours count towards a degree
* @return the degreeBasedMaxCourse
*/
public String getDegreeBasedMaxCourse() {
return degreeBasedMaxCourse;
}
/**Set the course that has a maximum limit of how many hours count towards a degree
* @param degreeBasedMaxCourse the degreeBasedMaxCourse to set
*/
public void setDegreeBasedMaxCourse(String degreeBasedMaxCourse) {
this.degreeBasedMaxCourse = degreeBasedMaxCourse;
}
/**Get the maximum hours allowed for the degreeBasedMaxCourse for a degree
* @return the degreeBasedMaxHours
*/
public int getDegreeBasedMaxHours() {
return degreeBasedMaxHours;
}
/**Set the maximum hours allowed for the degreeBasedMaxCourse for a degree
* @param degreeBasedMaxHours the degreeBasedMaxHours to set
*/
public void setDegreeBasedMaxHours(int degreeBasedMaxHours) {
this.degreeBasedMaxHours = degreeBasedMaxHours;
}
/**Get the course id's to exclude for degree based requirements
* @return the degreeBasedExcludeCourseIDs
*/
public List<String> getDegreeBasedExcludeCourseIDs() {
return degreeBasedExcludeCourseIDs;
}
/**Set the course id's to exclude for degree based requirements
* @param degreeBasedExcludeCourseIDs the degreeBasedExcludeCourseIDs to set
*/
public void setDegreeBasedExcludeCourseIDs(List<String> degreeBasedExcludeCourseIDs) {
this.degreeBasedExcludeCourseIDs = degreeBasedExcludeCourseIDs;
}
/**Get the thesis course id's for a degree
* @return the thesisCourseIDs
*/
public List<String> getThesisCourseIDs() {
return thesisCourseIDs;
}
/**Set the thesis course id's for a degree
* @param thesisCourseIDs the thesisCourseIDs to set
*/
public void setThesisCourseIDs(List<String> thesisCourseIDs) {
this.thesisCourseIDs = thesisCourseIDs;
}
/**Get the minimum credit hours required for 700 level courses for INFAS certificate
* @return the additionalCreditINFASMinHours
*/
public int getAdditionalCreditINFASMinHours() {
return additionalCreditINFASMinHours;
}
/**Set the minimum credit hours required for 700 level courses for INFAS certificate
* @param additionalCreditINFASMinHours the additionalCreditINFASMinHours to set
*/
public void setAdditionalCreditINFASMinHours(int additionalCreditINFASMinHours) {
this.additionalCreditINFASMinHours = additionalCreditINFASMinHours;
}
/**Get the maximum non-CSCE credit hours allowed for INFAS certificate
* @return the additionalCreditINFASMaxNonCSCEHours
*/
public int getAdditionalCreditINFASMaxNonCSCEHours() {
return additionalCreditINFASMaxNonCSCEHours;
}
/**Set the maximum non-CSCE credit hours allowed for INFAS certificate
* @param additionalCreditINFASMaxNonCSCEHours the additionalCreditINFASMaxNonCSCEHours to set
*/
public void setAdditionalCreditINFASMaxNonCSCEHours(int additionalCreditINFASMaxNonCSCEHours) {
this.additionalCreditINFASMaxNonCSCEHours = additionalCreditINFASMaxNonCSCEHours;
}
/**Get the maximum additional credit hours for INFAS certificate with a concurrent Master's degree
* @return the additionalCreditINFASMaxIncludeMasterHours
*/
public int getAdditionalCreditINFASMaxIncludeMasterHours() {
return additionalCreditINFASMaxIncludeMasterHours;
}
/**Set the maximum additional credit hours for INFAS certificate with a concurrent Master's degree
* @param additionalCreditINFASMaxIncludeMasterHours the additionalCreditINFASMaxIncludeMasterHours to set
*/
public void setAdditionalCreditINFASMaxIncludeMasterHours(int additionalCreditINFASMaxIncludeMasterHours) {
this.additionalCreditINFASMaxIncludeMasterHours = additionalCreditINFASMaxIncludeMasterHours;
}
/**Get the years required to complete courses
* @return the coursesInvalidYears
*/
public int getCoursesInvalidYears() {
return coursesInvalidYears;
}
/**Set the years required to complete courses
* @param coursesInvalidYears the coursesInvalidYears to set
*/
public void setCoursesInvalidYears(int coursesInvalidYears) {
this.coursesInvalidYears = coursesInvalidYears;
}
}
|
package jmini3d.material;
import jmini3d.Color4;
import jmini3d.Texture;
/**
* A material with PHONG lighting
*/
public class PhongMaterial extends Material {
// Alpha is intensity
public Color4 ambient;
public Color4 diffuse;
public Color4 specular;
public float shininess = 8;
public PhongMaterial(Color4 ambient, Color4 diffuse, Color4 specular) {
super(new Color4(255, 255, 255, 255));
this.ambient = ambient;
this.diffuse = diffuse;
this.specular = specular;
}
public PhongMaterial(Texture texture, Color4 ambient, Color4 diffuse, Color4 specular) {
super(texture);
this.ambient = ambient;
this.diffuse = diffuse;
this.specular = specular;
}
public PhongMaterial(Texture texture, Color4 ambient, Color4 diffuse, Color4 specular, float shininess) {
super(texture);
this.ambient = ambient;
this.diffuse = diffuse;
this.specular = specular;
this.shininess = shininess;
}
}
|
package org.jgrapes.core.annotation;
import java.lang.annotation.Annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
import org.jgrapes.core.Channel;
import org.jgrapes.core.Channel.Default;
import org.jgrapes.core.ClassChannel;
import org.jgrapes.core.Component;
import org.jgrapes.core.ComponentType;
import org.jgrapes.core.Components;
import org.jgrapes.core.Eligible;
import org.jgrapes.core.Event;
import org.jgrapes.core.HandlerScope;
import org.jgrapes.core.Manager;
import org.jgrapes.core.NamedChannel;
import org.jgrapes.core.NamedEvent;
import org.jgrapes.core.Self;
/**
* This is the basic, general purpose handler annotation provided as part of the
* core package.
*
* The annotated method is invoked for events that have a type (or
* name) matching the given `events` (or `namedEvents`) parameter
* of the annotation and that are fired on one of
* the `channels` (or `namedChannels`) specified in the annotation.
*
* If neither event classes nor named events are specified in the
* annotation, the class of the annotated method's first parameter (which
* must be of type {@link Event} or a derived type) is used as (single)
* event class (see the examples in {@link #events()} and
* {@link #namedEvents()}).
*
* Channel matching is performed by matching the event's channels
* (see {@link Event#channels()}) with the channels specified in the
* handler. The matching algorithm invokes
* {@link Eligible#isEligibleFor(Object) isEligibleFor} for each of the
* event's channels with the class (or name, see {@link #channels()} and
* {@link Handler#namedChannels()}) of each of the channels specified
* in the handler.
*
* If neither channel classes not named channels are specified in the
* handler, or `{@link Default Channel.Default}.class` is specified as one
* of the channel classes, the matching algorithm invokes
* {@link Eligible#isEligibleFor(Object) isEligibleFor} for each of
* the event's channels with the default criterion of the component's
* channel (see {@link Manager#channel()} and
* {@link Eligible#defaultCriterion()}) as argument.
*
* Finally, independent of any specified channels, the matching algorithm
* invokes {@link Eligible#isEligibleFor(Object) isEligibleFor}
* for each of the event's channels with the component's default criterion
* as argument. This results in a match if
* the component itself is used as one of the event's channels
* (see the description of {@link Eligible}).
*
* If a match is found for a given event's properties and a handler's
* specified attributes, the handler method is invoked.
* The method can have an additional optional parameter of type
* {@link Channel} (or a derived type). This parameter does not
* influence the eligibility of the method regarding a given event,
* it determines how the method is invoked. If the method does not
* have a second parameter, it is invoked once if an event
* matches. If the parameter exists, the method is invoked once for
* each of the event's channels, provided that the optional parameter's
* type is assignable from the event's channel.
*
* @see Component#channel()
*/
@Documented
@Retention(value=RetentionPolicy.RUNTIME)
@Target(value=ElementType.METHOD)
@HandlerDefinition(evaluator=Handler.Evaluator.class)
public @interface Handler {
/** The default value for the <code>events</code> parameter of
* the annotation. Indicates that the parameter is not used. */
public static final class NoEvent extends Event<Void> {
}
/** The default value for the <code>channels</code> parameter of
* the annotation. Indicates that the parameter is not used. */
public static final class NoChannel extends ClassChannel {
}
/**
* Specifies classes of events that the handler is to receive.
*
* ```java
* class SampleComponent extends Component {
*
* {@literal @}Handler
* public void onStart(Start event) {
* // Invoked for Start events on the component's channel,
* // event object made available
* }
*
* {@literal @}Handler(events=Start.class)
* public void onStart() {
* // Invoked for Start events on the component's channel,
* // not interested in the event object
* }
*
* {@literal @}Handler(events={Start.class, Stop.class})
* public void onStart(Event<?> event) {
* // Invoked for Start and Stop events on the component's
* // channel, event made available (may need casting to
* // access specific properties)
* }
* }
* ```
*
* @return the event classes
*/
@SuppressWarnings("rawtypes")
Class<? extends Event>[] events() default NoEvent.class;
/**
* Specifies names of {@link NamedEvent}s that the handler is to receive.
*
* ```java
* class SampleComponent extends Component {
*
* {@literal @}Handler(namedEvents="Test")
* public void onTest(Event<?> event) {
* // Invoked for (named) "Test" events (new NamedEvent("Test"))
* // on the component's channel, event object made available
* }
* }
* ```
*
* @return the event names
*/
String[] namedEvents() default "";
/**
* Specifies classes of channels that the handler listens on. If none
* are specified, the component's channel is used.
*
* ```java
* class SampleComponent extends Component {
*
* {@literal @}Handler(channels=Feedback.class)
* public void onStart(Start event) {
* // Invoked for Start events on the "Feedback" channel
* // (class Feedback implements Channel {...}),
* // event object made available
* }
* }
* ```
*
* Specifying `channels=Channel.class` make the handler listen
* for all events, independent of the channel that they are fired on.
*
* @return the channel classes
*/
Class<? extends Channel>[] channels() default NoChannel.class;
/**
* Specifies names of {@link NamedChannel}s that the handler listens on.
*
* ```java
* class SampleComponent extends Component {
*
* {@literal @}Handler(namedChannels="Feedback")
* public void onStart(Start event) {
* // Invoked for Start events on the (named) channel "Feedback"
* // (new NamedChannel("Feedback")), event object made available
* }
* }
* ```
*
* @return the channel names
*/
String[] namedChannels() default "";
/**
* Specifies a priority. The value is used to sort handlers.
* Handlers with higher priority are invoked first.
*
* @return the priority
*/
int priority() default 0;
/**
* Returns {@code true} if the annotated method defines a
* dynamic handler. A dynamic handler must be added to the set of
* handlers of a component explicitly at run time using
* {@link Evaluator#add(ComponentType, String, Object)}
* or {@link Evaluator#add(ComponentType, String, Object, Object, int)}.
*
* ```java
* class SampleComponent extends Component {
*
* SampleComponent() {
* Handler.Evaluator.add(this, "onStartDynamic", someChannel);
* }
*
* {@literal @}Handler(dynamic=true)
* public void onStartDynamic(Start event) {
* // Only invoked if added as handler at runtime
* }
* }
* ```
*
* @return the result
*/
boolean dynamic() default false;
/**
* This class provides the {@link Evaluator} for the
* {@link Handler} annotation provided by the core package. It
* implements the behavior as described for the annotation.
*/
public static class Evaluator implements HandlerDefinition.Evaluator {
@Override
public HandlerScope scope(
ComponentType component, Method method,
Object[] eventValues, Object[] channelValues) {
Handler annotation = method.getAnnotation(Handler.class);
if (annotation == null || annotation.dynamic()) {
return null;
}
return new Scope(component, method, annotation, eventValues,
channelValues);
}
/* (non-Javadoc)
* @see org.jgrapes.core.annotation.HandlerDefinition.Evaluator#getPriority()
*/
@Override
public int priority(Annotation annotation) {
return ((Handler)annotation).priority();
}
/**
* Adds the given method of the given component as a dynamic handler for
* a specific event and channel. The method with the given name must be
* annotated as dynamic handler and must have a single parameter of type
* {@link Event} (or a derived type as appropriate for the event type to
* be handled). It can have an optional parameter of type
* {@link Channel}.
*
* @param component
* the component
* @param method
* the name of the method that implements the handler
* @param eventValue
* the event key that should be used for matching this
* handler with an event. This is equivalent to an
* <code>events</code>/<code>namedEvents</code> parameter
* used with a single value in the handler annotation, but
* here all kinds of Objects are allowed as key values.
* @param channelValue
* the channel value that should be used for matching
* an event's channel with this handler. This is equivalent
* to a `channels`/`namedChannels` parameter with a single
* value in the handler annotation, but
* here all kinds of Objects are allowed as values. As a
* convenience, if the actual object provided is a
* {@link Channel}, its default criterion is used for
* matching.
* @param priority
* the priority of the handler
*/
public static void add(ComponentType component, String method,
Object eventValue, Object channelValue, int priority) {
addInternal(component, method, eventValue, channelValue, priority);
}
/**
* Add a handler like
* {@link #add(ComponentType, String, Object, Object, int)}
* but take the values for event and priority from the annotation.
*
* @param component the component
* @param method the name of the method that implements the handler
* @param channelValue the channel value that should be used
* for matching an event's channel with this handler
*/
public static void add(ComponentType component, String method,
Object channelValue) {
addInternal(component, method, null, channelValue, null);
}
private static void addInternal(ComponentType component, String method,
Object eventValue, Object channelValue, Integer priority) {
try {
if (channelValue instanceof Channel) {
channelValue = ((Eligible)channelValue).defaultCriterion();
}
for (Method m: component.getClass().getMethods()) {
if (!m.getName().equals(method)) {
continue;
}
for (Annotation annotation: m.getDeclaredAnnotations()) {
Class<?> annoType = annotation.annotationType();
if (!(annoType.equals(Handler.class))) {
continue;
}
HandlerDefinition hda
= annoType.getAnnotation(HandlerDefinition.class);
if (hda == null
|| !Handler.class.isAssignableFrom(annoType)
|| !((Handler)annotation).dynamic()) {
continue;
}
Scope scope = new Scope(component, m,
(Handler)annotation,
eventValue == null ? null
: new Object[] { eventValue },
new Object[] { channelValue });
Components.manager(component).addHandler(m, scope,
priority != null ? priority
: ((Handler)annotation).priority());
return;
}
}
throw new IllegalArgumentException(
"No method named \"" + method + "\" with DynamicHandler"
+ " annotation and correct parameter list.");
} catch (SecurityException e) {
throw (RuntimeException)
(new IllegalArgumentException().initCause(e));
}
}
/**
* The handler scope implementation used by the evaluator.
*/
private static class Scope implements HandlerScope {
private Set<Object> handledEvents = new HashSet<Object>();
private Set<Object> handledChannels = new HashSet<Object>();
public Scope(ComponentType component, Method method,
Handler annotation, Object[] eventValues,
Object[] channelValues) {
if (!HandlerDefinition.Evaluator.checkMethodSignature(method)) {
throw new IllegalArgumentException("Method \""
+ method.toString() + "\" cannot be used as"
+ " handler (wrong signature).");
}
if (eventValues != null) {
handledEvents.addAll(Arrays.asList(eventValues));
} else {
// Get all event values from the handler annotation.
if (annotation.events()[0] != Handler.NoEvent.class) {
handledEvents
.addAll(Arrays.asList(annotation.events()));
}
// Get all named events from the annotation and add to event
// keys.
if (!annotation.namedEvents()[0].equals("")) {
handledEvents.addAll(
Arrays.asList(annotation.namedEvents()));
}
// If no event types are given, try first parameter.
if (handledEvents.isEmpty()) {
Class<?>[] paramTypes = method.getParameterTypes();
if (paramTypes.length > 0) {
if (Event.class.isAssignableFrom(paramTypes[0])) {
handledEvents.add(paramTypes[0]);
}
}
}
}
if (channelValues != null) {
handledChannels.addAll(Arrays.asList(channelValues));
} else {
// Get channel values from the annotation.
boolean addDefaultChannel = false;
if (annotation.channels()[0] != Handler.NoChannel.class) {
for (Class<?> c : annotation.channels()) {
if (c == Self.class) {
if (!(component instanceof Channel)) {
throw new IllegalArgumentException(
"Canot use channel This.class in "
+ "annotation of " + method
+ " because " + getClass().getName()
+ " does not implement Channel.");
}
// Will be added anyway, see below
} else if (c == Channel.Default.class) {
addDefaultChannel = true;
} else {
handledChannels.add(c);
}
}
}
// Get named channels from annotation and add to channel
// keys.
if (!annotation.namedChannels()[0].equals("")) {
handledChannels.addAll(
Arrays.asList(annotation.namedChannels()));
}
if (handledChannels.size() == 0 || addDefaultChannel) {
handledChannels.add(Components.manager(component)
.channel().defaultCriterion());
}
}
// Finally, a component always handles events
// directed at it directly.
if (component instanceof Channel) {
handledChannels.add(
((Channel) component).defaultCriterion());
}
}
@Override
public boolean includes(Eligible event, Eligible[] channels) {
for (Object eventValue: handledEvents) {
if (event.isEligibleFor(eventValue)) {
// Found match regarding event, now try channels
for (Eligible channel: channels) {
for (Object channelValue: handledChannels) {
if (channel.isEligibleFor(channelValue)) {
return true;
}
}
}
return false;
}
}
return false;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Scope [");
if (handledEvents != null) {
builder.append("handledEvents=");
builder.append(handledEvents.stream().map(v -> {
if (v instanceof Class) {
return Components.className((Class<?>) v);
}
return v.toString();
}).collect(Collectors.toSet()));
builder.append(", ");
}
if (handledChannels != null) {
builder.append("handledChannels=");
builder.append(handledChannels);
}
builder.append("]");
return builder.toString();
}
}
}
}
|
package ro.isdc.wro.manager;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.Writer;
import java.net.URL;
import java.util.Arrays;
import javax.servlet.FilterConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import junit.framework.Assert;
import org.apache.commons.io.output.WriterOutputStream;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ro.isdc.wro.WroRuntimeException;
import ro.isdc.wro.cache.CacheEntry;
import ro.isdc.wro.config.Context;
import ro.isdc.wro.config.jmx.WroConfiguration;
import ro.isdc.wro.http.support.DelegatingServletOutputStream;
import ro.isdc.wro.http.support.HttpHeader;
import ro.isdc.wro.http.support.UnauthorizedRequestException;
import ro.isdc.wro.manager.callback.PerformanceLoggerCallback;
import ro.isdc.wro.manager.factory.BaseWroManagerFactory;
import ro.isdc.wro.manager.factory.NoProcessorsWroManagerFactory;
import ro.isdc.wro.manager.factory.WroManagerFactory;
import ro.isdc.wro.model.WroModel;
import ro.isdc.wro.model.factory.WroModelFactoryDecorator;
import ro.isdc.wro.model.factory.XmlModelFactory;
import ro.isdc.wro.model.group.DefaultGroupExtractor;
import ro.isdc.wro.model.group.Group;
import ro.isdc.wro.model.group.GroupExtractor;
import ro.isdc.wro.model.resource.Resource;
import ro.isdc.wro.model.resource.ResourceType;
import ro.isdc.wro.model.resource.processor.ResourcePreProcessor;
import ro.isdc.wro.model.resource.processor.impl.css.CssUrlRewritingProcessor;
import ro.isdc.wro.model.resource.util.CRC32HashBuilder;
import ro.isdc.wro.model.resource.util.MD5HashBuilder;
import ro.isdc.wro.util.WroTestUtils;
import ro.isdc.wro.util.WroUtil;
import ro.isdc.wro.util.io.UnclosableBufferedInputStream;
public class TestWroManager {
private static final Logger LOG = LoggerFactory.getLogger(TestWroManager.class);
/**
* A processor which which uses a {@link WroManager} during processor, in order to process a single group, which
* resource is the pre processed resource of this processor.
*/
private static final class WroManagerProcessor
implements ResourcePreProcessor {
private final WroManagerFactory managerFactory = new BaseWroManagerFactory() {
@Override
protected void onAfterInitializeManager(final WroManager manager) {
manager.registerCallback(new PerformanceLoggerCallback());
};
};
public void process(final Resource resource, final Reader reader, final Writer writer)
throws IOException {
LOG.debug("resource: {}", resource);
final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
final HttpServletResponse response = Context.get().getResponse();
Mockito.when(response.getOutputStream()).thenReturn(
new DelegatingServletOutputStream(new WriterOutputStream(writer)));
Mockito.when(request.getRequestURI()).thenReturn("");
final WroConfiguration config = new WroConfiguration();
// we don't need caching here, otherwise we'll have clashing during unit tests.
config.setDebug(true);
config.setDisableCache(true);
Context.set(Context.webContext(request, response, Mockito.mock(FilterConfig.class)), config);
// create a groupExtractor which always return the same group name.
final String groupName = "group";
final GroupExtractor groupExtractor = new DefaultGroupExtractor() {
@Override
public String getGroupName(final HttpServletRequest request) {
return groupName;
}
@Override
public ResourceType getResourceType(final HttpServletRequest request) {
return resource.getType();
}
};
// this manager will make sure that we always process a model holding one group which has only one resource.
final WroManager manager = managerFactory.create();
manager.setModelFactory(new WroModelFactoryDecorator(getValidModelFactory()) {
@Override
public WroModel create() {
final Group group = new Group("group");
group.setResources(Arrays.asList(new Resource[] {
resource
}));
final WroModel model = super.create();
model.setGroups(Arrays.asList(group));
return model;
}
});
manager.setGroupExtractor(groupExtractor);
manager.process();
}
}
private WroManagerFactory managerFactory;
@Before
public void setUp() {
final Context context = Context.webContext(Mockito.mock(HttpServletRequest.class),
Mockito.mock(HttpServletResponse.class, Mockito.RETURNS_DEEP_STUBS), Mockito.mock(FilterConfig.class));
Context.set(context, newConfigWithUpdatePeriodValue(0));
managerFactory = new BaseWroManagerFactory().setModelFactory(getValidModelFactory());
}
private class GenericTestBuilder {
/**
* Perform a processing on a group extracted from requestUri and compares with the expectedResourceUri content.
*
* @param requestUri
* contains the group name to process.
* @param expectedResourceUri
* the uri of the resource which has the expected content.
*/
public void processAndCompare(final String requestUri, final String expectedResourceUri)
throws Exception {
final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
final HttpServletResponse response = Context.get().getResponse();
final ByteArrayOutputStream out = new ByteArrayOutputStream();
Mockito.when(response.getOutputStream()).thenReturn(new DelegatingServletOutputStream(out));
Mockito.when(request.getRequestURI()).thenReturn(requestUri);
Context.set(Context.webContext(request, response, Mockito.mock(FilterConfig.class)));
onBeforeProcess();
managerFactory.create().process();
// compare written bytes to output stream with the content from specified css.
final InputStream expectedInputStream = new UnclosableBufferedInputStream(
WroTestUtils.getInputStream(expectedResourceUri));
final InputStream actualInputStream = new BufferedInputStream(new ByteArrayInputStream(out.toByteArray()));
expectedInputStream.reset();
WroTestUtils.compare(expectedInputStream, actualInputStream);
expectedInputStream.close();
actualInputStream.close();
}
/**
* Allow to execute custom logic before the actual processing is done.
*/
protected void onBeforeProcess() {
}
}
/**
* @return a {@link XmlModelFactory} pointing to a valid config resource.
*/
private static XmlModelFactory getValidModelFactory() {
return new XmlModelFactory() {
@Override
protected InputStream getModelResourceAsStream() {
return TestWroManager.class.getResourceAsStream("wro.xml");
}
};
}
@Test(expected = NullPointerException.class)
public void cannotRegisterNullCallback() {
WroManager manager = new WroManager();
manager.registerCallback(null);
}
/**
* Ignored because it fails when running the test from command line.
*/
// @Ignore
@Test
public void testFromFolder()
throws Exception {
final ResourcePreProcessor processor = new WroManagerProcessor();
final URL url = getClass().getResource("wroManager");
final File testFolder = new File(url.getFile(), "test");
final File expectedFolder = new File(url.getFile(), "expected");
WroTestUtils.compareFromDifferentFoldersByExtension(testFolder, expectedFolder, "js", processor);
// WroTestUtils.compareFromDifferentFoldersByExtension(testFolder, expectedFolder, "css", processor);
}
/**
* Initialize {@link WroConfiguration} object with cacheUpdatePeriod & modelUpdatePeriod equal with provided argument.
*/
private WroConfiguration newConfigWithUpdatePeriodValue(final long periodValue) {
final WroConfiguration config = new WroConfiguration();
config.setCacheUpdatePeriod(periodValue);
config.setModelUpdatePeriod(periodValue);
config.setDisableCache(true);
return config;
}
@Test
public void testNoProcessorWroManagerFactory()
throws IOException {
final WroManagerFactory factory = new NoProcessorsWroManagerFactory();
final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
final HttpServletResponse response = Context.get().getResponse();
final ByteArrayOutputStream out = new ByteArrayOutputStream();
Mockito.when(response.getOutputStream()).thenReturn(new DelegatingServletOutputStream(out));
Mockito.when(request.getRequestURI()).thenReturn("/app/g1.css");
Context.set(Context.webContext(request, response, Mockito.mock(FilterConfig.class)));
final WroManager manager = factory.create();
manager.setModelFactory(getValidModelFactory());
manager.process();
// compare written bytes to output stream with the content from specified css.
WroTestUtils.compare(WroTestUtils.getInputStream("classpath:ro/isdc/wro/manager/noProcessorsResult.css"),
new ByteArrayInputStream(out.toByteArray()));
}
@Test
public void testDuplicatedResourcesShouldBeSkipped()
throws Exception {
new GenericTestBuilder().processAndCompare("/repeatedResources.js", "classpath:ro/isdc/wro/manager/repeated-out.js");
}
@Test
public void testWildcardDuplicatedResourcesShouldBeSkiped()
throws Exception {
new GenericTestBuilder().processAndCompare("/wildcardRepeatedResources.js",
"classpath:ro/isdc/wro/manager/wildcardRepeated-out.js");
}
@Test
public void testMinimizeAttributeIsFalseOnResource()
throws Exception {
new GenericTestBuilder().processAndCompare("/resourceMinimizeFalse.js", "classpath:ro/isdc/wro/manager/sample.js");
}
@Test
public void testMinimizeAttributeIsTrueOnResource()
throws Exception {
new GenericTestBuilder().processAndCompare("/resourceMinimizeTrue.js",
"classpath:ro/isdc/wro/manager/sample.min.js");
}
@Test
public void testWildcardGroupResources()
throws Exception {
new GenericTestBuilder().processAndCompare("/wildcardResources.js", "classpath:ro/isdc/wro/manager/wildcard-out.js");
}
/**
* Test that when ignoreMissingResource is true and IOException is thrown by a processor, no exception is thrown.
*
* @throws Exception
*/
@Test
public void testCssWithInvalidImport()
throws Exception {
new GenericTestBuilder().processAndCompare("/invalidImport.css",
"classpath:ro/isdc/wro/manager/invalidImport-out.css");
}
@Test(expected = WroRuntimeException.class)
public void testCssWithInvalidImportAndIgnoreFalse()
throws Exception {
new GenericTestBuilder() {
@Override
protected void onBeforeProcess() {
Context.get().getConfig().setIgnoreMissingResources(false);
};
}.processAndCompare("/invalidImport.css", "classpath:ro/isdc/wro/manager/invalidImport-out.css");
}
@Test
public void processValidModel()
throws IOException {
final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
final HttpServletResponse response = Mockito.mock(HttpServletResponse.class, Mockito.RETURNS_DEEP_STUBS);
Mockito.when(request.getRequestURI()).thenReturn("/app/g1.css");
// Test also that ETag header value contains quotes
Mockito.doAnswer(new Answer<Void>() {
public Void answer(final InvocationOnMock invocation)
throws Throwable {
LOG.debug("Header: {}", Arrays.toString(invocation.getArguments()));
final Object[] arguments = invocation.getArguments();
if (HttpHeader.ETAG.toString().equals(arguments[0])) {
final String etagHeaderValue = (String) arguments[1];
Assert.assertTrue(etagHeaderValue.matches("\".*?\""));
}
return null;
}
}).when(response).setHeader(Mockito.anyString(), Mockito.anyString());
Context.set(Context.webContext(request, response, Mockito.mock(FilterConfig.class)));
managerFactory.create().process();
}
@Test
public void testManagerWithSchedulerAndUpdatePeriodSet()
throws Exception {
final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
Mockito.when(request.getRequestURI()).thenReturn("/app/g1.css");
final Context context = Context.webContext(request,
Mockito.mock(HttpServletResponse.class, Mockito.RETURNS_DEEP_STUBS), Mockito.mock(FilterConfig.class));
final WroConfiguration config = new WroConfiguration();
// make it run each 1 second
config.setModelUpdatePeriod(1);
config.setCacheUpdatePeriod(1);
Context.set(context, config);
managerFactory.create().process();
// let scheduler run a while
Thread.sleep(1300);
}
/**
* Test how manager behaves when the update period value is greater than zero and the scheduler starts.
*
* @throws Exception
*/
@Test
public void testManagerWhenSchedulerIsStarted()
throws Exception {
newConfigWithUpdatePeriodValue(1);
final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
final HttpServletResponse response = Context.get().getResponse();
Mockito.when(request.getRequestURI()).thenReturn("/app/g1.css");
Context.set(Context.webContext(request, response, Mockito.mock(FilterConfig.class)));
managerFactory.create().process();
// allow thread to do its job
Thread.sleep(500);
}
@Test
public void testAggregatedComputedFolder()
throws Exception {
final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
final HttpServletResponse response = Context.get().getResponse();
Mockito.when(request.getRequestURI()).thenReturn("/wro4j/wro/g1.css");
Context.set(Context.webContext(request, response, Mockito.mock(FilterConfig.class)));
managerFactory.create().process();
Assert.assertEquals("/wro4j/wro/", Context.get().getAggregatedFolderPath());
}
@Test
public void testAggregatedComputedFolder2()
throws Exception {
final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
final HttpServletResponse response = Context.get().getResponse();
Mockito.when(request.getRequestURI()).thenReturn("/wro4j/wro/path/to/g1.css");
Context.set(Context.webContext(request, response, Mockito.mock(FilterConfig.class)));
managerFactory.create().process();
Assert.assertEquals("/wro4j/wro/path/to/", Context.get().getAggregatedFolderPath());
}
@Test(expected = WroRuntimeException.class)
public void shouldNotProcessGroupWithNoResources()
throws Exception {
final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
final HttpServletResponse response = Context.get().getResponse();
Mockito.when(request.getRequestURI()).thenReturn("/noResources.css");
WroConfiguration config = new WroConfiguration();
config.setIgnoreEmptyGroup(false);
Context.set(Context.webContext(request, response, Mockito.mock(FilterConfig.class)), config);
WroModel model = new WroModel();
model.addGroup(new Group("noResources"));
final WroManagerFactory managerFactory = new BaseWroManagerFactory().setModelFactory(WroUtil.factoryFor(model));
managerFactory.create().process();
}
@Test(expected = UnauthorizedRequestException.class)
public void testProxyUnauthorizedRequest()
throws Exception {
processProxyWithResourceId("test");
}
private void processProxyWithResourceId(final String resourceId)
throws IOException {
final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
Mockito.when(request.getParameter(CssUrlRewritingProcessor.PARAM_RESOURCE_ID)).thenReturn(resourceId);
Mockito.when(request.getRequestURI()).thenReturn(
CssUrlRewritingProcessor.PATH_RESOURCES + "?" + CssUrlRewritingProcessor.PARAM_RESOURCE_ID + "=" + resourceId);
final WroConfiguration config = new WroConfiguration();
// we don't need caching here, otherwise we'll have clashing during unit tests.
config.setDisableCache(true);
Context.set(
Context.webContext(request, Mockito.mock(HttpServletResponse.class, Mockito.RETURNS_DEEP_STUBS),
Mockito.mock(FilterConfig.class)), newConfigWithUpdatePeriodValue(0));
managerFactory.create().process();
}
@Test
public void testCRC32Fingerprint()
throws Exception {
final WroManager manager = managerFactory.create();
manager.setHashBuilder(new CRC32HashBuilder());
final String path = manager.encodeVersionIntoGroupPath("g3", ResourceType.CSS, true);
Assert.assertEquals("daa1bb3c/g3.css?minimize=true", path);
}
@Test
public void testMD5Fingerprint()
throws Exception {
final WroManager manager = managerFactory.create();
manager.setHashBuilder(new MD5HashBuilder());
final String path = manager.encodeVersionIntoGroupPath("g3", ResourceType.CSS, true);
Assert.assertEquals("42b98f2980dc1366cf1d2677d4891eda/g3.css?minimize=true", path);
}
@Test
public void testSHA1DefaultHashBuilder()
throws Exception {
final WroManager manager = managerFactory.create();
final String path = manager.encodeVersionIntoGroupPath("g3", ResourceType.CSS, true);
Assert.assertEquals("51e6de8dde498cb0bf082b2cd80323fca19eef5/g3.css?minimize=true", path);
}
@Test
public void cacheShouldBeClearedAfterModelReload()
throws IOException {
final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
final HttpServletResponse response = Mockito.mock(HttpServletResponse.class, Mockito.RETURNS_DEEP_STUBS);
Mockito.when(request.getRequestURI()).thenReturn("/app/g3.css");
final WroConfiguration config = new WroConfiguration();
config.setDebug(true);
config.setDisableCache(false);
Context.set(Context.webContext(request, response, Mockito.mock(FilterConfig.class)));
final WroManager wroManager = managerFactory.create();
wroManager.process();
Assert.assertNotNull(wroManager.getCacheStrategy().get(new CacheEntry("g3", ResourceType.CSS, true)));
final ReloadModelRunnable reloadModelRunnable = new ReloadModelRunnable(wroManager);
reloadModelRunnable.run();
Assert.assertNull(wroManager.getCacheStrategy().get(new CacheEntry("g3", ResourceType.CSS, true)));
}
@After
public void tearDown() {
managerFactory.destroy();
Context.unset();
}
}
|
package org.spoofax.interpreter;
import java.io.IOException;
import org.spoofax.DebugUtil;
import org.spoofax.interpreter.terms.IStrategoTerm;
public class Main {
public static void main(String args[]) throws IOException {
Interpreter itp = new Interpreter();
String file = "";
boolean waitForProfiler = false;
for (int i = 0; i < args.length; i++) {
if (args[i].equals("--debug")) {
DebugUtil.setDebug(true);
} else if (args[i].equals("-i")) {
file = args[i + 1];
} else if (args[i].equals("--wait-for-profiler")) {
waitForProfiler = true;
}
}
try {
itp.load(file);
} catch (IOException e) {
e.printStackTrace();
} catch (InterpreterException e) {
e.printStackTrace();
}
IStrategoTerm inp = itp.getFactory().makeList();
try {
itp.setCurrent(inp);
boolean r = itp.invoke("main_0_0");
if(r) {
System.out.println("" + itp.current());
} else {
System.err.println("rewriting failed");
System.exit(-1);
}
} catch (InterpreterException e) {
e.printStackTrace();
}
if(waitForProfiler)
System.in.read();
}
}
|
package com.jcwhatever.nucleus.providers.citizensnpc;
import com.jcwhatever.nucleus.Nucleus;
import com.jcwhatever.nucleus.providers.citizensnpc.ai.BehaviourAgent;
import com.jcwhatever.nucleus.providers.citizensnpc.ai.NpcGoals;
import com.jcwhatever.nucleus.providers.citizensnpc.navigator.NpcNavigator;
import com.jcwhatever.nucleus.providers.citizensnpc.storage.DataNodeKey;
import com.jcwhatever.nucleus.providers.citizensnpc.traits.NpcTraits;
import com.jcwhatever.nucleus.providers.npc.INpc;
import com.jcwhatever.nucleus.providers.npc.events.NpcClickEvent;
import com.jcwhatever.nucleus.providers.npc.events.NpcDamageByBlockEvent;
import com.jcwhatever.nucleus.providers.npc.events.NpcDamageByEntityEvent;
import com.jcwhatever.nucleus.providers.npc.events.NpcDamageEvent;
import com.jcwhatever.nucleus.providers.npc.events.NpcDeathEvent;
import com.jcwhatever.nucleus.providers.npc.events.NpcDespawnEvent;
import com.jcwhatever.nucleus.providers.npc.events.NpcDespawnEvent.NpcDespawnReason;
import com.jcwhatever.nucleus.providers.npc.events.NpcDisposeEvent;
import com.jcwhatever.nucleus.providers.npc.events.NpcLeftClickEvent;
import com.jcwhatever.nucleus.providers.npc.events.NpcRightClickEvent;
import com.jcwhatever.nucleus.providers.npc.events.NpcSpawnEvent;
import com.jcwhatever.nucleus.providers.npc.events.NpcSpawnEvent.NpcSpawnReason;
import com.jcwhatever.nucleus.providers.npc.events.NpcTargetedEvent;
import com.jcwhatever.nucleus.storage.IDataNode;
import com.jcwhatever.nucleus.utils.PreCon;
import com.jcwhatever.nucleus.utils.Scheduler;
import com.jcwhatever.nucleus.utils.coords.LocationUtils;
import com.jcwhatever.nucleus.utils.observer.script.IScriptUpdateSubscriber;
import com.jcwhatever.nucleus.utils.observer.script.ScriptUpdateSubscriber;
import com.jcwhatever.nucleus.utils.observer.update.NamedUpdateAgents;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import net.citizensnpcs.api.event.DespawnReason;
import net.citizensnpcs.api.npc.NPC;
import net.citizensnpcs.util.NMS;
import java.util.HashMap;
import java.util.Map;
import java.util.WeakHashMap;
import javax.annotation.Nullable;
/**
* {@link INpc} implementation.
*/
public class Npc implements INpc {
private static final Location LOOK_LOCATION = new Location(null, 0, 0, 0);
private String _name;
private String _searchName;
private Registry _registry;
private DataNodeKey _dataKey;
private final NPC _npc;
private final NpcPool _pool;
private final NpcNavigator _navigator;
private final NpcGoals _goals;
private final NpcTraits _traits;
private final NamedUpdateAgents _agents = new NamedUpdateAgents();
private final Map<BehaviourAgent<?, ?, ?, ?>, NamedUpdateAgents> _behaviourAgents = new WeakHashMap<>(10);
private Map<String, Object> _meta;
private boolean _isDisposed;
private boolean _isSpawned;
// Holds entity reference, otherwise no one else may be holding it (weak references).
// Prevents losing entity reference in WeakHashMap in CitizensProvider.
private Entity _currentEntity;
// Store spawn/despawn reasons to fill in functionality missing in Citizens
// spawn event. Used to "guess" the reason an NPC is spawning.
private NpcSpawnReason _spawnReason;
private NpcDespawnReason _lastDespawnReason;
/**
* Constructor.
*
* @param npc The Citizens NPC.
* @param pool The {@link NpcPool} that created the Npc.
*/
public Npc(NPC npc, NpcPool pool) {
PreCon.notNull(npc);
PreCon.notNull(pool);
_npc = npc;
_navigator = new NpcNavigator(this, npc.getNavigator());
_goals = new NpcGoals(this);
_traits = new NpcTraits(this);
_pool = pool;
}
/**
* Initialize or re-initialize.
*
* @param lookupName The unique lookup name of the NPC.
* @param npcName The name of the NPC.
* @param type The initial {@link EntityType}.
* @param registry The owning registry.
* @param dataKey The NPC's data storage.
*/
void init(String lookupName, String npcName,
EntityType type, Registry registry, DataNodeKey dataKey) {
PreCon.notNull(lookupName);
PreCon.notNull(npcName);
PreCon.notNull(type);
PreCon.notNull(registry);
PreCon.notNull(dataKey);
_isDisposed = false;
_name = lookupName;
_searchName = lookupName.toLowerCase();
_registry = registry;
_dataKey = dataKey;
_npc.setName(npcName);
CitizensProvider.getInstance().registerNpc(this);
_traits.init(type);
_navigator.init(registry);
_goals.init();
}
/**
* Get the NPC data storage.
*/
public DataNodeKey getDataKey() {
return _dataKey;
}
/**
* Get the NPC data node storage.
*/
public IDataNode getDataNode() {
return _dataKey.getDataNode();
}
@Override
public String getName() {
return _name;
}
@Override
public String getSearchName() {
return _searchName;
}
@Override
public Registry getRegistry() {
return _registry;
}
@Override
public String getNPCName() {
return _npc.getName();
}
@Nullable
@Override
public Entity getEntity() {
return _npc.getEntity();
}
@Override
public boolean isSpawned() {
return _isSpawned && _npc.isSpawned();
}
@Override
public boolean spawn(Location location) {
PreCon.notNull(location);
checkDisposed();
if (_npc.spawn(LocationUtils.copy(location))) {
_isSpawned = true;
_goals.reset();
CitizensProvider.getInstance().registerEntity(this, _npc.getEntity());
_currentEntity = _npc.getEntity();
return true;
}
return false;
}
@Override
public boolean despawn() {
return !_isDisposed && despawn(DespawnReason.PLUGIN);
}
@Nullable
@Override
public Location getLocation() {
return _npc.getStoredLocation();
}
@Nullable
@Override
public Location getLocation(Location location) {
PreCon.notNull(location);
Location stored = _npc.getStoredLocation();
if (stored == null)
return null;
location.setWorld(stored.getWorld());
location.setX(stored.getX());
location.setY(stored.getY());
location.setZ(stored.getZ());
location.setYaw(stored.getYaw());
location.setPitch(stored.getPitch());
return location;
}
@Override
public NpcNavigator getNavigator() {
return _navigator;
}
@Override
public NpcGoals getGoals() {
return _goals;
}
@Override
public NpcTraits getTraits() {
return _traits;
}
@Override
@Nullable
public Object getMeta(String key) {
PreCon.notNull(key);
if (_meta == null)
return null;
return _meta.get(key);
}
@Override
public void setMeta(String key, @Nullable Object value) {
PreCon.notNullOrEmpty(key);
checkDisposed();
if (_meta == null)
_meta = new HashMap<>(7);
if (value == null) {
_meta.remove(key);
}
else {
_meta.put(key, value);
}
}
@Nullable
@Override
public INpc getNPCVehicle() {
if (!isSpawned())
return null;
Entity entity = _npc.getEntity();
Entity vehicle = entity.getVehicle();
if (vehicle == null)
return null;
return CitizensProvider.getInstance().getNpc(vehicle);
}
@Nullable
@Override
public INpc getNPCPassenger() {
if (!isSpawned())
return null;
Entity entity = _npc.getEntity();
Entity passenger = entity.getPassenger();
if (passenger == null)
return null;
return CitizensProvider.getInstance().getNpc(passenger);
}
@Override
public INpc mountNPC(INpc vehicle) {
PreCon.notNull(vehicle);
checkDisposed();
if (!isSpawned())
return this;
if (!vehicle.isSpawned())
return this;
Entity vehicleEntity = vehicle.getEntity();
assert vehicleEntity != null;
vehicleEntity.setPassenger(_npc.getEntity());
return this;
}
@Override
public INpc look(float yaw, float pitch) {
if (!isSpawned())
return this;
NMS.look(_npc.getEntity(), yaw, pitch);
return this;
}
@Override
public INpc lookEntity(Entity entity) {
PreCon.notNull(entity);
if (!isSpawned())
return this;
Location location = entity.getLocation(LOOK_LOCATION);
return lookLocation(location);
}
@Override
public INpc lookLocation(Location location) {
PreCon.notNull(location);
if (!isSpawned())
return this;
if (location.distanceSquared(_npc.getStoredLocation()) <= 0.25)
return this;
_npc.faceLocation(location);
return this;
}
@Override
public boolean save(IDataNode dataNode) {
PreCon.notNull(dataNode);
dataNode.set("lookup", _name);
dataNode.set("name", _npc.getName());
dataNode.set("uuid", _npc.getUniqueId());
dataNode.set("type", getTraits().getType());
getTraits().save(dataNode.getNode("traits"));
dataNode.save();
return true;
}
@Override
public boolean isDisposed() {
return _isDisposed;
}
@Override
public void dispose() {
if (_isDisposed)
return;
_isDisposed = true;
despawn(DespawnReason.REMOVAL);
NpcDisposeEvent event = new NpcDisposeEvent(Npc.this);
Nucleus.getEventManager().callBukkit(this, event);
CitizensProvider.getInstance().unregisterNPC(this);
_registry.remove(this);
_agents.disposeAgents();
for (NamedUpdateAgents agent : _behaviourAgents.values()) {
agent.disposeAgents();
}
_behaviourAgents.clear();
_goals.dispose();
_traits.dispose();
if (_meta != null)
_meta.clear();
_name = null;
_searchName = null;
_registry = null;
_dataKey = null;
_pool.recycle(this);
}
public NPC getHandle() {
return _npc;
}
@Override
public INpc onNpcSpawn(IScriptUpdateSubscriber<NpcSpawnEvent> subscriber) {
PreCon.notNull(subscriber);
checkDisposed();
_agents.getAgent("onNpcSpawn").register(new ScriptUpdateSubscriber<>(subscriber));
return this;
}
@Override
public INpc onNpcDespawn(IScriptUpdateSubscriber<NpcDespawnEvent> subscriber) {
PreCon.notNull(subscriber);
checkDisposed();
_agents.getAgent("onNpcDespawn").register(new ScriptUpdateSubscriber<>(subscriber));
return this;
}
@Override
public INpc onNpcClick(IScriptUpdateSubscriber<NpcClickEvent> subscriber) {
PreCon.notNull(subscriber);
checkDisposed();
_agents.getAgent("onNpcClick").register(new ScriptUpdateSubscriber<>(subscriber));
return this;
}
@Override
public INpc onNpcRightClick(IScriptUpdateSubscriber<NpcRightClickEvent> subscriber) {
PreCon.notNull(subscriber);
checkDisposed();
_agents.getAgent("onNpcRightClick").register(new ScriptUpdateSubscriber<>(subscriber));
return this;
}
@Override
public INpc onNpcLeftClick(IScriptUpdateSubscriber<NpcLeftClickEvent> subscriber) {
PreCon.notNull(subscriber);
checkDisposed();
_agents.getAgent("onNpcLeftClick").register(new ScriptUpdateSubscriber<>(subscriber));
return this;
}
@Override
public INpc onNpcEntityTarget(IScriptUpdateSubscriber<NpcTargetedEvent> subscriber) {
PreCon.notNull(subscriber);
checkDisposed();
_agents.getAgent("onNpcEntityTarget").register(new ScriptUpdateSubscriber<>(subscriber));
return this;
}
@Override
public INpc onNpcDamage(IScriptUpdateSubscriber<NpcDamageEvent> subscriber) {
PreCon.notNull(subscriber);
checkDisposed();
_agents.getAgent("onNpcDamage").register(new ScriptUpdateSubscriber<>(subscriber));
return this;
}
@Override
public INpc onNpcDamageByBlock(IScriptUpdateSubscriber<NpcDamageByBlockEvent> subscriber) {
PreCon.notNull(subscriber);
checkDisposed();
_agents.getAgent("onNpcDamageByBlock").register(new ScriptUpdateSubscriber<>(subscriber));
return this;
}
@Override
public INpc onNpcDamageByEntity(IScriptUpdateSubscriber<NpcDamageByEntityEvent> subscriber) {
PreCon.notNull(subscriber);
checkDisposed();
_agents.getAgent("onNpcDamageByEntity").register(new ScriptUpdateSubscriber<>(subscriber));
return this;
}
@Override
public INpc onNpcDeath(IScriptUpdateSubscriber<NpcDeathEvent> subscriber) {
PreCon.notNull(subscriber);
checkDisposed();
_agents.getAgent("onNpcDeath").register(new ScriptUpdateSubscriber<>(subscriber));
return this;
}
public void onNpcSpawn(NpcSpawnEvent event) {
PreCon.notNull(event);
updateAgents("onNpcSpawn", event);
_registry.onNpcSpawn(event);
if (!event.isCancelled()) {
_isSpawned = true;
getTraits().onSpawn(event.getReason());
Scheduler.runTaskLater(Nucleus.getPlugin(), new Runnable() {
@Override
public void run() {
if (!_isDisposed)
getTraits().applyEquipment();
}
});
}
}
public void onNpcDespawn(NpcDespawnEvent event) {
PreCon.notNull(event);
updateAgents("onNpcDespawn", event);
_registry.onNpcDespawn(event);
if (!event.isCancelled()) {
_isSpawned = false;
getTraits().onDespawn(event.getReason());
}
}
public void onNpcClick(NpcClickEvent event) {
PreCon.notNull(event);
updateAgents("onNpcClick", event);
_registry.onNpcClick(event);
}
public void onNpcRightClick(NpcRightClickEvent event) {
PreCon.notNull(event);
updateAgents("onNpcRightClick", event);
_registry.onNpcRightClick(event);
}
public void onNpcLeftClick(NpcLeftClickEvent event) {
PreCon.notNull(event);
updateAgents("onNpcLeftClick", event);
_registry.onNpcLeftClick(event);
}
public void onNpcEntityTarget(NpcTargetedEvent event) {
PreCon.notNull(event);
updateAgents("onNpcEntityTarget", event);
_registry.onNpcEntityTarget(event);
}
public void onNpcDamage(NpcDamageEvent event) {
PreCon.notNull(event);
updateAgents("onNpcDamage", event);
_registry.onNpcDamage(event);
}
public void onNpcDamageByBlock(NpcDamageByBlockEvent event) {
PreCon.notNull(event);
updateAgents("onNpcDamageByBlock", event);
_registry.onNpcDamageByBlock(event);
}
public void onNpcDamageByEntity(NpcDamageByEntityEvent event) {
PreCon.notNull(event);
updateAgents("onNpcDamageByEntity", event);
_registry.onNpcDamageByEntity(event);
}
public void onNpcDeath(NpcDeathEvent event) {
PreCon.notNull(event);
updateAgents("onNpcDeath", event);
_registry.onNpcDeath(event);
}
public NamedUpdateAgents registerUpdateAgent(BehaviourAgent<?, ?, ?, ?> agent) {
PreCon.notNull(agent);
checkDisposed();
if (_behaviourAgents.containsKey(agent)) {
return _behaviourAgents.get(agent);
}
NamedUpdateAgents updateAgents = new NamedUpdateAgents();
_behaviourAgents.put(agent, updateAgents);
return updateAgents;
}
public void unregisterUpdateAgent(BehaviourAgent<?, ?, ?, ?> agent) {
_behaviourAgents.remove(agent);
}
public void updateAgents(String agentName, Object event) {
PreCon.notNullOrEmpty(agentName);
PreCon.notNull(event);
for (NamedUpdateAgents agents : _behaviourAgents.values()) {
agents.update(agentName, event);
}
_agents.update(agentName, event);
}
/**
* Get the reason the NPC was spawned for.
*
* <p>For internal use.</p>
*/
public NpcSpawnReason getSpawnReason() {
NpcSpawnReason spawnReason = _spawnReason;
NpcDespawnReason despawnReason = _lastDespawnReason;
_lastDespawnReason = null;
_spawnReason = null;
// attempt to guess the reason Citizens is respawning for
if (spawnReason == null) {
if (despawnReason == null) {
return NpcSpawnReason.INVOKED;
}
else {
switch (despawnReason) {
case INVOKED:
// fall through
case DEATH:
return NpcSpawnReason.INVOKED;
case RESPAWN:
return NpcSpawnReason.RESPAWN;
case CHUNK_UNLOAD:
return NpcSpawnReason.CHUNK_LOAD;
case WORLD_UNLOAD:
return NpcSpawnReason.WORLD_LOAD;
}
}
return NpcSpawnReason.INVOKED;
}
else {
return _spawnReason;
}
}
/**
* Set the last reason the NPC was despawned for.
*
* <p>For internal use.</p>
*
* @param reason The reason.
*/
public void setLastDespawnReason(NpcDespawnReason reason) {
_lastDespawnReason = reason;
}
// despawn the NPC
private boolean despawn(DespawnReason reason) {
if (!isSpawned()) {
// make Citizens2 remove chunk load references to the NPC so
// it doesn't get respawned when the chunk loads.
if (_lastDespawnReason == NpcDespawnReason.CHUNK_UNLOAD &&
reason == DespawnReason.REMOVAL) {
_npc.despawn(reason);
}
return false;
}
Entity entity = _npc.getEntity();
if (_npc.despawn(reason)) {
CitizensProvider.getInstance().unregisterEntity(entity);
_currentEntity = null;
_isSpawned = false;
return true;
}
return false;
}
private void checkDisposed() {
if (_isDisposed)
throw new IllegalStateException("Cannot use a disposed Npc.");
}
}
|
package com.github.wsrv.nio;
import com.github.wsrv.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.concurrent.Callable;
/**
* @author tommaso
*/
@Deprecated
public class SocketChannelHandler implements Callable<Object> {
private final Logger log = LoggerFactory.getLogger(SocketChannelHandler.class);
private SocketChannel socket;
public SocketChannelHandler(SocketChannel socket) {
this.socket = socket;
}
@Override
public Object call() throws Exception {
try {
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
socket.read(byteBuffer);
byteBuffer.flip();
// parse the http request
String requestString = new String(byteBuffer.array());
if (requestString.length() > 20 && requestString.startsWith("GET")) {
HttpRequestParser httpRequestParser = new HttpRequestParser();
HttpRequest httpRequest = httpRequestParser.parse(requestString);
byteBuffer.clear(); //make buffer ready for writing
log.info("parsed HTTP request :\n{}", httpRequest);
Resource resource = null;
// log.info("parsed request :\n " + httpRequest.toString());
// check the cache
// ResourceCache<HttpRequest, Resource> cache = ResourceCacheProvider.getInstance().getCache("in-memory");
// Resource resource = cache.get(httpRequest);
// if (resource == null) {
// // retrieve the resource
// final byte[] byteStream;
// String path = httpRequest.getPath();
// File file = new File(path);
// if (!file.exists()) {
// throw new FileNotFoundException(new StringBuilder(path).append(" not found").toString());
// if (file.isFile()) {
// try {
// byteStream = IOUtils.toByteArray(new FileInputStream(file));
// } catch (Exception e) {
// throw new FileNotFoundException(e.getLocalizedMessage());
// } else {
// StringBuilder sb = new StringBuilder();
// for (File f : file.listFiles()) {
// sb.append(f.getName()).append("\n");
// byteStream = sb.toString().getBytes();
// resource = new Resource() {
// @Override
// public byte[] getBytes() {
// return byteStream;
// cache.put(httpRequest, resource);
// write response
HttpResponse httpResponse = new HttpResponse();
httpResponse.setStatusCode(200);
httpResponse.setVersion(httpRequest.getVersion());
httpResponse.addHeader("ETag", "111");
httpResponse.setResource(resource);
log.info("parsed HTTP response :\n {}", httpResponse);
byteBuffer.put(httpResponse.toString().getBytes());
socket.write(byteBuffer);
}
} catch (Exception e) {
e.printStackTrace();
socket.close();
throw e;
}
return null;
}
}
|
package com.jme3.ai.agents.events;
import java.util.EventListener;
public interface AgentSeenEventListener extends EventListener {
public void handleAgentSeenEvent(AgentSeenEvent event);
}
|
package com.mysample.mondrian.dsp;
import mondrian.olap.Util;
import mondrian.spi.*;
import mondrian.i18n.*;
import org.pentaho.platform.api.engine.IPentahoSession;
import org.pentaho.platform.engine.core.system.PentahoSessionHolder;
import org.apache.log4j.Logger;
import java.io.InputStream;
import java.util.regex.PatternSyntaxException;
/* used to log to console for debugging purpose */
import static java.lang.System.out;
public class DynamicSchemaProcessor extends LocalizingDynamicSchemaProcessor {
private static final Logger LOG = Logger.getLogger(DynamicSchemaProcessor.class);
/** Creates a new instance of class */
public DynamicSchemaProcessor() {
}
@Override
public String filter(String schemaUrl, Util.PropertyList connectInfo, InputStream stream)
throws Exception {
String schema = super.filter(schemaUrl, connectInfo, stream);
System.out.println("[CUSTOM.DSP] *********** Started DSP Custom ***********");
IPentahoSession session = PentahoSessionHolder.getSession();
// if you need only the default Pentaho username session var, not a specific one,
// you can change the code with: String usercode = session.getName().toString();
// this avoid to use a startup kettle job
String usercode = (String) session.getAttribute("USERNAME");
try {
System.out.println("[CUSTOM.DSP] Trying to replace '%USER_NAME%' with session value: "+usercode);
LOG.info("Trying to replace '%USER_NAME%' with session value: "+usercode);
schema = schema.replaceAll("%USER_NAME%", usercode);
}
catch (PatternSyntaxException pse) {
System.out.println("[CUSTOM.DSP] Some error during custom schema processing: "+usercode);
LOG.error("Some error during custom schema processing. " , pse);
pse.printStackTrace();
}
LOG.info("DSP Ended correctly for "+usercode);
System.out.println("[CUSTOM.DSP] *********** DSP Ended correctly for "+usercode+" ***********");
return schema;
}
}
|
package com.redhat.ceylon.compiler.util;
import com.redhat.ceylon.compiler.model.Type;
import com.redhat.ceylon.compiler.tree.Node;
import com.redhat.ceylon.compiler.tree.Tree;
import com.redhat.ceylon.compiler.tree.Visitor;
public class AssertionVisitor extends Visitor {
boolean expectingError = false;
boolean foundError = false;
@Override
public void visit(Tree.TypedDeclaration that) {
checkType(that, that.getTypeOrSubtype().getTypeModel());
super.visit(that);
}
@Override
public void visit(Tree.ExpressionStatement that) {
checkType(that, that.getExpression().getTypeModel());
super.visit(that);
}
private void checkType(Tree.Statement that, Type tm) {
for (Tree.CompilerAnnotation c: that.getCompilerAnnotations()) {
if (c.getIdentifier().getText().equals("type")) {
String actualType = tm.getProducedTypeName();
String expectedType = c.getStringLiteral().getText();
if ( !actualType.equals(expectedType.substring(1,expectedType.length()-1)) )
System.err.println(
"not of type " + expectedType +
" at "+ that.getAntlrTreeNode().getLine() + ":" +
that.getAntlrTreeNode().getCharPositionInLine());
}
}
}
@Override
public void visit(Tree.Statement that) {
boolean b = expectingError;
boolean f = foundError;
expectingError = false;
foundError = false;
for (Tree.CompilerAnnotation c: that.getCompilerAnnotations()) {
if (c.getIdentifier().getText().equals("error")) {
expectingError = true;
}
}
super.visit(that);
if (expectingError!=foundError)
System.err.println(
(expectingError ? "no " : "") + "error encountered at " +
that.getAntlrTreeNode().getLine() + ":" +
that.getAntlrTreeNode().getCharPositionInLine());
expectingError = b;
foundError = f;
}
@Override
public void visitAny(Node that) {
if ( !that.getErrors().isEmpty() )
foundError = true;
super.visitAny(that);
}
}
|
package com.team254.frc2015.auto.modes;
import com.team254.frc2015.Constants;
import com.team254.frc2015.auto.AutoMode;
import com.team254.frc2015.auto.AutoModeEndedException;
import com.team254.frc2015.subsystems.TopCarriage;
import com.team254.lib.util.ConstantsBase;
import edu.wpi.first.wpilibj.Timer;
public class ThreeToteAutoMode extends AutoMode {
public static double CLEAR_TOTE_HEIGHT = 20.0;
public static double CLEAR_GROUND_HEIGHT = 7;
public static double ON_GROUND_HEIGHT = 2;
public static double CLEAR_WHEELS_HEIGHT = 12.5;
Timer t = new Timer();
protected void routine() throws AutoModeEndedException {
t.reset();
t.start();
double heading_cache = 0;
bottom_carriage.setFlapperOpen(true);
top_carriage.setGrabberPosition(TopCarriage.GrabberPositions.CLOSED);
waitTime(.1);
// Move can
top_carriage.setFastPositionSetpoint(20);
waitForCarriageHeight(top_carriage, 16.5, true, 1.0);
intake.setSpeed(Constants.kAutoIntakeSpeed);
drive.setDistanceSetpoint(24);
waitForDriveDistance(10, true, 1.0);
intake.close();
waitForTote(1.0);
// Turn on squeeze
top_carriage.squeeze();
waitForDrive(2);
// Lift tote a bit off ground
bottom_carriage.setFlapperOpen(false);
waitTime(.1);
bottom_carriage.setPositionSetpoint(CLEAR_TOTE_HEIGHT, true);
waitForCarriageHeight(bottom_carriage, CLEAR_TOTE_HEIGHT - 1, true, 1.0);
// Turn 180
drive.setTurnSetPoint(-Math.PI, 3.4);
heading_cache = -Math.PI;
intake.open();
waitForDrive(5.0);
drive.reset();
drive.setDistanceSetpoint(25);
waitForDriveDistance(22.5, true, 1.5);
intake.close();
waitForTote(1.0);
waitForDrive(.5);
// Start turn
drive.setTurnSetPoint(heading_cache + .65);
// Grab 2nd tote
bottom_carriage.setFastPositionSetpoint(2.0);
waitForCarriage(bottom_carriage, 1.5);
bottom_carriage.setPositionSetpoint(CLEAR_TOTE_HEIGHT, true);
waitForCarriageHeight(bottom_carriage, CLEAR_TOTE_HEIGHT - 1, true, 1.5);
intake.setSpeed(0);
waitForDrive(1.0);
drive.reset();
drive.setDistanceSetpoint(33, 42);
intake.setSpeed(-Constants.kAutoIntakeSpeed);
waitForDrive(3.0);
drive.setTurnSetPoint(heading_cache - 0.275);
intake.open();
waitForDrive(1.0);
drive.reset();
drive.setDistanceSetpoint(64);
intake.setSpeed(Constants.kAutoIntakeSpeed);
intake.close();
waitForDriveDistance(55, true, 1.5);
waitForDrive(3);
intake.close();
// Turn towards auto zone
drive.setTurnSetPoint(heading_cache + (Math.PI/2.65));
bottom_carriage.setFastPositionSetpoint(2.0);
waitForCarriage(bottom_carriage, 1.5);
waitForTote(1.0);
bottom_carriage.setPositionSetpoint(CLEAR_GROUND_HEIGHT, true);
waitForCarriageHeight(bottom_carriage, CLEAR_GROUND_HEIGHT - 1, true, 1.5);
waitForDrive(2.0);
// drive forwards to auto zone
drive.reset();
drive.setDistanceSetpoint(90);
waitForDrive(2.0);
// Drop
double top_carriage_height_end = top_carriage.getHeight();
top_carriage.setFastPositionSetpoint(top_carriage_height_end + 15);
intake.open();
bottom_carriage.setFastPositionSetpoint(2.0);
waitForCarriageHeight(bottom_carriage, 2.5, false, 1.0);
bottom_carriage.setFlapperOpen(true);
waitForCarriageHeight(top_carriage, top_carriage_height_end + 4, true, 1.0);
// Drive backwards
drive.setDistanceSetpoint(60);
waitForDrive(2.0);
System.out.println("Auto time: " + t.get());
}
}
|
package com.zegoggles.smssync.service.state;
import android.content.res.Resources;
import com.zegoggles.smssync.R;
import com.zegoggles.smssync.mail.DataType;
import static com.zegoggles.smssync.service.state.SmsSyncState.INITIAL;
public class RestoreState extends State {
/** items currently restored */
public final int currentRestoredCount;
/** total number of items to be restored */
public final int itemsToRestore;
/** how many items did get actually restored */
public final int actualRestoredCount;
/** how many duplicates where detected after restore */
public final int duplicateCount;
public RestoreState() {
this(INITIAL, 0, 0, 0, 0, null, null);
}
public RestoreState(SmsSyncState state,
int currentRestoredCount,
int itemsToRestore,
int actualRestoredCount,
int duplicateCount,
DataType dataType,
Exception exception) {
super(state, dataType, exception);
this.currentRestoredCount = currentRestoredCount;
this.actualRestoredCount = actualRestoredCount;
this.itemsToRestore = itemsToRestore;
this.duplicateCount = duplicateCount;
}
@Override
public String toString() {
return "RestoreStateChanged{" +
"state=" + state +
", currentRestoredCount=" + currentRestoredCount +
", itemsToRestore=" + itemsToRestore +
", actualRestoredCount=" + actualRestoredCount +
", duplicateCount=" + duplicateCount +
'}';
}
@Override
public RestoreState transition(SmsSyncState newState, Exception exception) {
return new RestoreState(newState, currentRestoredCount, itemsToRestore, actualRestoredCount, duplicateCount, dataType, exception);
}
@Override
public String getNotificationLabel(Resources resources) {
String label = super.getNotificationLabel(resources);
if (label != null) return label;
switch (state) {
case RESTORE:
label = resources.getString(R.string.status_restore_details,
currentRestoredCount,
itemsToRestore);
if (dataType != null) {
label += " ("+resources.getString(dataType.resId)+")";
}
return label;
case UPDATING_THREADS:
return resources.getString(R.string.status_updating_threads);
default:
return "";
}
}
}
|
package com.ociweb.matrix;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import com.ociweb.iot.maker.FogRuntime;
import com.ociweb.iot.maker.Hardware;
import com.ociweb.iot.maker.FogApp;
import com.ociweb.pronghorn.pipe.Pipe;
import com.ociweb.pronghorn.pipe.PipeConfig;
import com.ociweb.pronghorn.stage.math.BuildMatrixCompute;
import com.ociweb.pronghorn.stage.math.BuildMatrixCompute.MatrixTypes;
import com.ociweb.pronghorn.stage.math.ColumnSchema;
import com.ociweb.pronghorn.stage.math.ColumnsToRowsStage;
import com.ociweb.pronghorn.stage.math.DecimalSchema;
import com.ociweb.pronghorn.stage.math.MatrixSchema;
import com.ociweb.pronghorn.stage.math.RowSchema;
import com.ociweb.pronghorn.stage.monitor.MonitorConsoleStage;
import com.ociweb.pronghorn.stage.scheduling.FixedThreadsScheduler;
import com.ociweb.pronghorn.stage.scheduling.GraphManager;
import com.ociweb.pronghorn.stage.scheduling.StageScheduler;
import com.ociweb.pronghorn.stage.scheduling.ThreadPerStageScheduler;
import com.ociweb.pronghorn.stage.test.ConsoleSummaryStage;
import com.ociweb.pronghorn.stage.test.PipeCleanerStage;
public class IoTApp implements FogApp
{
public static void main( String[] args ) {
IoTApp app = new IoTApp();
//DeviceRuntime.run(app);
app.matrixTest();
}
@Override
public void declareConnections(Hardware c) {
//Connection specifications
// // specify each of the connections on the harware, eg which component is plugged into which connection.
//c.connect(Button, BUTTON_PORT);
//c.connect(Relay, RELAY_PORT);
//c.connect(LightSensor, LIGHT_SENSOR_PORT);
//c.connect(LED, LED_PORT);
//c.useI2C();
}
@Override
public void declareBehavior(FogRuntime runtime) {
runtime.registerListener(new Behavior(runtime));
}
public <M extends MatrixSchema<M> > void matrixTest() {
//speed
//slow Doubles Longs 6.15 5.8 7.024 7.18
// Decimals 5.9 9.40 - 13
// Floats 6.06 6.26
//fast Integers 5.80 5.95
MatrixTypes type = MatrixTypes.Integers;//Decimals;//Integers; //2, 3328335 longs/ints/doubles [0,332833152] floats
//TypeMask.Decimal;
//when matrix size is larger than CPU cache we run into issues.
int leftRows=1200;
int leftColumns = 1000;
int rightColumns=1000;
int rightRows=leftColumns;
//walk leftRows , by rightCol for output
//5x2
//2x3
MatrixSchema leftSchema = BuildMatrixCompute.buildSchema(leftRows, leftColumns, type);
RowSchema<M> leftRowSchema = new RowSchema<M>(leftSchema);
MatrixSchema rightSchema = BuildMatrixCompute.buildSchema(rightRows, rightColumns, type);
RowSchema<M> rightRowSchema = new RowSchema<M>(rightSchema);
MatrixSchema resultSchema = BuildMatrixCompute.buildResultSchema(leftSchema, rightSchema);
RowSchema<M> rowResultSchema = new RowSchema<M>(resultSchema);
DecimalSchema result2Schema = new DecimalSchema<M>(resultSchema);
GraphManager gm = new GraphManager();
//GraphManager.addDefaultNota(gm, GraphManager.SCHEDULE_RATE, 500);
//TODO: not sure why but the splitter that consumes left needs a minimum ring size or it gets stuck,
Pipe<RowSchema<M>> left = new Pipe<RowSchema<M>>(new PipeConfig<RowSchema<M>>(leftRowSchema, leftRows /*Math.min(16, leftRows)*/));
Pipe<RowSchema<M>> right = new Pipe<RowSchema<M>>(new PipeConfig<RowSchema<M>>(rightRowSchema, rightRows /*Math.min(16, rightRows)*/));
Pipe<RowSchema<M>> result = new Pipe<RowSchema<M>>(new PipeConfig<RowSchema<M>>(rowResultSchema, /*Math.min(16,*/ resultSchema.getRows() )); //NOTE: reqires 2 or JSON will not write out !!
// Pipe<DecimalSchema<MatrixSchema>> result2 = new Pipe<DecimalSchema<MatrixSchema>>(new PipeConfig<DecimalSchema<MatrixSchema>>(result2Schema, resultSchema.getRows())); //NOTE: reqires 2 or JSON will not write out !!
int targetThreadCount = 10;//60; //105967ms
Pipe<ColumnSchema<M>>[] colResults = BuildMatrixCompute.buildProductGraphRC(gm, left, right, targetThreadCount-2);
// int x = colResults.length;
// PipeCleanerStage[] watches = new PipeCleanerStage[colResults.length];
// while (--x>=0) {
// watches[x] = new PipeCleanerStage<>(gm, colResults[x]);
ColumnsToRowsStage<M> ctr = new ColumnsToRowsStage(gm, colResults, result);
//ByteArrayOutputStream baos = new ByteArrayOutputStream();
//ConvertToDecimalStage<MatrixSchema> convert = new ConvertToDecimalStage<MatrixSchema>(gm, resultSchema, result, result2);
//ConsoleJSONDumpStage<?> watch = new ConsoleJSONDumpStage<>(gm, result , new PrintStream(baos));
// ConsoleSummaryStage<RowSchema<MatrixSchema>> watch = new ConsoleSummaryStage<>(gm, result);
PipeCleanerStage watch = new PipeCleanerStage<>(gm, result);
GraphManager.enableBatching(gm);
//gm.exportGraphDotFile();//TODO: this may not work and cause issues.
//MonitorConsoleStage.attach(gm);
StageScheduler scheduler = new ThreadPerStageScheduler(gm);
//new FixedThreadsScheduler(gm, targetThreadCount);
scheduler.startup();
int testSize = 100;//5000;
int k = testSize;
long timeout = 0;
while (--k>=0) {
timeout = System.currentTimeMillis()+5000;
for(int c=0;c<rightRows;c++) {
while (!Pipe.hasRoomForWrite(right)) {
Thread.yield();
if (System.currentTimeMillis()>timeout) {
scheduler.shutdown();
scheduler.awaitTermination(20, TimeUnit.SECONDS);
System.err.println("A, unable to write all of test data!");
return;
}
}
Pipe.addMsgIdx(right, resultSchema.rowId);
for(int r=0;r<rightColumns;r++) {
type.addValue(c, right);
}
Pipe.confirmLowLevelWrite(right, Pipe.sizeOf(right, resultSchema.rowId));
Pipe.publishWrites(right);
}
for(int c=0;c<leftRows;c++) {
while (!Pipe.hasRoomForWrite(left)) {
Thread.yield();
if (System.currentTimeMillis()>timeout) {
scheduler.shutdown();
scheduler.awaitTermination(20, TimeUnit.SECONDS);
System.err.println("B, unable to write all of test data!");
return;
}
}
Pipe.addMsgIdx(left, resultSchema.rowId);
for(int r=0;r<leftColumns;r++) {
type.addValue(r, left);
}
Pipe.confirmLowLevelWrite(left, Pipe.sizeOf(left, resultSchema.rowId));
Pipe.publishWrites(left);
}
}
if (k<0) {
//only works because we have multiple threads in play
while (!Pipe.hasRoomForWrite(left, Pipe.EOF_SIZE)) {
Pipe.spinWork(left);
}
while (!Pipe.hasRoomForWrite(right, Pipe.EOF_SIZE)) {
Pipe.spinWork(right);
}
Pipe.publishEOF(left);
Pipe.publishEOF(right);
}
if (GraphManager.blockUntilStageBeginsShutdown(gm, watch, 6000)) {//timeout in ms
} else {
System.err.println("time out!");
}
scheduler.shutdown();
//all the requests have now been sent.
// int w = watches.length;
// while (--w>=0) {
// if (!GraphManager.blockUntilStageBeginsShutdown(gm, watches[w], 5000)) {//timeout in ms
// System.err.println("ERROR SHUTDOWN");
// System.exit(-1);
scheduler.awaitTermination(10, TimeUnit.SECONDS);
// System.out.println("len "+baos.toByteArray().length+" "+new String(baos.toByteArray()));
}
}
|
package com.example.android.pets.data;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.net.Uri;
public class PetProvider extends ContentProvider {
/**
* URI matcher code for the content URI for the pets table.
*/
private static final int PETS = 100;
/**
* URI matcher code for the content URI for a single pet in the pets table.
*/
private static final int PET_ID = 101;
/**
* UriMatcher object to match a content URI to a corresponding code. The input passed into the
* constructor represents the code to return for the root URI. It's common to use NO_MATCH as
* the input for this case.
*/
private static final UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
/**
* Static initializer. This is run the first time anything is called from this class.
*/
static {
/**
* The calls to addURI() go here, for all of the content URI patterns that the provider
* should recognise. All paths added to the UriMatcher have a corresponding code to return
* when a match is found.
*/
/**
* The content URI fo the form "content://com.example.android.pets/pets" will map to the
* integer code {@link #PETS}. This URI is used to provide access to MULTIPLE rows of the
* pets table.
*/
uriMatcher.addURI(PetContract.CONTENT_AUTHORITY, PetContract.PATH_PETS, PETS);
/**
* The content URI of the form "content://com.example.android.pets/pets/#" will map to the
* integer code {@link #PET_ID}. This URI is used to proivde access to ONE single row of the
* pets table.
*
* In this case, the "#" wildcard is used where "#" can be substituted for an integer. For
* example, "content://com.exammple.android.pets/pets/3" matches, but
* "content://com.example.android.pets/pets" (without a number at the end) doesn't match.
*/
uriMatcher.addURI(PetContract.CONTENT_AUTHORITY, PetContract.PATH_PETS + "/#", PET_ID);
}
/**
* Database helper object
*/
private PetDbHelper dbHelper;
/**
* Tag for the log messages
*/
public static final String LOG_TAG = PetProvider.class.getSimpleName();
/**
* Initialise the provider and the database helper object.
*
* @return true
*/
@Override
public boolean onCreate() {
dbHelper = new PetDbHelper(getContext());
return true;
}
/**
* Perform the query for the given URI. Use the given projection, selection arguments, and sort
* order.
*
* @param uri is the given URI
* @param projection is the given projection
* @param selection is the selection
* @param selectionArgs are the selection arguments
* @param sortOrder is the given sort order
* @return null
*/
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
return null;
}
/**
* Returns the MIME type of data for the content URI
*
* @param uri is the content URI
* @return null
*/
@Override
public String getType(Uri uri) {
return null;
}
/**
* Insert new data into the provider with the given ContentValues
*
* @param uri is the given URI
* @param contentValues are the given content values
* @return null
*/
@Override
public Uri insert(Uri uri, ContentValues contentValues) {
return null;
}
/**
* Delete the data at the given selection and selection arguments.
*
* @param uri is the given URI
* @param selection is the given selection
* @param selectionArgs is an array of the given selection arguments.
* @return 0
*/
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
return 0;
}
/**
* Updates the data at the given selection and selection arguments, with the new ContentValues.
*
* @param uri is the given URI
* @param contentValues are the new content values
* @param selection is the given selection
* @param selectionArgs is an array of the given selection arguments
* @return 0
*/
@Override
public int update(Uri uri, ContentValues contentValues, String selection,
String[] selectionArgs) {
return 0;
}
}
|
package com.example.hai.eventfinder;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.util.Log;
import android.util.EventLog;
import com.ramotion.foldingcell.FoldingCell;
import java.util.ArrayList;
import java.util.List;
/**
* A simple {@link Fragment} subclass.
*/
public class EventFragment extends Fragment {
ListView listView;
ArrayList<Event> arrayList;
myFoldingCellListAdapter adapter;
public EventFragment() {
// Required empty public constructor
}
public static EventFragment newInstance(){
return new EventFragment();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_event, container, false);
//final ArrayList<Event> arrayList = new ArrayList<Event>();
arrayList = new ArrayList<Event>();
listView = (ListView) v.findViewById(R.id.listView);
//final myFoldingCellListAdapter adapter = new myFoldingCellListAdapter(v.getContext(), 0, arrayList);
Activity mainActivity = getActivity();
adapter = new myFoldingCellListAdapter(v.getContext(), 0, arrayList , mainActivity);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("I've been toggled" , "true");
// toggle clicked cell state
((FoldingCell) view).toggle(false);
// register in adapter that state for selected cell is toggled
adapter.registerToggle(position);
}
});
listView.setRecyclerListener(ViewHolder.mRecycleListener);
/*
MainActivity myParent = (MainActivity)getActivity();
this.updateAdapter(myParent.getUserLocation().latitude , myParent.getUserLocation().longitude);
*/
/*
ASYNCparams eventArgs = new ASYNCparams(0 , arrayList , this.getContext() , adapter );
EventRequestAsyncTask BriteRequest = new EventRequestAsyncTask();
BriteRequest.execute(eventArgs);
*/
return v;
}
public void updateAdapter(double lat , double lon) {
ASYNCparams eventArgs = new ASYNCparams(0, arrayList, this.getContext(), adapter , lat, lon);
EventRequestAsyncTask BriteRequest = new EventRequestAsyncTask(this.getContext());
UserEventAsyncTask UserRequest = new UserEventAsyncTask(this.getContext() , BriteRequest);
UserRequest.execute(eventArgs);
//BriteRequest.execute(eventArgs);
}
}
|
package com.example.kanjuice.utils;
import com.example.kanjuice.R;
import java.util.HashMap;
public class JuiceDecorator {
private static HashMap<String, Integer> imageIdMap;
private static HashMap<String, Integer> kanTextMap;
static {
imageIdMap = new HashMap<>();
imageIdMap.put("tea", R.drawable.tea);
imageIdMap.put("lemon tea", R.drawable.lemon_tea);
imageIdMap.put("ginger tea", R.drawable.ginger_tea);
imageIdMap.put("coffee", R.drawable.coffee);
imageIdMap.put("almond milk", R.drawable.almond);
imageIdMap.put("register user",R.drawable.register_user);
imageIdMap.put("buttermilk", R.drawable.buttermilk);
kanTextMap = new HashMap<>();
kanTextMap.put("tea", R.string.tea);
kanTextMap.put("lemon tea", R.string.lemon_tea);
kanTextMap.put("ginger tea", R.string.ginger_tea);
kanTextMap.put("coffee", R.string.coffee);
kanTextMap.put("almond milk", R.string.almond_milk);
kanTextMap.put("buttermilk", R.string.buttermilk);
}
public static int matchImage(String name) {
Integer id = imageIdMap.get(name.toLowerCase().trim());
if (id == null) {
id = R.drawable.tea;
}
return id;
}
public static int matchKannadaName(String name) {
Integer id = kanTextMap.get(name.toLowerCase().trim());
if (id == null) {
id = R.string.unknown_kan;
}
return id;
}
}
|
package com.example.pac.pacman.views;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import com.example.pac.pacman.event.DrawRequestEvent;
import com.example.pac.pacman.event.DummyEventManager;
import com.example.pac.pacman.event.EventListener;
import com.example.pac.pacman.event.IEventManager;
import com.example.pac.pacman.event.InitEvent;
import com.example.pac.pacman.event.InvalidateViewEvent;
import com.example.pac.pacman.event.PacManDirectionRequestEvent;
import java.util.ArrayList;
import java.util.Collection;
public class GameplayView extends View {
private static final int MARGIN = 10;
private RectF getInnerBounds(int w, int h) {
return new RectF(MARGIN, MARGIN, w - MARGIN, h - MARGIN);
}
public GameplayView(Context context) {
super(context);
}
public GameplayView(Context context, AttributeSet attrs) {
super(context, attrs);
}
private IEventManager _eventManager = new DummyEventManager();
private Collection<IChildView> _childViews = new ArrayList<IChildView>();
public void init(IEventManager eventManager, Collection<IChildView> childViews) {
_eventManager = eventManager;
_eventManager.registerObserver(InvalidateViewEvent.class,
new EventListener<InvalidateViewEvent>() {
@Override
public void onEvent(InvalidateViewEvent event) {
invalidate(event.GetRect());
}
});
_childViews = childViews;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
for (IChildView view : _childViews) {
view.draw(canvas);
}
}
@SuppressLint("ClickableViewAccessibility")
@Override
public boolean onTouchEvent(MotionEvent event) {
// Act only on ACTION_UP - should be good enough for touch and wipe
if (event.getAction() == MotionEvent.ACTION_UP) {
_eventManager.fire(new PacManDirectionRequestEvent(event.getX(), event.getY()));
}
return true;
}
@Override
protected void onSizeChanged(int w, int h, int _, int __) {
RectF bounds = getInnerBounds(w, h);
_eventManager.fire(new InitEvent(bounds));
}
}
|
package com.fallenritemonk.numbers.game;
import android.content.DialogInterface;
import android.graphics.Color;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.fallenritemonk.numbers.R;
import com.fallenritemonk.numbers.db.DatabaseHelper;
import com.tapfortap.sdk.Interstitial;
import com.tapfortap.sdk.TapForTap;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
class GameField extends BaseAdapter {
private final GameActivity activity;
private final FloatingActionButton addFieldsButton;
private final TextView headerCombos;
private final GameModeEnum gameMode;
private final DatabaseHelper dbHelper;
private ArrayList<NumberField> fieldArray;
private ArrayList<CombinePos> possibilities = new ArrayList<>();
private int selectedField;
private int hint;
private int stateOrder;
private Interstitial interstitial;
Interstitial.InterstitialListener interstitialListener;
private boolean showAd = true;
private int tryAdReload;
public GameField(final GameActivity activity, FloatingActionButton addFieldsButton, TextView headerCombos, GameModeEnum gameMode, Boolean resume) {
this.activity = activity;
this.addFieldsButton = addFieldsButton;
this.headerCombos = headerCombos;
this.gameMode = gameMode;
dbHelper = DatabaseHelper.getInstance(activity);
if (resume) {
resumeGame();
} else {
newGame();
}
interstitialListener = new Interstitial.InterstitialListener() {
@Override
public void interstitialDidReceiveAd(Interstitial interstitial) {
Log.i("GAME_ADS", "interstitialDidReceiveAd");
tryAdReload = 0;
}
@Override
public void interstitialDidFail(Interstitial interstitial, String reason, Throwable throwable) {
Log.i("GAME_ADS", "interstitialDidFail because: " + reason);
if (tryAdReload++ < 5) {
interstitial.load();
}
}
@Override
public void interstitialDidShow(Interstitial interstitial) {
Log.i("GAME_ADS", "interstitialDidShow");
}
@Override
public void interstitialWasTapped(Interstitial interstitial) {
Log.i("GAME_ADS", "interstitialWasTapped");
}
@Override
public void interstitialWasDismissed(Interstitial interstitial) {
Log.i("GAME_ADS", "interstitialWasDismissed");
}
@Override
public void interstitialAdWasRewarded(Interstitial interstitial) {
Log.i("GAME_ADS", "interstitialAdWasRewarded");
}
};
try {
interstitial = Interstitial.loadBreakInterstitial(activity, interstitialListener);
showAd = true;
} catch (Exception e) {
showAd = false;
}
}
public void newGame() {
fieldArray = new ArrayList<>();
fieldArray.add(new NumberField(1));
fieldArray.add(new NumberField(2));
fieldArray.add(new NumberField(3));
fieldArray.add(new NumberField(4));
fieldArray.add(new NumberField(5));
fieldArray.add(new NumberField(6));
fieldArray.add(new NumberField(7));
fieldArray.add(new NumberField(8));
fieldArray.add(new NumberField(9));
fieldArray.add(new NumberField(1));
fieldArray.add(new NumberField(1));
fieldArray.add(new NumberField(1));
fieldArray.add(new NumberField(2));
fieldArray.add(new NumberField(1));
fieldArray.add(new NumberField(3));
fieldArray.add(new NumberField(1));
fieldArray.add(new NumberField(4));
fieldArray.add(new NumberField(1));
fieldArray.add(new NumberField(5));
fieldArray.add(new NumberField(1));
fieldArray.add(new NumberField(6));
fieldArray.add(new NumberField(1));
fieldArray.add(new NumberField(7));
fieldArray.add(new NumberField(1));
fieldArray.add(new NumberField(8));
fieldArray.add(new NumberField(1));
fieldArray.add(new NumberField(9));
if (gameMode == GameModeEnum.RANDOM) {
Collections.shuffle(fieldArray, new Random(System.nanoTime()));
}
notifyDataSetChanged();
selectedField = -1;
hint = -1;
stateOrder = -1;
findPossibilities();
dbHelper.clearDB();
saveState();
}
private void resumeGame() {
fieldsFromString(dbHelper.getLastState());
selectedField = -1;
hint = -1;
stateOrder = dbHelper.getLastStateOrder();
findPossibilities();
}
private void findPossibilities() {
hint = -1;
possibilities = new ArrayList<>();
for (int i = 0; i < fieldArray.size() - 1; i++) {
if (fieldArray.get(i).getState() == NumberField.STATE.USED) continue;
for (int ii = i + 1; ii < fieldArray.size(); ii++) {
if (fieldArray.get(ii).getState() == NumberField.STATE.USED) continue;
if (canBeCombined(i, ii)) {
possibilities.add(new CombinePos(i, ii));
}
break;
}
for (int ii = i + 9; ii < fieldArray.size(); ii += 9) {
if (fieldArray.get(ii).getState() == NumberField.STATE.USED) continue;
if (canBeCombined(i, ii)) {
possibilities.add(new CombinePos(i, ii));
}
break;
}
}
if (possibilities.size() == 0)
addFieldsButton.setVisibility(View.VISIBLE);
else addFieldsButton.setVisibility(View.GONE);
}
private boolean canBeCombined(int id1, int id2) {
return id1 != id2 && !(fieldArray.get(id1).getNumber() + fieldArray.get(id2).getNumber() != 10 && fieldArray.get(id1).getNumber() != fieldArray.get(id2).getNumber());
}
public void hint() {
if (showAd && interstitial.isReadyToShow()) {
interstitial.show();
}
try {
interstitial = Interstitial.loadBreakInterstitial(activity, interstitialListener);
showAd = true;
} catch (Exception e) {
showAd = false;
}
if (possibilities.size() == 0) return;
if (hint >= 0) {
fieldArray.get(possibilities.get(hint).getId1()).setState(NumberField.STATE.UNUSED);
fieldArray.get(possibilities.get(hint).getId2()).setState(NumberField.STATE.UNUSED);
}
hint = ++hint % possibilities.size();
fieldArray.get(possibilities.get(hint).getId1()).setState(NumberField.STATE.HINT);
fieldArray.get(possibilities.get(hint).getId2()).setState(NumberField.STATE.HINT);
notifyDataSetChanged();
}
public void undo() {
if (dbHelper.undo()) {
if (showAd && interstitial.isReadyToShow()) {
interstitial.show();
}
try {
interstitial = Interstitial.loadBreakInterstitial(activity, interstitialListener);
showAd = true;
} catch (Exception e) {
showAd = false;
}
resumeGame();
}
}
public void clicked(int id) {
if (fieldArray.get(id).getState() == NumberField.STATE.USED) return;
if (selectedField == -1) {
selectedField = id;
fieldArray.get(id).setState(NumberField.STATE.SELECTED);
notifyDataSetChanged();
} else if (id == selectedField) {
fieldArray.get(id).setState(NumberField.STATE.UNUSED);
selectedField = -1;
notifyDataSetChanged();
} else {
combine(id);
}
}
private void combine(int id) {
boolean combined = false;
for (CombinePos pos : possibilities) {
if (pos.equals(new CombinePos(id, selectedField))) {
fieldArray.get(id).setState(NumberField.STATE.USED);
fieldArray.get(selectedField).setState(NumberField.STATE.USED);
if (reduceFields()) {
won();
} else {
saveState();
findPossibilities();
}
selectedField = -1;
combined = true;
break;
}
}
if (!combined) {
fieldArray.get(selectedField).setState(NumberField.STATE.UNUSED);
selectedField = -1;
}
notifyDataSetChanged();
}
private boolean reduceFields() {
ArrayList<NumberField> deleteList = new ArrayList<>();
int preLeft = -1;
for (int i = 0; i < fieldArray.size(); i += 9) {
preLeft = reduceRow(i, preLeft, deleteList);
}
fieldArray.removeAll(deleteList);
return fieldArray.isEmpty();
}
private int reduceRow(int index, int preLeft, ArrayList<NumberField> deleteList) {
boolean empty = true;
int left = -1;
int right = -1;
for (int ii = 0; ii < 9 && index + ii < fieldArray.size(); ii++) {
if (fieldArray.get(index + ii).getState() != NumberField.STATE.USED) {
empty = false;
left = ii;
if (right == -1) right = ii;
}
}
if (empty && index + 8 < fieldArray.size()) {
deleteNine(index, deleteList);
} else if (preLeft != -1 && right > preLeft) {
deleteNine(index - 8 + preLeft, deleteList);
} else if (empty && index == deleteList.size()) {
fieldArray.clear();
}
return left;
}
private void deleteNine(int index, ArrayList<NumberField> deleteList) {
ArrayList<NumberField> tempList = new ArrayList<>();
for (int i = 0; i < 9; i++) {
if (deleteList.contains(fieldArray.get(index + i))) {
return;
} else {
tempList.add(fieldArray.get(index + i));
}
}
deleteList.addAll(tempList);
}
public void addFields() {
ArrayList<NumberField> tempField = new ArrayList<>();
for (NumberField field : fieldArray) {
if (field.getState() != NumberField.STATE.USED) {
tempField.add(new NumberField(field.getNumber()));
}
}
fieldArray.addAll(tempField);
notifyDataSetChanged();
findPossibilities();
}
private String fieldsToString() {
String stringified = "";
for (NumberField field : fieldArray) {
stringified += field.stringify() + ",";
}
stringified = stringified.substring(0, stringified.length() - 1);
return stringified;
}
private void fieldsFromString(String string) {
fieldArray = new ArrayList<>();
String[] tempFieldArray = string.split(",");
for (String tempField : tempFieldArray) {
fieldArray.add(new NumberField(tempField));
}
notifyDataSetChanged();
}
private void saveState() {
dbHelper.saveState(++stateOrder, fieldsToString());
headerCombos.setText(String.valueOf(stateOrder));
}
private void won() {
stateOrder += 1;
activity.gameWon(gameMode, stateOrder);
dbHelper.clearDB();
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle(R.string.game_won);
builder.setPositiveButton(R.string.confirm_restart_title, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
newGame();
}
});
builder.setNegativeButton(R.string.menu, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
activity.finish();
}
});
AlertDialog dialog = builder.create();
dialog.setCancelable(false);
dialog.show();
}
@Override
public int getCount() {
return fieldArray.size();
}
@Override
public Object getItem(int i) {
return null;
}
@Override
public long getItemId(int i) {
return 0;
}
@Override
public View getView(int i, final View view, ViewGroup viewGroup) {
TextView textView;
if (view == null) {
textView = new TextView(activity);
textView.setTextColor(Color.WHITE);
textView.setTextSize(25);
textView.setGravity(Gravity.CENTER_HORIZONTAL);
AbsListView.LayoutParams params = new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT, AbsListView.LayoutParams.MATCH_PARENT);
textView.setLayoutParams(params);
} else {
textView = (TextView) view;
}
textView.setText("" + fieldArray.get(i).getNumber());
textView.setAlpha(1);
switch (fieldArray.get(i).getState()) {
case USED: textView.setAlpha(0.2f); textView.setText("");
case UNUSED: textView.setBackgroundColor(Color.BLACK); break;
case SELECTED: textView.setBackgroundColor(Color.BLUE); break;
case HINT: textView.setBackgroundColor(Color.GREEN); break;
}
return textView;
}
}
|
package com.malmstein.hnews.feed;
import com.malmstein.hnews.tasks.FetchShowHNTask;
import java.io.IOException;
import rx.Observable;
import rx.Subscriber;
import rx.schedulers.Schedulers;
public class StoriesRetriever implements Retriever<StoriesUpdateEvent> {
private final DatabasePersister databasePersister;
public StoriesRetriever(DatabasePersister databasePersister) {
this.databasePersister = databasePersister;
}
@Override
public Observable<StoriesUpdateEvent> fetch(Long... params) {
return Observable.create(new StoriesUpdateOnSubscribe(databasePersister))
.subscribeOn(Schedulers.io());
}
private static class StoriesUpdateOnSubscribe implements Observable.OnSubscribe<StoriesUpdateEvent> {
private final DatabasePersister databasePersister;
private Subscriber<? super StoriesUpdateEvent> subscriber;
private StoriesUpdateOnSubscribe(DatabasePersister databasePersister) {
this.databasePersister = databasePersister;
}
@Override
public void call(Subscriber<? super StoriesUpdateEvent> subscriber) {
this.subscriber = subscriber;
try {
startFetchingTopsStories();
} catch (IOException e) {
this.subscriber.onError(e);
}
this.subscriber.onCompleted();
}
private void startFetchingTopsStories() throws IOException {
subscriber.onNext(new StoriesUpdateEvent(StoriesUpdateEvent.Type.REFRESH_STARTED));
createFetchTopStoriesTask().execute();
subscriber.onNext(new StoriesUpdateEvent(StoriesUpdateEvent.Type.REFRESH_FINISHED));
}
private FetchShowHNTask createFetchTopStoriesTask() {
return new FetchShowHNTask(databasePersister);
}
}
}
|
package com.nathanosman.chronosnap;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.hardware.Camera;
import android.os.Build;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.widget.Toast;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Captures images at the predefined interval
*
* Capture parameters are initialized at the beginning of the capture.
*/
public class CaptureService extends Service {
/**
* Broadcast the current status of the capture
*/
public static final String ACTION_BROADCAST_STATUS = "com.nathanosman.chronosnap.action.BROADCAST_STATUS";
/**
* Start capturing a sequence
*/
public static final String ACTION_START_CAPTURE = "com.nathanosman.chronosnap.action.START_CAPTURE";
/**
* Explicitly stop capturing a sequence
*/
public static final String ACTION_STOP_CAPTURE = "com.nathanosman.chronoshap.action.STOP_CAPTURE";
/**
* Capture the next image in the sequence
* <p/>
* This action is triggered by an alarm set to the appropriate interval
* and therefore can only be sent from within the service.
*/
private static final String ACTION_CAPTURE = "com.nathanosman.chronosnap.action.CAPTURE";
/**
* Broadcast containing capture status
*/
public static final String BROADCAST_STATUS = "com.nathanosman.chronosnap.broadcast.STATUS";
/**
* Start time of the capture
*/
public static final String EXTRA_START_TIME = "com.nathanosman.chronosnap.extra.START_TIME";
/**
* Number of images captured so far
*/
public static final String EXTRA_IMAGES_CAPTURED = "com.nathanosman.chronosnap.extra.IMAGES_CAPTURED";
/**
* Number of images remaining to be captured (0 if not limit)
*/
public static final String EXTRA_IMAGES_REMAINING = "com.nathanosman.chronosnap.extra.IMAGES_REMAINING";
// Alarm manager and intent for triggering a capture
private AlarmManager mAlarmManager;
private PendingIntent mCaptureIntent;
// Data initialized when the capture begins
private long mStartTime;
private long mInterval;
private int mIndex;
private int mLimit;
// Used for capturing the images
private ImageCapturer mImageCapturer;
/**
* Reimplementation of Service.onCreate()
*/
@Override
public void onCreate() {
mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
mCaptureIntent = PendingIntent.getService(this, 0,
new Intent(this, CaptureService.class).setAction(ACTION_CAPTURE), 0);
}
/**
* Reimplementation of Service.onStartCommand()
*/
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO: figure out why the intent is sometimes NULL
if (intent != null) {
// Dispatch the command to the appropriate method
final String action = intent.getAction();
switch (action) {
case ACTION_BROADCAST_STATUS:
broadcastStatus();
break;
case ACTION_START_CAPTURE:
startCapture();
break;
case ACTION_STOP_CAPTURE:
stopCapture();
break;
case ACTION_CAPTURE:
capture();
break;
}
}
return START_STICKY;
}
/**
* Not implemented
*/
@Override
public IBinder onBind(Intent intent) {
return null;
}
/**
* Send a broadcast with current status
*/
private void broadcastStatus() {
Intent intent = new Intent(BROADCAST_STATUS);
intent.putExtra(EXTRA_START_TIME, mStartTime);
intent.putExtra(EXTRA_IMAGES_CAPTURED, mIndex);
intent.putExtra(EXTRA_IMAGES_REMAINING, mLimit == 0 ? 0 : mLimit - mIndex);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
/**
* Start capturing a sequence of images
*/
@SuppressWarnings("deprecation")
private void startCapture() {
log("Starting image capture.");
// Indicate that this is a foreground service by creating a persistent
// notification displayed while the capture is in progress
Intent intent = new Intent(this, MainActivity.class);
Notification notification = new Notification.Builder(this)
.setContentTitle(getText(R.string.notification_title))
.setContentText(getText(R.string.notification_text))
.setSmallIcon(R.drawable.ic_stat_notify)
.setContentIntent(PendingIntent.getActivity(this, 0, intent, 0))
.getNotification();
startForeground(1, notification);
// Set the start time and reset the index
mStartTime = System.currentTimeMillis();
mIndex = 0;
// Load the current settings
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
mInterval = Long.parseLong(sharedPreferences.getString("interval", ""));
mLimit = Integer.parseInt(sharedPreferences.getString("limit", ""));
// TODO: load focus setting
// Generate a name for the sequence based on the current date and time
int cameraId = Integer.parseInt(sharedPreferences.getString("camera", ""));
// TODO: user should be able to select the sequence name
String sequenceName = new SimpleDateFormat("yyyymmdd_hhmmss").format(new Date());
// Initialize the capturer
mImageCapturer = new ImageCapturer(cameraId, sequenceName);
// Broadcast the new status (that the capture has started) and set an alarm
broadcastStatus();
setAlarm();
}
/**
* Stop capturing a sequence of images
*/
private void stopCapture() {
log("Stopping image capture.");
// TODO: this currently cannot cancel an image capture in progress
// Cancel any pending capture intents and leave the foreground
mAlarmManager.cancel(mCaptureIntent);
stopForeground(true);
// Reset the start time (to indicate no transfer) and broadcast this status
mStartTime = 0;
broadcastStatus();
// Stop the service
stopSelf();
}
/**
* Capture a single image
*/
private void capture() {
log("Capturing image #" + String.valueOf(mIndex) + ".");
mImageCapturer.startCapture(mIndex, new ImageCapturer.CaptureCallback() {
@Override
public void onSuccess() {
log("Image #" + String.valueOf(mIndex) + " captured.");
// Increment the counter and broadcast the status
mIndex++;
broadcastStatus();
// Check to see if more images should be captured (and set the alarm)
// or if the limit was reached (and the capture may be stopped
if (mLimit == 0 || mIndex < mLimit) {
// TODO: this should be a configurable setting
mImageCapturer.close();
setAlarm();
} else {
stopCapture();
}
}
@Override
public void onError(String description) {
log("Error: " + description);
// Inform the user that an error has occurred during capture
Toast.makeText(CaptureService.this, R.string.toast_error_storage_img,
Toast.LENGTH_LONG).show();
// Stop the capture
stopCapture();
}
});
}
/**
* Set the alarm for the next capture
*/
private void setAlarm() {
long triggerAtMillis = System.currentTimeMillis() + mInterval;
// For KitKat and newer devices, we need to use setExact or we don't
// end up with the same level of precision as earlier versions
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
mAlarmManager.setExact(AlarmManager.RTC_WAKEUP, triggerAtMillis, mCaptureIntent);
} else {
mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerAtMillis, mCaptureIntent);
}
}
/**
* Log the specified message
*/
private void log(String message) {
Log.d(CaptureService.class.getSimpleName(), message);
}
}
|
package com.nutomic.syncthingandroid.model;
import android.text.TextUtils;
import com.nutomic.syncthingandroid.service.Constants;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class Folder {
public String id;
public String label;
public String filesystemType = "basic";
public String path;
public String type = Constants.FOLDER_TYPE_SEND_RECEIVE;
public boolean fsWatcherEnabled = true;
public int fsWatcherDelayS = 10;
private List<Folder.Device> devices = new ArrayList<>();
public int rescanIntervalS;
public final boolean ignorePerms = true;
public boolean autoNormalize = true;
public MinDiskFree minDiskFree;
public Versioning versioning;
public int copiers;
public int pullerMaxPendingKiB;
public int hashers;
public String order;
public boolean ignoreDelete;
public int scanProgressIntervalS;
public int pullerPauseS;
public int maxConflicts = 10;
public boolean disableSparseFiles;
public boolean disableTempIndexes;
public boolean paused;
public boolean useLargeBlocks;
public int weakHashThresholdPct = 25;
public String markerName = ".stfolder";
public String invalid;
public static class Versioning implements Serializable {
public String type;
public Map<String, String> params = new HashMap<>();
}
public static class MinDiskFree {
public float value;
public String unit;
}
public void addDevice(String deviceId) {
Device d = new Device();
d.deviceID = deviceId;
devices.add(d);
}
public Device getDevice(String deviceId) {
for (Device d : devices) {
if (d.deviceID.equals(deviceId)) {
return d;
}
}
return null;
}
public void removeDevice(String deviceId) {
for (Iterator<Device> it = devices.iterator(); it.hasNext();) {
String currentId = it.next().deviceID;
if (currentId.equals(deviceId)) {
it.remove();
}
}
}
@Override
public String toString() {
return !TextUtils.isEmpty(label) ? label : id;
}
public class Device {
public String deviceID;
public String introducedBy;
public String encryptionPassword;
}
}
|
package durdinapps.rxfirebase2;
import android.support.annotation.NonNull;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.MutableData;
import com.google.firebase.database.Query;
import com.google.firebase.database.Transaction;
import com.google.firebase.database.ValueEventListener;
import java.util.Iterator;
import java.util.Map;
import durdinapps.rxfirebase2.exceptions.RxFirebaseDataException;
import io.reactivex.BackpressureStrategy;
import io.reactivex.Completable;
import io.reactivex.CompletableEmitter;
import io.reactivex.CompletableOnSubscribe;
import io.reactivex.Flowable;
import io.reactivex.FlowableEmitter;
import io.reactivex.FlowableOnSubscribe;
import io.reactivex.Maybe;
import io.reactivex.MaybeEmitter;
import io.reactivex.MaybeOnSubscribe;
import io.reactivex.MaybeSource;
import io.reactivex.Single;
import io.reactivex.SingleEmitter;
import io.reactivex.SingleOnSubscribe;
import io.reactivex.functions.Cancellable;
import io.reactivex.functions.Function;
import static durdinapps.rxfirebase2.DataSnapshotMapper.DATA_SNAPSHOT_EXISTENCE_PREDICATE;
public class RxFirebaseDatabase {
/**
* Listener for changes in te data at the given query location.
*
* @param query reference represents a particular location in your Database and can be used for reading or writing data to that Database location.
* @param strategy {@link BackpressureStrategy} associated to this {@link Flowable}
* @return a {@link Flowable} which emits when a value of the database change in the given query.
*/
@NonNull
public static Flowable<DataSnapshot> observeValueEvent(@NonNull final Query query,
@NonNull BackpressureStrategy strategy) {
return Flowable.create(new FlowableOnSubscribe<DataSnapshot>() {
@Override
public void subscribe(final FlowableEmitter<DataSnapshot> emitter) throws Exception {
final ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
emitter.onNext(dataSnapshot);
} else {
emitter.onComplete();
}
}
@Override
public void onCancelled(final DatabaseError error) {
emitter.onError(new RxFirebaseDataException(error));
}
};
emitter.setCancellable(new Cancellable() {
@Override
public void cancel() throws Exception {
query.removeEventListener(valueEventListener);
}
});
query.addValueEventListener(valueEventListener);
}
}, strategy);
}
/**
* Listener for a single change in te data at the given query location.
*
* @param query reference represents a particular location in your Database and can be used for reading or writing data to that Database location.
* @return a {@link Maybe} which emits the actual state of the database for the given query. onSuccess will be only call when
* the given {@link DataSnapshot} exists.
*/
@NonNull
public static Maybe<DataSnapshot> observeSingleValueEvent(@NonNull final Query query) {
return Maybe.create(new MaybeOnSubscribe<DataSnapshot>() {
@Override
public void subscribe(final MaybeEmitter<DataSnapshot> emitter) throws Exception {
query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
emitter.onSuccess(dataSnapshot);
}
emitter.onComplete();
}
@Override
public void onCancelled(DatabaseError error) {
emitter.onError(new RxFirebaseDataException(error));
}
});
}
});
}
/**
* Run a transaction on the data at this location. For more information on running transactions, see
*
* @param ref reference represents a particular location in your database.
* @param fireLocalEvents boolean which allow to receive calls of your transaction in your local device.
* @param transactionValue value of the transaction.
* @return a {@link Single} which emits the final {@link DataSnapshot} value if the transaction success.
*/
@NonNull
public static Single<DataSnapshot> runTransaction(@NonNull final DatabaseReference ref,
@NonNull final boolean fireLocalEvents,
@NonNull final long transactionValue) {
return Single.create(new SingleOnSubscribe<DataSnapshot>() {
@Override public void subscribe(final SingleEmitter emitter) throws Exception {
ref.runTransaction(new Transaction.Handler() {
@Override
public Transaction.Result doTransaction(MutableData mutableData) {
Integer currentValue = mutableData.getValue(Integer.class);
if (currentValue == null) {
mutableData.setValue(transactionValue);
} else {
mutableData.setValue(currentValue + transactionValue);
}
return Transaction.success(mutableData);
}
@Override
public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
if (databaseError != null) {
emitter.onError(new RxFirebaseDataException(databaseError));
} else {
emitter.onSuccess(dataSnapshot);
}
}
}, fireLocalEvents);
}
});
}
/**
* Set the given value on the specified {@link DatabaseReference}.
*
* @param ref reference represents a particular location in your database.
* @param value value to update.
* @return a {@link Completable} which is complete when the set value call finish successfully.
*/
@NonNull
public static Completable setValue(@NonNull final DatabaseReference ref,
final Object value) {
return Completable.create(new CompletableOnSubscribe() {
@Override
public void subscribe(@NonNull final CompletableEmitter e) throws Exception {
ref.setValue(value).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override public void onSuccess(Void aVoid) {
e.onComplete();
}
}).addOnFailureListener(new OnFailureListener() {
@Override public void onFailure(@NonNull Exception exception) {
e.onError(exception);
}
});
}
});
}
/**
* Update the specific child keys to the specified values.
*
* @param ref reference represents a particular location in your database.
* @param updateData The paths to update and their new values
* @return a {@link Completable} which is complete when the update children call finish successfully.
*/
@NonNull
public static Completable updateChildren(@NonNull final DatabaseReference ref,
@NonNull final Map<String, Object> updateData) {
return Completable.create(new CompletableOnSubscribe() {
@Override
public void subscribe(final CompletableEmitter emitter) throws Exception {
ref.updateChildren(updateData, new DatabaseReference.CompletionListener() {
@Override
public void onComplete(DatabaseError error, DatabaseReference databaseReference) {
if (error != null) {
emitter.onError(new RxFirebaseDataException(error));
} else {
emitter.onComplete();
}
}
});
}
});
}
/**
* Listener for for child events occurring at the given query location.
*
* @param query reference represents a particular location in your Database and can be used for reading or writing data to that Database location.
* @param strategy {@link BackpressureStrategy} associated to this {@link Flowable}
* @return a {@link Flowable} which emits when a value of a child int the database change on the given query.
*/
@NonNull
public static Flowable<RxFirebaseChildEvent<DataSnapshot>> observeChildEvent(
@NonNull final Query query, @NonNull BackpressureStrategy strategy) {
return Flowable.create(new FlowableOnSubscribe<RxFirebaseChildEvent<DataSnapshot>>() {
@Override
public void subscribe(final FlowableEmitter<RxFirebaseChildEvent<DataSnapshot>> emitter) throws Exception {
final ChildEventListener childEventListener = new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
emitter.onNext(
new RxFirebaseChildEvent<>(dataSnapshot.getKey(), dataSnapshot, previousChildName,
RxFirebaseChildEvent.EventType.ADDED));
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String previousChildName) {
emitter.onNext(
new RxFirebaseChildEvent<>(dataSnapshot.getKey(), dataSnapshot, previousChildName,
RxFirebaseChildEvent.EventType.CHANGED));
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
emitter.onNext(new RxFirebaseChildEvent<>(dataSnapshot.getKey(), dataSnapshot,
RxFirebaseChildEvent.EventType.REMOVED));
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) {
emitter.onNext(
new RxFirebaseChildEvent<>(dataSnapshot.getKey(), dataSnapshot, previousChildName,
RxFirebaseChildEvent.EventType.MOVED));
}
@Override
public void onCancelled(DatabaseError error) {
emitter.onError(new RxFirebaseDataException(error));
}
};
emitter.setCancellable(new Cancellable() {
@Override
public void cancel() throws Exception {
query.removeEventListener(childEventListener);
}
});
query.addChildEventListener(childEventListener);
}
}, strategy);
}
/**
* Method which retrieve a list of DataSnapshot from multiple {@link DatabaseReference}.
*
* @param whereRefs array of {@link DatabaseReference references.}
* @return a {@link Flowable} which emmit {@link DataSnapshot} from the given queries.
*/
@NonNull
public static Flowable<DataSnapshot> observeMultipleSingleValueEvent(@NonNull DatabaseReference... whereRefs) {
return Maybe.merge(Flowable.fromArray(whereRefs)
.map(new Function<DatabaseReference, MaybeSource<? extends DataSnapshot>>() {
@Override
public MaybeSource<? extends DataSnapshot> apply(@NonNull DatabaseReference databaseReference) throws
Exception {
return observeSingleValueEvent(databaseReference);
}
})
);
}
/**
* Retrieve the child {@link DatabaseReference references} from an specific parent which equals to the
* references retrieved from another query. Which allow to make a "where" clause on a no relational table.
* <p>
* Example:
* DatabaseReference from = reference.child("Tweets");
* Query where = reference.child("favorited").child(userA);
* requestFilteredReferenceKeys(from, where).subscribe...
* <p>
* This last method will return the key references(/tweets/tweetId) which the userA mark as favorited.
* With the given list we can work together with {@link RxFirebaseDatabase#observeMultipleSingleValueEvent(DatabaseReference...)}
* to retrieve the Datasnapshots from the desired {@link DatabaseReference} based on other {@link DatabaseReference} values.
*
* @param from base reference where you want to retrieve the original references.
* @param whereRef reference that you use as a filter to create your from references.
* @return a {@link Maybe} which contain the list of the given DatabaseReferences.
*/
@NonNull
public static Maybe<DatabaseReference[]> requestFilteredReferenceKeys(@NonNull final DatabaseReference from,
@NonNull Query whereRef) {
return observeSingleValueEvent(whereRef, new Function<DataSnapshot, DatabaseReference[]>() {
@Override
public DatabaseReference[] apply(@NonNull DataSnapshot dataSnapshot) throws Exception {
int childrenCount = (int) dataSnapshot.getChildrenCount();
DatabaseReference[] filterRefs = new DatabaseReference[childrenCount];
final Iterator<DataSnapshot> iterator = dataSnapshot.getChildren().iterator();
for (int i = 0; i < childrenCount; i++) {
filterRefs[i] = from.child(iterator.next().getKey());
}
return filterRefs;
}
});
}
/**
* Listener for changes in te data at the given query location.
*
* @param query reference represents a particular location in your Database and can be used for reading or writing data to that Database location.
* @param clazz class type for the {@link DataSnapshot} items.
* @param strategy {@link BackpressureStrategy} associated to this {@link Flowable}
* @return a {@link Flowable} which emits when a value of the database change in the given query.
*/
@NonNull
public static <T> Flowable<T> observeValueEvent(@NonNull final Query query,
@NonNull final Class<T> clazz,
@NonNull BackpressureStrategy strategy) {
return observeValueEvent(query, DataSnapshotMapper.of(clazz), strategy);
}
/**
* Listener for a single change in te data at the given query location.
*
* @param query reference represents a particular location in your Database and can be used for reading or writing data to that Database location.
* @param clazz class type for the {@link DataSnapshot} items.
* @return a {@link Maybe} which emits the actual state of the database for the given query.
*/
@NonNull
public static <T> Maybe<T> observeSingleValueEvent(@NonNull final Query query,
@NonNull final Class<T> clazz) {
return observeSingleValueEvent(query, DataSnapshotMapper.of(clazz));
}
/**
* Listener for for child events occurring at the given query location.
*
* @param query reference represents a particular location in your Database and can be used for reading or writing data to that Database location.
* @param clazz class type for the {@link DataSnapshot} items.
* @param strategy {@link BackpressureStrategy} associated to this {@link Flowable}
* @return a {@link Flowable} which emits when a value of a child int the database change on the given query.
*/
@NonNull
public static <T> Flowable<RxFirebaseChildEvent<T>> observeChildEvent(
@NonNull final Query query, @NonNull final Class<T> clazz,
@NonNull BackpressureStrategy strategy) {
return observeChildEvent(query, DataSnapshotMapper.ofChildEvent(clazz), strategy);
}
/**
* Listener for changes in te data at the given query location.
*
* @param query reference represents a particular location in your Database and can be used for reading or writing data to that Database location.
* @param mapper specific function to map the dispatched events.
* @param strategy {@link BackpressureStrategy} associated to this {@link Flowable}
* @return a {@link Flowable} which emits when a value of the database change in the given query.
*/
@NonNull
public static <T> Flowable<T> observeValueEvent(@NonNull final Query query,
@NonNull final Function<? super DataSnapshot, ? extends T> mapper,
@NonNull BackpressureStrategy strategy) {
return observeValueEvent(query, strategy).map(mapper);
}
/**
* Listener for a single change in te data at the given query location.
*
* @param query reference represents a particular location in your Database and can be used for reading or writing data to that Database location.
* @param mapper specific function to map the dispatched events.
* @return a {@link Maybe} which emits the actual state of the database for the given query.
*/
@NonNull
public static <T> Maybe<T> observeSingleValueEvent(@NonNull final Query query,
@NonNull final Function<? super DataSnapshot, ? extends T> mapper) {
return observeSingleValueEvent(query)
.filter(DATA_SNAPSHOT_EXISTENCE_PREDICATE)
.map(mapper);
}
/**
* Listener for for child events occurring at the given query location.
*
* @param query reference represents a particular location in your Database and can be used for reading or writing data to that Database location.
* @param mapper specific function to map the dispatched events.
* @param strategy {@link BackpressureStrategy} associated to this {@link Flowable}
* @return a {@link Flowable} which emits when a value of a child int the database change on the given query.
*/
@NonNull
public static <T> Flowable<RxFirebaseChildEvent<T>> observeChildEvent(
@NonNull final Query query, @NonNull final Function<? super RxFirebaseChildEvent<DataSnapshot>,
? extends RxFirebaseChildEvent<T>> mapper, @NonNull BackpressureStrategy strategy) {
return observeChildEvent(query, strategy).map(mapper);
}
/**
* Listener for changes in the data at the given query location.
*
* @param query reference represents a particular location in your Database and can be used for reading or writing data to that Database location.
* @return a {@link Flowable} which emits when a value of the database change in the given query.
*/
@NonNull
public static Flowable<DataSnapshot> observeValueEvent(@NonNull final Query query) {
return observeValueEvent(query, BackpressureStrategy.DROP);
}
/**
* Listener for for child events occurring at the given query location.
*
* @param query reference represents a particular location in your Database and can be used for reading or writing data to that Database location.
* @return a {@link Flowable} which emits when a value of a child int the database change on the given query.
*/
@NonNull
public static Flowable<RxFirebaseChildEvent<DataSnapshot>> observeChildEvent(
@NonNull final Query query) {
return observeChildEvent(query, BackpressureStrategy.DROP);
}
/**
* Run a transaction on the data at this location. For more information on running transactions, see
*
* @param ref reference represents a particular location in your database.
* @param transactionValue value of the transaction.
* @return a {@link Single} which emits the final {@link DataSnapshot} value if the transaction success.
*/
@NonNull
public static Single<DataSnapshot> runTransaction(@NonNull final DatabaseReference ref,
@NonNull final long transactionValue) {
return runTransaction(ref, true, transactionValue);
}
/**
* Listener for changes in te data at the given query location.
*
* @param query reference represents a particular location in your Database and can be used for reading or writing data to that Database location.
* @param clazz class type for the {@link DataSnapshot} items.
* @return a {@link Flowable} which emits when a value of the database change in the given query.
*/
@NonNull
public static <T> Flowable<T> observeValueEvent(@NonNull final Query query,
@NonNull final Class<T> clazz) {
return observeValueEvent(query, DataSnapshotMapper.of(clazz), BackpressureStrategy.DROP);
}
/**
* Listener for for child events occurring at the given query location.
*
* @param query reference represents a particular location in your Database and can be used for reading or writing data to that Database location.
* @param clazz class type for the {@link DataSnapshot} items.
* @return a {@link Flowable} which emits when a value of a child int the database change on the given query.
*/
@NonNull
public static <T> Flowable<RxFirebaseChildEvent<T>> observeChildEvent(
@NonNull final Query query, @NonNull final Class<T> clazz) {
return observeChildEvent(query, DataSnapshotMapper.ofChildEvent(clazz), BackpressureStrategy.DROP);
}
/**
* Listener for changes in te data at the given query location.
*
* @param query reference represents a particular location in your Database and can be used for reading or writing data to that Database location.
* @return a {@link Flowable} which emits when a value of the database change in the given query.
*/
@NonNull
public static <T> Flowable<T> observeValueEvent(@NonNull final Query query,
@NonNull final Function<? super DataSnapshot, ? extends T> mapper) {
return observeValueEvent(query, BackpressureStrategy.DROP).map(mapper);
}
/**
* Listener for for child events occurring at the given query location.
*
* @param query reference represents a particular location in your Database and can be used for reading or writing data to that Database location.
* @param mapper specific function to map the dispatched events.
* @return a {@link Flowable} which emits when a value of a child int the database change on the given query.
*/
@NonNull
public static <T> Flowable<RxFirebaseChildEvent<T>> observeChildEvent(
@NonNull final Query query, @NonNull final Function<? super RxFirebaseChildEvent<DataSnapshot>,
? extends RxFirebaseChildEvent<T>> mapper) {
return observeChildEvent(query, BackpressureStrategy.DROP).map(mapper);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.