repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
SimianArmy
SimianArmy-master/src/main/java/com/netflix/simianarmy/chaos/ChaosCrawler.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.simianarmy.chaos; import java.util.EnumSet; import java.util.List; import com.amazonaws.services.autoscaling.model.TagDescription; import com.netflix.simianarmy.GroupType; /** * The Interface ChaosCrawler. */ public interface ChaosCrawler { /** * The Interface InstanceGroup. */ public interface InstanceGroup { /** * Type. * * @return the group type enum */ GroupType type(); /** * Name. * * @return the group string */ String name(); /** * Region. * * @return the region the group exists in */ String region(); /** * Tags. * * @return the list of tags associated with group type */ List<TagDescription> tags(); /** * Instances. * * @return the list of instances */ List<String> instances(); /** * Adds the instance. * * @param instance * the instance */ void addInstance(String instance); /** * Copies the Instance group replacing its name with * the supplied name. * * * @param name * @return the new instance group */ InstanceGroup copyAs(String name); } /** * Group types. * * @return the type of groups this crawler creates \set */ EnumSet<?> groupTypes(); /** * Groups. * * @return the list */ List<InstanceGroup> groups(); /** * Gets the up to date information for a collection of group names. * * @param names * the group names * @return the list of instance groups */ List<InstanceGroup> groups(String... names); }
2,537
21.460177
79
java
SimianArmy
SimianArmy-master/src/main/java/com/netflix/simianarmy/chaos/ChaosInstanceSelector.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.simianarmy.chaos; import com.netflix.simianarmy.chaos.ChaosCrawler.InstanceGroup; import java.util.Collection; /** * The Interface ChaosInstanceSelector. */ public interface ChaosInstanceSelector { /** * Select. Pick random instances out of the group with provided probability. Chaos will draw a random number and if * that random number is lower than probability then it will proceed to select an instance (at random) out of the * group. If the random number is higher than the provided probability then no instance will be selected and * <b>null</b> will be returned. * * When the probability value is bigger than 1, say N + 0.x, it will first applies the algorithm described above * with the probability value as 0.x to select possibly one instance, then it will randomly pick N instances. * * The probability is the run probability. If Chaos is running hourly between 9am and 3pm with an overall configured * probability of "1.0" then the probability provided to this routine would be 1.0/6 (6 hours in 9am-3pm). So the * typical probability here would be .1666. For Chaos to select an instance it will pick a random number between 0 * and 1. If that random number is less than the .1666 it will proceed to select an instance and return it, * otherwise it will return null. Over 6 runs it is likely that the random number be less than .1666, but it is not * certain. * * To make Chaos select an instance with 100% certainty it would have to be configured to run only once a day and * the instance group would have to be configured for "1.0" daily probability. * * @param group * the group * @param probability * the probability per run that an instance should be terminated. * @return the instance */ Collection<String> select(InstanceGroup group, double probability); }
2,591
45.285714
120
java
SimianArmy
SimianArmy-master/src/main/java/com/netflix/simianarmy/chaos/BlockAllNetworkTrafficChaosType.java
/* * * Copyright 2013 Justin Santa Barbara. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.simianarmy.chaos; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.Lists; import com.netflix.simianarmy.CloudClient; import com.netflix.simianarmy.MonkeyConfiguration; /** * Blocks network traffic to/from instance, so it is running but offline. * * We actually put the instance into a different security group. First, because AWS requires a SG for some reason. * Second, because you might well want to continue to allow e.g. SSH inbound. */ public class BlockAllNetworkTrafficChaosType extends ChaosType { /** The Constant LOGGER. */ private static final Logger LOGGER = LoggerFactory.getLogger(BlockAllNetworkTrafficChaosType.class); private final String blockedSecurityGroupName; /** * Constructor. * * @param config * Configuration to use */ public BlockAllNetworkTrafficChaosType(MonkeyConfiguration config) { super(config, "BlockAllNetworkTraffic"); this.blockedSecurityGroupName = config.getStrOrElse(getConfigurationPrefix() + "group", "blocked-network"); } /** * We can apply the strategy iff the blocked security group is configured. */ @Override public boolean canApply(ChaosInstance instance) { CloudClient cloudClient = instance.getCloudClient(); String instanceId = instance.getInstanceId(); if (!cloudClient.canChangeInstanceSecurityGroups(instanceId)) { LOGGER.info("Not a VPC instance, can't change security groups"); return false; } return super.canApply(instance); } /** * Takes the instance off the network. */ @Override public void apply(ChaosInstance instance) { CloudClient cloudClient = instance.getCloudClient(); String instanceId = instance.getInstanceId(); if (!cloudClient.canChangeInstanceSecurityGroups(instanceId)) { throw new IllegalStateException("canApply should have returned false"); } String groupId = cloudClient.findSecurityGroup(instance.getInstanceId(), blockedSecurityGroupName); if (groupId == null) { LOGGER.info("Auto-creating security group {}", blockedSecurityGroupName); String description = "Empty security group for blocked instances"; groupId = cloudClient.createSecurityGroup(instance.getInstanceId(), blockedSecurityGroupName, description); } LOGGER.info("Blocking network traffic by applying security group {} to instance {}", groupId, instanceId); List<String> groups = Lists.newArrayList(); groups.add(groupId); cloudClient.setInstanceSecurityGroups(instanceId, groups); } }
3,412
34.185567
119
java
SimianArmy
SimianArmy-master/src/main/java/com/netflix/simianarmy/chaos/NullRouteChaosType.java
/* * * Copyright 2013 Justin Santa Barbara. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.simianarmy.chaos; import com.netflix.simianarmy.MonkeyConfiguration; /** * Null routes the network, taking a node going offline. * * Currently we offline 10.x.x.x (the AWS private network range). * * I think the machine will still be publicly accessible, but won't be able to communicate with any other nodes on * the EC2 network. */ public class NullRouteChaosType extends ScriptChaosType { /** * Constructor. * * @param config * Configuration to use */ public NullRouteChaosType(MonkeyConfiguration config) { super(config, "NullRoute"); } }
1,276
30.146341
114
java
SimianArmy
SimianArmy-master/src/main/java/com/netflix/simianarmy/chaos/ChaosMonkey.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.simianarmy.chaos; import java.util.Date; import java.util.List; import com.netflix.simianarmy.EventType; import com.netflix.simianarmy.FeatureNotEnabledException; import com.netflix.simianarmy.InstanceGroupNotFoundException; import com.netflix.simianarmy.Monkey; import com.netflix.simianarmy.MonkeyConfiguration; import com.netflix.simianarmy.MonkeyRecorder.Event; import com.netflix.simianarmy.MonkeyType; /** * The Class ChaosMonkey. */ public abstract class ChaosMonkey extends Monkey { /** * The Interface Context. */ public interface Context extends Monkey.Context { /** * Configuration. * * @return the monkey configuration */ MonkeyConfiguration configuration(); /** * Chaos crawler. * * @return the chaos crawler */ ChaosCrawler chaosCrawler(); /** * Chaos instance selector. * * @return the chaos instance selector */ ChaosInstanceSelector chaosInstanceSelector(); /** * Chaos email notifier. * * @return the chaos email notifier */ ChaosEmailNotifier chaosEmailNotifier(); } /** The context. */ private final Context ctx; /** * Instantiates a new chaos monkey. * * @param ctx * the context. */ public ChaosMonkey(Context ctx) { super(ctx); this.ctx = ctx; } /** * The monkey Type. */ public enum Type implements MonkeyType { /** chaos monkey. */ CHAOS } /** * The event types that this monkey causes. */ public enum EventTypes implements EventType { /** The chaos termination. */ CHAOS_TERMINATION, CHAOS_TERMINATION_SKIPPED } /** {@inheritDoc} */ @Override public final Type type() { return Type.CHAOS; } /** {@inheritDoc} */ @Override public Context context() { return ctx; } /** {@inheritDoc} */ @Override public abstract void doMonkeyBusiness(); /** * Gets the count of terminations since a specific time. Chaos should probably not continue to beat up an instance * group if the count exceeds a threshold. * * @param group * the group * @return true, if successful */ public abstract int getPreviousTerminationCount(ChaosCrawler.InstanceGroup group, Date after); /** * Record termination. This is used to notify system owners of terminations and to record terminations so that Chaos * does not continue to thrash the instance groups on later runs. * * @param group * the group * @param instance * the instance * @return the termination event */ public abstract Event recordTermination(ChaosCrawler.InstanceGroup group, String instance, ChaosType chaosType); /** * Terminates one instance right away from an instance group when there are available instances. * @param type * the type of the instance group * @param name * the name of the instance group * @return the termination event * @throws FeatureNotEnabledException * @throws InstanceGroupNotFoundException */ public abstract Event terminateNow(String type, String name, ChaosType chaosType) throws FeatureNotEnabledException, InstanceGroupNotFoundException; /** * Sends notification for the termination to the instance owners. * * @param group * the group * @param instance * the instance * @param chaosType * the chaos monkey strategy that was chosen */ public abstract void sendTerminationNotification(ChaosCrawler.InstanceGroup group, String instance, ChaosType chaosType); /** * Gets a list of all enabled chaos types for this ChaosMonkey. */ public abstract List<ChaosType> getChaosTypes(); }
4,723
26.625731
120
java
SimianArmy
SimianArmy-master/src/main/java/com/netflix/simianarmy/chaos/BurnCpuChaosType.java
/* * * Copyright 2013 Justin Santa Barbara. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.simianarmy.chaos; import com.netflix.simianarmy.MonkeyConfiguration; /** * Executes a CPU intensive program on the node, using up all available CPU. * * This simulates either a noisy CPU neighbor on the box or just a general issue with the CPU. */ public class BurnCpuChaosType extends ScriptChaosType { /** * Constructor. * * @param config * Configuration to use */ public BurnCpuChaosType(MonkeyConfiguration config) { super(config, "BurnCpu"); } }
1,181
30.105263
94
java
SimianArmy
SimianArmy-master/src/main/java/com/netflix/simianarmy/chaos/NetworkCorruptionChaosType.java
/* * * Copyright 2013 Justin Santa Barbara. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.simianarmy.chaos; import com.netflix.simianarmy.MonkeyConfiguration; /** * Introduces network packet corruption using traffic-shaping. */ public class NetworkCorruptionChaosType extends ScriptChaosType { /** * Constructor. * * @param config * Configuration to use */ public NetworkCorruptionChaosType(MonkeyConfiguration config) { super(config, "NetworkCorruption"); } }
1,099
29.555556
79
java
SimianArmy
SimianArmy-master/src/main/java/com/netflix/simianarmy/chaos/KillProcessesChaosType.java
/* * * Copyright 2013 Justin Santa Barbara. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.simianarmy.chaos; import com.netflix.simianarmy.MonkeyConfiguration; /** * Kills processes on the node. * * This simulates the process crashing (for any reason). */ public class KillProcessesChaosType extends ScriptChaosType { /** * Constructor. * * @param config * Configuration to use */ public KillProcessesChaosType(MonkeyConfiguration config) { super(config, "KillProcesses"); } }
1,116
28.394737
79
java
SimianArmy
SimianArmy-master/src/main/java/com/netflix/simianarmy/chaos/BurnIoChaosType.java
/* * * Copyright 2013 Justin Santa Barbara. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.simianarmy.chaos; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.simianarmy.MonkeyConfiguration; /** * Executes a disk I/O intensive program on the node, reducing I/O capacity. * * This simulates either a noisy neighbor on the box or just a general issue with the disk. */ public class BurnIoChaosType extends ScriptChaosType { /** The Constant LOGGER. */ private static final Logger LOGGER = LoggerFactory.getLogger(BurnIoChaosType.class); /** * Enhancement: It would be nice to target other devices than the root disk. * * Considerations: * 1) EBS activity costs money. * 2) The root may be on EBS anyway. * 3) If it's costing money, we might want to stop after a while to stop runaway charges. * * coryb suggested this, and proposed something like this: * * tmp=$(mktemp) * df -hl -x tmpfs | awk '/\//{print $6}' > $tmp * mount=$(sed -n $((RANDOM%$(wc -l < $tmp)+1))p $tmp) * rm $tmp * * And then of=$mount/burn * * An alternative might be to run df over SSH, parse it here, and then pass the desired * path to the script. This keeps the script simpler. I don't think there's an easy way * to tell the difference between an EBS volume and an instance volume other than from the * EC2 API. */ /** * Constructor. * * @param config * Configuration to use */ public BurnIoChaosType(MonkeyConfiguration config) { super(config, "BurnIO"); } @Override public boolean canApply(ChaosInstance instance) { if (!super.canApply(instance)) { return false; } if (isRootVolumeEbs(instance) && !isBurnMoneyEnabled()) { LOGGER.debug("Root volume is EBS so BurnIO would cost money; skipping"); return false; } return true; } }
2,583
30.901235
94
java
SimianArmy
SimianArmy-master/src/main/java/com/netflix/simianarmy/chaos/SshConfig.java
/* * * Copyright 2013 Justin Santa Barbara. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.simianarmy.chaos; import java.io.File; import java.io.IOException; import org.jclouds.domain.LoginCredentials; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Charsets; import com.google.common.base.Strings; import com.google.common.io.Files; import com.netflix.simianarmy.MonkeyConfiguration; /** * Holds SSH connection info, used for script-based chaos types. */ public class SshConfig { /** The Constant LOGGER. */ private static final Logger LOGGER = LoggerFactory.getLogger(SshConfig.class); /** * The SSH credentials to log on to an instance. */ private final LoginCredentials sshCredentials; /** * Constructor. * * @param config * Configuration to use */ public SshConfig(MonkeyConfiguration config) { String sshUser = config.getStrOrElse("simianarmy.chaos.ssh.user", "root"); String privateKey = null; String sshKeyPath = config.getStrOrElse("simianarmy.chaos.ssh.key", null); if (sshKeyPath != null) { sshKeyPath = sshKeyPath.trim(); if (sshKeyPath.startsWith("~/")) { String home = System.getProperty("user.home"); if (!Strings.isNullOrEmpty(home)) { if (!home.endsWith("/")) { home += "/"; } sshKeyPath = home + sshKeyPath.substring(2); } } LOGGER.debug("Reading SSH key from {}", sshKeyPath); try { privateKey = Files.toString(new File(sshKeyPath), Charsets.UTF_8); } catch (IOException e) { throw new IllegalStateException("Unable to read the specified SSH key: " + sshKeyPath, e); } } if (privateKey == null) { this.sshCredentials = LoginCredentials.builder().user(sshUser).build(); } else { this.sshCredentials = LoginCredentials.builder().user(sshUser).privateKey(privateKey).build(); } } /** * Get the configured SSH credentials. * * @return configured SSH credentials */ public LoginCredentials getCredentials() { return sshCredentials; } /** * Check if ssh is configured. * * @return true if credentials are configured */ public boolean isEnabled() { return sshCredentials != null; } }
3,115
30.16
106
java
SimianArmy
SimianArmy-master/src/main/java/com/netflix/simianarmy/chaos/FailDynamoDbChaosType.java
/* * * Copyright 2013 Justin Santa Barbara. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.simianarmy.chaos; import com.netflix.simianarmy.MonkeyConfiguration; /** * Adds entries to /etc/hosts so that DynamoDB API endpoints are unreachable. */ public class FailDynamoDbChaosType extends ScriptChaosType { /** * Constructor. * * @param config * Configuration to use */ public FailDynamoDbChaosType(MonkeyConfiguration config) { super(config, "FailDynamoDb"); } }
1,099
29.555556
79
java
SimianArmy
SimianArmy-master/src/main/java/com/netflix/simianarmy/chaos/ShutdownInstanceChaosType.java
/* * * Copyright 2013 Justin Santa Barbara. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.simianarmy.chaos; import com.netflix.simianarmy.CloudClient; import com.netflix.simianarmy.MonkeyConfiguration; /** * Shuts down the instance using the cloud instance-termination API. * * This is the classic chaos-monkey strategy. */ public class ShutdownInstanceChaosType extends ChaosType { /** * Constructor. * * @param config * Configuration to use */ public ShutdownInstanceChaosType(MonkeyConfiguration config) { super(config, "ShutdownInstance"); } /** * Shuts down the instance. */ @Override public void apply(ChaosInstance instance) { CloudClient cloudClient = instance.getCloudClient(); String instanceId = instance.getInstanceId(); cloudClient.terminateInstance(instanceId); } /** * We want to default to enabled. */ @Override protected boolean getEnabledDefault() { return true; } }
1,613
26.355932
79
java
SimianArmy
SimianArmy-master/src/main/java/com/netflix/simianarmy/chaos/FailDnsChaosType.java
/* * * Copyright 2013 Justin Santa Barbara. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.simianarmy.chaos; import com.netflix.simianarmy.MonkeyConfiguration; /** * Blocks TCP and UDP port 53, so DNS resolution fails. */ public class FailDnsChaosType extends ScriptChaosType { /** * Constructor. * * @param config * Configuration to use */ public FailDnsChaosType(MonkeyConfiguration config) { super(config, "FailDns"); } }
1,062
28.527778
79
java
SimianArmy
SimianArmy-master/src/main/java/com/netflix/simianarmy/chaos/ChaosType.java
/* * * Copyright 2013 Justin Santa Barbara. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.simianarmy.chaos; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.simianarmy.CloudClient; import com.netflix.simianarmy.MonkeyConfiguration; /** * A strategy pattern for different types of chaos the chaos monkey can cause. */ public abstract class ChaosType { /** The Constant LOGGER. */ private static final Logger LOGGER = LoggerFactory.getLogger(ChaosType.class); /** * Configuration for this chaos type. */ private final MonkeyConfiguration config; /** * The unique key for the ChaosType. */ private final String key; /** * Is this strategy enabled? */ private final boolean enabled; /** * Protected constructor (abstract class). * * @param config * Configuration to use * @param key * Unique key for the ChaosType strategy */ protected ChaosType(MonkeyConfiguration config, String key) { this.config = config; this.key = key; this.enabled = config.getBoolOrElse(getConfigurationPrefix() + "enabled", getEnabledDefault()); LOGGER.info("ChaosType: {}: enabled={}", key, enabled); } /** * If not specified, controls whether we default to enabled. * * Most ChaosTypes should be disabled by default, not least for legacy compatibility, but we want at least one * strategy to be available. */ protected boolean getEnabledDefault() { return false; } /** * Returns the configuration key prefix to use for this strategy. */ protected String getConfigurationPrefix() { return "simianarmy.chaos." + key.toLowerCase() + "."; } /** * Returns the unique key for the ChaosType. */ public String getKey() { return key; } /** * Checks if this chaos type can be applied to the given instance. * * For example, if the strategy was to detach all the EBS volumes, that only makes sense if there are EBS volumes to * detach. */ public boolean canApply(ChaosInstance instance) { return isEnabled(); } /** * Returns whether we are enabled. */ public boolean isEnabled() { return enabled; } /** * Applies this chaos type to the specified instance. */ public abstract void apply(ChaosInstance instance); /** * Returns the ChaosType with the matching key. */ public static ChaosType parse(List<ChaosType> all, String chaosTypeName) { for (ChaosType chaosType : all) { if (chaosType.getKey().equalsIgnoreCase(chaosTypeName)) { return chaosType; } } throw new IllegalArgumentException("Unknown chaos type value: " + chaosTypeName); } /** * Returns whether chaos types that cost money are allowed. */ protected boolean isBurnMoneyEnabled() { return config.getBoolOrElse("simianarmy.chaos.burnmoney", false); } /** * Checks whether the root volume of the specified instance is on EBS. * * @param instance id of instance * @return true iff root is on EBS */ protected boolean isRootVolumeEbs(ChaosInstance instance) { CloudClient cloudClient = instance.getCloudClient(); String instanceId = instance.getInstanceId(); List<String> withRoot = cloudClient.listAttachedVolumes(instanceId, true); List<String> withoutRoot = cloudClient.listAttachedVolumes(instanceId, false); return (withRoot.size() != withoutRoot.size()); } }
4,307
28.108108
120
java
SimianArmy
SimianArmy-master/src/main/java/com/netflix/simianarmy/resources/janitor/JanitorMonkeyResource.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.simianarmy.resources.janitor; import com.netflix.simianarmy.MonkeyRecorder.Event; import com.netflix.simianarmy.MonkeyRunner; import com.netflix.simianarmy.janitor.JanitorMonkey; import org.apache.commons.lang.StringUtils; import org.codehaus.jackson.JsonEncoding; import org.codehaus.jackson.JsonGenerator; import org.codehaus.jackson.JsonNode; import org.codehaus.jackson.map.MappingJsonFactory; import org.codehaus.jackson.map.ObjectMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Map; /** * The Class JanitorMonkeyResource for json REST apis. */ @Path("/v1/janitor") public class JanitorMonkeyResource { /** The Constant JSON_FACTORY. */ private static final MappingJsonFactory JSON_FACTORY = new MappingJsonFactory(); /** The monkey. */ private static JanitorMonkey monkey; /** The Constant LOGGER. */ private static final Logger LOGGER = LoggerFactory.getLogger(JanitorMonkeyResource.class); /** * Instantiates a janitor monkey resource with a specific janitor monkey. * * @param monkey * the janitor monkey */ public JanitorMonkeyResource(JanitorMonkey monkey) { JanitorMonkeyResource.monkey = monkey; } public JanitorMonkeyResource() { } public JanitorMonkey getJanitorMonkey() { if (JanitorMonkeyResource.monkey == null ) { JanitorMonkeyResource.monkey = MonkeyRunner.getInstance().factory(JanitorMonkey.class); } return monkey; } /** * GET /api/v1/janitor/addEvent will try to a add a new event with the information in the url query string. * This is the same as the regular POST addEvent except through a query string. This technically isn't * very REST-ful as it is a GET call that creates an Opt-out/in event, but is a convenience method * for exposing opt-in/opt-out functionality more directly, for example in an email notification. * * @param eventType eventType from the query string * @param resourceId resourceId from the query string * @return the response * @throws IOException */ @GET @Path("addEvent") public Response addEventThroughHttpGet( @QueryParam("eventType") String eventType, @QueryParam("resourceId") String resourceId, @QueryParam("region") String region) throws IOException { Response.Status responseStatus; ByteArrayOutputStream baos = new ByteArrayOutputStream(); baos.write("<html><body style=\"text-align:center\">".getBytes()); if (StringUtils.isEmpty(eventType) || StringUtils.isEmpty(resourceId)) { responseStatus = Response.Status.BAD_REQUEST; baos.write("<p>NOPE!<br/><br/>Janitor didn't get that: eventType and resourceId parameters are both required</p>".getBytes()); } else { ByteArrayOutputStream baos2 = new ByteArrayOutputStream(); JsonGenerator gen = JSON_FACTORY.createJsonGenerator(baos2, JsonEncoding.UTF8); gen.writeStartObject(); gen.writeStringField("eventType", eventType); gen.writeStringField("resourceId", resourceId); if (eventType.equals("OPTIN")) { responseStatus = optInResource(resourceId, true, region, gen); } else if (eventType.equals("OPTOUT")) { responseStatus = optInResource(resourceId, false, region, gen); } else { responseStatus = Response.Status.BAD_REQUEST; gen.writeStringField("message", String.format("Unrecognized event type: %s", eventType)); } gen.writeEndObject(); gen.close(); if(responseStatus == Response.Status.OK) { baos.write(("<p>SUCCESS!<br/><br/>Resource <strong>" + resourceId + "</strong> has been " + eventType + " of Janitor Monkey!</p>").getBytes()); } else { baos.write(("<p>NOPE!<br/><br/>Janitor is Confused! Error processing Resource <strong>" + resourceId + "</strong></p>").getBytes()); } String jsonout = String.format("<p><em>Monkey JSON Response:</em><br/><br/><textarea cols=40 rows=20>%s</textarea></p>", baos2.toString()); baos.write(jsonout.getBytes()); } baos.write("</body></html>".getBytes()); return Response.status(responseStatus).entity(baos.toString("UTF-8")).build(); } /** * POST /api/v1/janitor will try a add a new event with the information in the url context. * * @param content * the Json content passed to the http POST request * @return the response * @throws IOException */ @POST public Response addEvent(String content) throws IOException { ObjectMapper mapper = new ObjectMapper(); LOGGER.info(String.format("JSON content: '%s'", content)); JsonNode input = mapper.readTree(content); String eventType = getStringField(input, "eventType"); String resourceId = getStringField(input, "resourceId"); String region = getStringField(input, "region"); Response.Status responseStatus; ByteArrayOutputStream baos = new ByteArrayOutputStream(); JsonGenerator gen = JSON_FACTORY.createJsonGenerator(baos, JsonEncoding.UTF8); gen.writeStartObject(); gen.writeStringField("eventType", eventType); gen.writeStringField("resourceId", resourceId); if (StringUtils.isEmpty(eventType) || StringUtils.isEmpty(resourceId)) { responseStatus = Response.Status.BAD_REQUEST; gen.writeStringField("message", "eventType and resourceId parameters are all required"); } else { if (eventType.equals("OPTIN")) { responseStatus = optInResource(resourceId, true, region, gen); } else if (eventType.equals("OPTOUT")) { responseStatus = optInResource(resourceId, false, region, gen); } else { responseStatus = Response.Status.BAD_REQUEST; gen.writeStringField("message", String.format("Unrecognized event type: %s", eventType)); } } gen.writeEndObject(); gen.close(); LOGGER.info("entity content is '{}'", baos.toString("UTF-8")); return Response.status(responseStatus).entity(baos.toString("UTF-8")).build(); } /** * Gets the janitor status (e.g. to support an AWS ELB Healthcheck on an instance running JanitorMonkey). * Creates GET /api/v1/janitor api which responds 200 OK if JanitorMonkey is running. * * @param uriInfo * the uri info * @return the chaos events json response * @throws IOException * Signals that an I/O exception has occurred. */ @GET public Response getJanitorStatus(@Context UriInfo uriInfo) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); JsonGenerator gen = JSON_FACTORY.createJsonGenerator(baos, JsonEncoding.UTF8); gen.writeStartArray(); gen.writeStartObject(); gen.writeStringField("JanitorMonkeyStatus", "OnLikeDonkeyKong"); gen.writeEndObject(); gen.writeEndArray(); gen.close(); return Response.status(Response.Status.OK).entity(baos.toString("UTF-8")).build(); } private Response.Status optInResource(String resourceId, boolean optIn, String region, JsonGenerator gen) throws IOException { String op = optIn ? "in" : "out"; LOGGER.info(String.format("Opt %s resource %s for Janitor Monkey.", op, resourceId)); Response.Status responseStatus; Event evt; if (optIn) { evt = getJanitorMonkey().optInResource(resourceId, region); } else { evt = getJanitorMonkey().optOutResource(resourceId, region); } if (evt != null) { responseStatus = Response.Status.OK; gen.writeStringField("monkeyType", evt.monkeyType().name()); gen.writeStringField("eventId", evt.id()); gen.writeNumberField("eventTime", evt.eventTime().getTime()); gen.writeStringField("region", evt.region()); for (Map.Entry<String, String> pair : evt.fields().entrySet()) { gen.writeStringField(pair.getKey(), pair.getValue()); } } else { responseStatus = Response.Status.INTERNAL_SERVER_ERROR; gen.writeStringField("message", String.format("Failed to opt %s resource %s", op, resourceId)); } LOGGER.info(String.format("Opt %s operation completed.", op)); return responseStatus; } private String getStringField(JsonNode input, String field) { JsonNode node = input.get(field); if (node == null) { return null; } return node.getTextValue(); } }
9,813
40.940171
191
java
SimianArmy
SimianArmy-master/src/main/java/com/netflix/simianarmy/resources/chaos/ChaosMonkeyResource.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.simianarmy.resources.chaos; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import com.google.common.base.Strings; import com.netflix.simianarmy.Monkey; import com.sun.jersey.spi.resource.Singleton; import org.apache.commons.lang.StringUtils; import org.codehaus.jackson.JsonEncoding; import org.codehaus.jackson.JsonGenerator; import org.codehaus.jackson.JsonNode; import org.codehaus.jackson.map.MappingJsonFactory; import org.codehaus.jackson.map.ObjectMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.simianarmy.FeatureNotEnabledException; import com.netflix.simianarmy.InstanceGroupNotFoundException; import com.netflix.simianarmy.MonkeyRecorder.Event; import com.netflix.simianarmy.MonkeyRunner; import com.netflix.simianarmy.NotFoundException; import com.netflix.simianarmy.chaos.ChaosMonkey; import com.netflix.simianarmy.chaos.ChaosType; import com.netflix.simianarmy.chaos.ShutdownInstanceChaosType; /** * The Class ChaosMonkeyResource for json REST apis. */ @Path("/v1/chaos") @Produces(MediaType.APPLICATION_JSON) @Singleton public class ChaosMonkeyResource { /** The Constant JSON_FACTORY. */ private static final MappingJsonFactory JSON_FACTORY = new MappingJsonFactory(); /** The monkey. */ private ChaosMonkey monkey = null; /** The Constant LOGGER. */ private static final Logger LOGGER = LoggerFactory.getLogger(ChaosMonkeyResource.class); /** * Instantiates a chaos monkey resource with a specific chaos monkey. * * @param monkey * the chaos monkey */ public ChaosMonkeyResource(ChaosMonkey monkey) { this.monkey = monkey; } /** * Instantiates a chaos monkey resource using a registered chaos monkey from factory. */ public ChaosMonkeyResource() { for (Monkey runningMonkey : MonkeyRunner.getInstance().getMonkeys()) { if (runningMonkey instanceof ChaosMonkey) { this.monkey = (ChaosMonkey) runningMonkey; break; } } if (this.monkey == null) { LOGGER.info("Creating a new Chaos monkey instance for the resource."); this.monkey = MonkeyRunner.getInstance().factory(ChaosMonkey.class); } } /** * Gets the chaos events. Creates GET /api/v1/chaos api which outputs the chaos events in json. Users can specify * cgi query params to filter the results and use "since" query param to set the start of a timerange. "since" should * be specified in milliseconds since the epoch. * * @param uriInfo * the uri info * @return the chaos events json response * @throws IOException * Signals that an I/O exception has occurred. */ @GET public Response getChaosEvents(@Context UriInfo uriInfo) throws IOException { Map<String, String> query = new HashMap<String, String>(); Date date = null; for (Map.Entry<String, List<String>> pair : uriInfo.getQueryParameters().entrySet()) { if (pair.getValue().isEmpty()) { continue; } if (pair.getKey().equals("since")) { date = new Date(Long.parseLong(pair.getValue().get(0))); } else { query.put(pair.getKey(), pair.getValue().get(0)); } } // if "since" not set, default to 24 hours ago if (date == null) { Calendar now = monkey.context().calendar().now(); now.add(Calendar.DAY_OF_YEAR, -1); date = now.getTime(); } List<Event> evts = monkey.context().recorder() .findEvents(ChaosMonkey.Type.CHAOS, ChaosMonkey.EventTypes.CHAOS_TERMINATION, query, date); ByteArrayOutputStream baos = new ByteArrayOutputStream(); JsonGenerator gen = JSON_FACTORY.createJsonGenerator(baos, JsonEncoding.UTF8); gen.writeStartArray(); for (Event evt : evts) { gen.writeStartObject(); gen.writeStringField("monkeyType", evt.monkeyType().name()); gen.writeStringField("eventId", evt.id()); gen.writeStringField("eventType", evt.eventType().name()); gen.writeNumberField("eventTime", evt.eventTime().getTime()); gen.writeStringField("region", evt.region()); for (Map.Entry<String, String> pair : evt.fields().entrySet()) { gen.writeStringField(pair.getKey(), pair.getValue()); } gen.writeEndObject(); } gen.writeEndArray(); gen.close(); return Response.status(Response.Status.OK).entity(baos.toString("UTF-8")).build(); } /** * POST /api/v1/chaos will try a add a new event with the information in the url context, * ignoring the monkey probability and max termination configurations, for a specific instance group. * * @param content * the Json content passed to the http POST request * @return the response * @throws IOException */ @POST public Response addEvent(String content) throws IOException { ObjectMapper mapper = new ObjectMapper(); LOGGER.info(String.format("JSON content: '%s'", content)); JsonNode input = mapper.readTree(content); String eventType = getStringField(input, "eventType"); String groupType = getStringField(input, "groupType"); String groupName = getStringField(input, "groupName"); String chaosTypeName = getStringField(input, "chaosType"); ChaosType chaosType; if (!Strings.isNullOrEmpty(chaosTypeName)) { chaosType = ChaosType.parse(this.monkey.getChaosTypes(), chaosTypeName); } else { chaosType = new ShutdownInstanceChaosType(monkey.context().configuration()); } Response.Status responseStatus; ByteArrayOutputStream baos = new ByteArrayOutputStream(); JsonGenerator gen = JSON_FACTORY.createJsonGenerator(baos, JsonEncoding.UTF8); gen.writeStartObject(); gen.writeStringField("eventType", eventType); gen.writeStringField("groupType", groupType); gen.writeStringField("groupName", groupName); gen.writeStringField("chaosType", chaosType.getKey()); if (StringUtils.isEmpty(eventType) || StringUtils.isEmpty(groupType) || StringUtils.isEmpty(groupName)) { responseStatus = Response.Status.BAD_REQUEST; gen.writeStringField("message", "eventType, groupType, and groupName parameters are all required"); } else { if (eventType.equals("CHAOS_TERMINATION")) { responseStatus = addTerminationEvent(groupType, groupName, chaosType, gen); } else { responseStatus = Response.Status.BAD_REQUEST; gen.writeStringField("message", String.format("Unrecognized event type: %s", eventType)); } } gen.writeEndObject(); gen.close(); LOGGER.info("entity content is '{}'", baos.toString("UTF-8")); return Response.status(responseStatus).entity(baos.toString("UTF-8")).build(); } private Response.Status addTerminationEvent(String groupType, String groupName, ChaosType chaosType, JsonGenerator gen) throws IOException { LOGGER.info("Running on-demand termination for instance group type '{}' and name '{}'", groupType, groupName); Response.Status responseStatus; try { Event evt = monkey.terminateNow(groupType, groupName, chaosType); if (evt != null) { responseStatus = Response.Status.OK; gen.writeStringField("monkeyType", evt.monkeyType().name()); gen.writeStringField("eventId", evt.id()); gen.writeNumberField("eventTime", evt.eventTime().getTime()); gen.writeStringField("region", evt.region()); for (Map.Entry<String, String> pair : evt.fields().entrySet()) { gen.writeStringField(pair.getKey(), pair.getValue()); } } else { responseStatus = Response.Status.INTERNAL_SERVER_ERROR; gen.writeStringField("message", String.format("Failed to terminate instance in group %s [type %s]", groupName, groupType)); } } catch (FeatureNotEnabledException e) { responseStatus = Response.Status.FORBIDDEN; gen.writeStringField("message", e.getMessage()); } catch (InstanceGroupNotFoundException e) { responseStatus = Response.Status.NOT_FOUND; gen.writeStringField("message", e.getMessage()); } catch (NotFoundException e) { // Available instance cannot be found to terminate, maybe the instance is already gone responseStatus = Response.Status.GONE; gen.writeStringField("message", e.getMessage()); } LOGGER.info("On-demand termination completed."); return responseStatus; } private String getStringField(JsonNode input, String field) { JsonNode node = input.get(field); if (node == null) { return null; } return node.getTextValue(); } }
10,408
39.501946
121
java
chlorine-finder
chlorine-finder-master/src/test/java/io/dataapps/chlorine/finder/TestAddFinders.java
/* * Copyright 2016, DataApps Corporation (http://dataApps.io) . * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.dataapps.chlorine.finder; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import io.dataapps.chlorine.pattern.RegexFinder; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import org.junit.Test; public class TestAddFinders { private static String TEXT_PART1 = "text containing some stuff - "; private static String TEXT_PART2 = " - end of text"; static class SantaClaraZipCodeFinder implements Finder { @Override public String getName() { return "Santa Clara ZipCode"; } @Override public FinderResult find(String input) { List<String> zipsFound = new ArrayList<>(); if (input.contains("95050")) { zipsFound.add ("95050"); } if (input.contains("95051")) { zipsFound.add ("95051"); } if (input.contains("95054")) { zipsFound.add ("95054"); } return new FinderResult (zipsFound,input.replaceAll("(95050|95051|95054)", "")); } } static class DummyFinderProvider implements FinderProvider { List<Finder> finders = new ArrayList<>(); public DummyFinderProvider() { Finder reservedWordFinder = new RegexFinder("Reserved Word Finder" , "\\b(?:class|interface|void|static|public|private)\\b"); SantaClaraZipCodeFinder scZipFinder = new SantaClaraZipCodeFinder(); finders.add(scZipFinder); finders.add(reservedWordFinder); } @Override public List<Finder> getFinders() { return finders; } } @Test public void testAdd() { FinderEngine engine = new FinderEngine(); Finder scFinder = new SantaClaraZipCodeFinder(); engine.add(scFinder); List<String> matches = engine.find(TEXT_PART1 + "b@b.com" + TEXT_PART2).getMatches(); assertTrue(matches.size()==1); assertEquals("b@b.com", matches.get(0)); matches = engine.find(TEXT_PART1 + "95050" + TEXT_PART2).getMatches(); assertEquals(1, matches.size()); assertEquals("95050", matches.get(0)); matches = engine.find(TEXT_PART1 + "94090" + TEXT_PART2).getMatches(); assertEquals(0, matches.size()); Map<String, List<String>> matchesByType = engine.findWithType(TEXT_PART1 + "95050" + TEXT_PART2); assertEquals(1, matchesByType.size()); matchesByType.containsKey(scFinder.getName()); } @Test public void testAddList() { List<Finder> lstFinders = new ArrayList<>(); Finder scFinder = new SantaClaraZipCodeFinder(); Finder reservedWordFinder = new RegexFinder("Reserved Word Finder" , "\\b(?:class|interface|void|static|public|private)\\b"); lstFinders.add(reservedWordFinder); lstFinders.add(scFinder); FinderEngine engine = new FinderEngine(lstFinders, false); List<String> matches = engine.find(TEXT_PART1 + "b@b.com" + TEXT_PART2).getMatches(); assertEquals(0, matches.size()); matches = engine.find(TEXT_PART1 + "95050" + TEXT_PART2).getMatches(); assertEquals(1, matches.size()); assertEquals("95050", matches.get(0)); matches = engine.find(TEXT_PART1 + "94090" + TEXT_PART2).getMatches(); assertEquals(0, matches.size()); Map<String, List<String>> matchesByType = engine.findWithType(TEXT_PART1 + "95050" + TEXT_PART2); assertEquals(1, matchesByType.size()); matchesByType.containsKey(scFinder.getName()); matches = engine.find(TEXT_PART1 + "public" + TEXT_PART2).getMatches(); assertEquals(1, matches.size()); assertEquals("public", matches.get(0)); matchesByType = engine.findWithType(TEXT_PART1 + "class" + TEXT_PART2); assertEquals(1, matchesByType.size()); matchesByType.containsKey(reservedWordFinder.getName()); } @Test public void testAddProvider() { FinderEngine engine = new FinderEngine(new DummyFinderProvider() , false); List<String> matches = engine.find(TEXT_PART1 + "b@b.com" + TEXT_PART2).getMatches(); assertEquals(0, matches.size()); matches = engine.find(TEXT_PART1 + "95050" + TEXT_PART2).getMatches(); assertEquals(1, matches.size()); assertEquals("95050", matches.get(0)); matches = engine.find(TEXT_PART1 + "94090" + TEXT_PART2).getMatches(); assertEquals(0, matches.size()); Map<String, List<String>> matchesByType = engine.findWithType(TEXT_PART1 + "95050" + TEXT_PART2); assertEquals(1, matchesByType.size()); matchesByType.containsKey("Santa Clara ZipCode"); matches = engine.find(TEXT_PART1 + "public" + TEXT_PART2).getMatches(); assertEquals(1, matches.size()); assertEquals("public", matches.get(0)); matchesByType = engine.findWithType(TEXT_PART1 + "class" + TEXT_PART2); assertEquals(1, matchesByType.size()); matchesByType.containsKey("Reserved Word Finder"); } @Test public void testReadFromAFileUsingClassPath () { FinderEngine engine = new FinderEngine("testfinders.xml", true); assertEquals (TestDefaultFinders.FINDERNAMES.length+2, engine.getFinders().size()); } @Test public void testReadFromAFileUsingPath () { String fileName = this.getClass().getClassLoader() .getResource("testfinders.xml").getFile(); FinderEngine engine = new FinderEngine(fileName); assertEquals (TestDefaultFinders.FINDERNAMES.length+2, engine.getFinders().size()); } }
5,734
32.735294
99
java
chlorine-finder
chlorine-finder-master/src/test/java/io/dataapps/chlorine/finder/TestDefaultFinders.java
/* * Copyright 2016, DataApps Corporation (http://dataApps.io) . * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.dataapps.chlorine.finder; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.List; import java.util.Map; import org.junit.Test; public class TestDefaultFinders { private static String TEXT_PART1 = "text containing some stuff - "; private static String TEXT_PART2 = " - end of text"; //emails private static String EMAIL1 = "b@b.com"; private static String EMAIL2 = "b.b@b.com"; private static String EMAIL3 = "bob_smith@foo.com"; private static String EMAIL4 = "bob-smith@foo.com"; //credit cards private static String MASTERCARD1 = "5555555555554444"; private static String MASTERCARD2 = "5105105105105100"; private static String VISACARD1 = "4111111111111111"; private static String VISACARD2 = "4012888888881881"; //private static String VISACARD3 = "4222222222222"; private static String AMEXCARD1 = "378282246310005"; private static String AMEXCARD2 = "371449635398431"; private static String AMEXCARD3 = "378734493671000"; private static String DINERSCLUB1 = "30569309025904"; private static String DINERSCLUB2 = "38520000023237"; private static String DISCOVER1 = "6011111111111117"; private static String DISCOVER2 = "6011000990139424"; private static String JCB1 = "3530111333300000"; private static String JCB2= "3566002020360505"; //Phone Numbers private static String USPHONE1 = "333-444-5555"; private static String USPHONE2 = "(658) 154 1122"; private static String USPHONE3 = "3334445555"; private static String USPHONE4 = "(658)1541122"; //ips private static String IP1 = "127.0.0.1"; private static String IP2 = "123.345.23.123"; //addresses private static String ADDRESS1 = "2345 Nulla St"; private static String ADDRESS2 = "8562 Fusce Rd"; private static String ADDRESS3 = "Somecity CA 2345"; //SSNs private static String SSN1 = "576-16-2345"; private static String SSN2 = "576 16 2345"; //ZIPCodes private static String ZIP1 = "95050"; private static String URL1 = "https://www.dataApps.io"; private static String IPV6_1 = "2001:db8:a0b:12f0::1"; public static String[] FINDERNAMES = new String[] {"Email", "CreditCard", "USPhone-Formatted", "IPV4", "StreetAddress", "SSN-dashes" , "SSN-spaces", "Hostname", "IPV6"}; private static String[] testStrings = new String[] { EMAIL1, EMAIL2, EMAIL3, EMAIL4, MASTERCARD1, MASTERCARD2, VISACARD1, VISACARD2, AMEXCARD1, AMEXCARD2, AMEXCARD3, DINERSCLUB1, DINERSCLUB2, DISCOVER1, DISCOVER2, JCB1, JCB2, USPHONE1, USPHONE2, IP1, IP2, ADDRESS1, ADDRESS2, SSN1, SSN2, ZIP1, URL1, IPV6_1 }; private static String[] testStringTypes = new String[] { "Email", "Email", "Email", "Email", "CreditCard", "CreditCard", "CreditCard", "CreditCard", "CreditCard", "CreditCard", "CreditCard", "CreditCard", "CreditCard", "CreditCard", "CreditCard", "CreditCard", "CreditCard", "USPhone-Formatted", "USPhone-Formatted", "IPV4", "IPV4", "StreetAddress", "StreetAddress", "SSN-dashes","SSN-spaces", "ZipCode", "URL", "IPV6" }; private static String[] testBadStrings = new String[] {USPHONE3, USPHONE4, ADDRESS3}; private static String PLAIN_TEXT = "text containing no sensitive elements"; private static String multipleEmails = EMAIL1 + "," + EMAIL2; private static String multipleCreditCards = "a"+ MASTERCARD2 + "," + AMEXCARD1 + " "; @Test public void testFinders () { FinderEngine engine = new FinderEngine(); assertEquals (FINDERNAMES.length, engine.getFinders().size()); for (String finderName: FINDERNAMES) { assertTrue ("Finder Not Found:" + finderName, contains(finderName, engine.getFinders())); } } private static boolean contains(String finderName, List<Finder> finders) { for (Finder finder: finders) { if (finder.getName().equalsIgnoreCase(finderName)) { return true; } } return false; } @Test public void testMatch() { FinderEngine engine = new FinderEngine((List<Finder>)null, true, true); for (String str: testStrings) { List<String> results = engine.find(TEXT_PART1 + str + TEXT_PART2).getMatches(); assertEquals (1, results.size()); assertEquals(str, results.get(0)); } } @Test public void testNonMatch() { for (String str: testBadStrings) { FinderEngine engine = new FinderEngine(); List<String> results = engine.find(TEXT_PART1 + str + TEXT_PART2).getMatches(); assertEquals (str + " is found. ", 0, results.size()); } } @Test public void testNoMatch () { FinderEngine engine = new FinderEngine(); List<String> emails = engine.find(PLAIN_TEXT).getMatches(); assertTrue (emails.isEmpty()); } @Test public void testMatchWithType() { int i = 0; for (String str: testStrings) { FinderEngine engine = new FinderEngine((List<Finder>)null, true, true); Map<String, List<String>> results = engine.findWithType(TEXT_PART1 + str + TEXT_PART2); if (results.size() > 1) { // This is an error condition, Print some helpful information on what happened for (Map.Entry<String, List<String>> entry : results.entrySet()) { System.out.println("Finder Name:"+ entry.getKey()); for (String value: entry.getValue()) { System.out.println("Value:"+ value); } } }; assertTrue (results.size()>0); String expectedType = testStringTypes[i++]; String actualType = null; for (Map.Entry<String, List<String>> entry : results.entrySet()) { if (expectedType.equals(entry.getKey())) { actualType = entry.getKey(); break; } } if (actualType == null) { System.out.println(expectedType); } assertNotNull(actualType); List<String> matches = results.get(actualType); if (matches.size() > 1) { for (String value: matches) { System.out.println("Value:"+ value); } } assertEquals(str, matches.get(0)); } } @Test public void testDisabledFinders () { FinderEngine engine = new FinderEngine(); List<String> results = engine.find(TEXT_PART1 + ZIP1).getMatches(); assertEquals (ZIP1 + " is found. ", 0, results.size()); } @Test public void testMultipleEmailsWithCommas () { FinderEngine engine = new FinderEngine(); List<String> results = engine.find(multipleEmails).getMatches(); assertTrue (results.size()>=2); assertTrue(results.contains(EMAIL1)); assertTrue(results.contains(EMAIL2)); } @Test public void testMultipleCreditCardsWithCommas () { FinderEngine engine = new FinderEngine(); List<String> results = engine.find(multipleCreditCards).getMatches(); assertEquals (2, results.size()); assertTrue(results.contains(MASTERCARD2)); assertTrue(results.contains(AMEXCARD1)); } }
7,364
31.021739
90
java
chlorine-finder
chlorine-finder-master/src/test/java/io/dataapps/chlorine/finder/TestMasker.java
/* * Copyright 2016, DataApps Corporation (http://dataApps.io) . * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.dataapps.chlorine.finder; 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 io.dataapps.chlorine.mask.MaskFactory; import io.dataapps.chlorine.mask.Masker; import java.util.List; import org.junit.Test; public class TestMasker { private static String TEXT_PART1 = "text containing - "; private static String TEXT_PART2 = " - end of text"; //emails private static String EMAIL1 = "b@b.com"; private static String EMAIL2 = "b.b@b.com"; //credit cards private static String MASTERCARD1 = "5555555555554444"; private static String DINERSCLUB1 = "30569309025904"; //Phone Numbers private static String USPHONE1 = "333-444-5555"; private static String USPHONE2 = "(658) 154 1122"; private static String USPHONE3 = "3334445555"; private static String USPHONE4 = "(658)1541122"; //ips private static String IP1 = "127.0.0.1"; private static String IP2 = "123.345.23.123"; //addresses private static String ADDRESS1 = "2345 Nulla St"; private static String ADDRESS2 = "8562 Fusce Rd"; private static String ADDRESS3 = "Somecity CA 2345"; //SSNs private static String SSN1 = "576-16-2345"; private static String SSN2 = "576 16 2345"; //ZIPCodes private static String ZIP1 = "95050"; private static String URL1 = "https://www.dataApps.io"; private static String IPV6_1 = "2001:db8:a0b:12f0::1"; public static String[] FINDERNAMES = new String[] {"Email", "Credit Card", "US Phone#Formatted", "IPV4", "Street Address", "SSN-dashes" , "SSN-spaces"}; private static String[] testStrings = new String[] { EMAIL1, MASTERCARD1, USPHONE1, USPHONE2, IP1, IP2, ADDRESS1, ADDRESS2, SSN1, SSN2, ZIP1, URL1, IPV6_1 }; private static String[] testBadStrings = new String[] {USPHONE3, USPHONE4, ADDRESS3}; private static String PLAIN_TEXT = "text containing no sensitive elements"; private static String multipleEmails = EMAIL1 + "," + EMAIL2; private static String multipleCreditCards = "a"+ MASTERCARD1 + "," + DINERSCLUB1 + " ";; @Test public void testMasker() { MaskFactory maskFactory = new MaskFactory(); assertNotNull(maskFactory.getMaskers()); assertEquals (1, maskFactory.getMaskers().size()); } @Test public void testMatch() { FinderEngine engine = new FinderEngine((List<Finder>)null, true, true); MaskFactory maskFactory = new MaskFactory(engine); Masker masker = maskFactory.getMasker(); for (String str: testStrings) { String input = TEXT_PART1 + str + TEXT_PART2; String result = masker.mask(input); List<String> elements = engine.find(input).getMatches(); assertEquals (1,elements.size()); for (String element:elements) { assertFalse("element=" +element + ", str=" +str,result.contains(element)); } } } @Test public void testNonMatch() { MaskFactory maskFactory = new MaskFactory(); Masker masker = maskFactory.getMasker(); for (String str: testBadStrings) { String input = TEXT_PART1 + str + TEXT_PART2; String output = masker.mask(input); assertEquals(input,output); } } @Test public void testNoMatch () { MaskFactory maskFactory = new MaskFactory(); Masker masker = maskFactory.getMasker(); String result = masker.mask(PLAIN_TEXT); assertEquals(PLAIN_TEXT, result); } @Test public void testMultipleEmailsWithCommas () { MaskFactory maskFactory = new MaskFactory(); Masker masker = maskFactory.getMasker(); String result = masker.mask(multipleEmails); assertFalse(result.contains(EMAIL1)); assertFalse(result.contains(EMAIL2)); } @Test public void testMultipleCreditCardsWithCommas () { MaskFactory maskFactory = new MaskFactory(); Masker masker = maskFactory.getMasker(); String result = masker.mask(multipleCreditCards); assertFalse(result.contains(MASTERCARD1)); assertFalse(result.contains(DINERSCLUB1)); } }
4,571
29.278146
92
java
chlorine-finder
chlorine-finder-master/src/main/java/io/dataapps/chlorine/mask/Redactor.java
/* * Copyright 2016, DataApps Corporation (http://dataApps.io) . * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.dataapps.chlorine.mask; import io.dataapps.chlorine.finder.Finder; import io.dataapps.chlorine.finder.FinderEngine; import io.dataapps.chlorine.finder.FinderResult; import io.dataapps.chlorine.pattern.FinderUtil; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Implements the Masker. * Accepts a replacement string for each finder element. * Detects the data using the FinderEngine. * Substitutes any element detected by the finder using * the replacement text. * If the Finder implements Replacer, then it invokes * replace on the Finder. */ public class Redactor implements Masker { private static final Log LOG = LogFactory.getLog(Redactor.class); Map<String,String> replacements ; FinderEngine engine; public void init(FinderEngine engine, Map<String,String> replacements) { this.engine = engine; this.replacements = replacements; } public void init(FinderEngine engine, String configurationFileName) { init(engine, readReplacements(configurationFileName)); } private static Map<String,String> readReplacements (String configurationFileName) { Properties properties =new Properties(); Map<String,String> map = new HashMap<>(); try (final InputStream stream = MaskFactory.class.getClassLoader(). getResourceAsStream(configurationFileName)) { properties.load(stream); for (final String name: properties.stringPropertyNames()) { map.put(name, properties.getProperty(name)); } }catch (IOException e) { LOG.error(e); } return map; } @Override public String mask(String input) { String temp = input; String masked = input; List<Finder> finders = engine.getFinders(); for (Finder finder:finders) { String replacement = replacements.get(finder.getName()); if (replacement != null) { FinderResult result = finder.find(temp); masked = FinderUtil.replaceMatches( masked, result.getMatches(), replacement); temp = result.getMatchesRemoved(); } } return masked; } public Map<String, String> getReplacements() { return replacements; } public void setReplacements(Map<String, String> replacements) { this.replacements = replacements; } public FinderEngine getEngine() { return engine; } public void setEngine(FinderEngine engine) { this.engine = engine; } }
3,119
28.158879
75
java
chlorine-finder
chlorine-finder-master/src/main/java/io/dataapps/chlorine/mask/MaskFactory.java
/* * Copyright 2016, DataApps Corporation (http://dataApps.io) . * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.dataapps.chlorine.mask; import io.dataapps.chlorine.finder.FinderEngine; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** * The MaskFactory looks up maskers.xml in the classpath. * Reads all the maskers and uses it for Scanning. * * The file syntax: * <?xml version="1.0" encoding="UTF-8" standalone="no"?> * <configuration> * <maskers> * <masker> * <name>nameofthemasker</name> * <class>classforthemasker</class> * <configuration>true</configuration> * </masker> * </maskers> * <default>nameofthemasker</dafault> * </configuration> * */ public class MaskFactory { public static final String MASK_DEFAULT_XML = "mask_default.xml"; private static final Log LOG = LogFactory.getLog(MaskFactory.class); Map<String,Masker> maskers = new HashMap<> (); private FinderEngine engine; private String defaultMasker; public MaskFactory() { this(new FinderEngine()); } public MaskFactory(FinderEngine engine) { this(engine, MaskFactory.class.getClassLoader() .getResourceAsStream(MASK_DEFAULT_XML)); } public MaskFactory(FinderEngine fEngine, InputStream in) { engine = fEngine; try { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); DefaultHandler handler = new DefaultHandler() { boolean bName = false; boolean bClass = false; boolean bConfiguration = false; boolean bDefault = false; String name = ""; String className = ""; String configuration = ""; String defaultStr; public void startElement(String uri, String localName,String qName, Attributes attributes) throws SAXException { if (qName.equalsIgnoreCase("NAME")) { bName = true; } else if (qName.equalsIgnoreCase("CLASS")) { bClass = true; } else if (qName.equalsIgnoreCase("CONFIGURATION")) { bConfiguration = true; } else if (qName.equalsIgnoreCase("DEFAULT")) { bDefault = true; } } public void endElement(String uri, String localName, String qName) throws SAXException { if (qName.equalsIgnoreCase("NAME")) { bName = false; name = name.trim(); } else if (qName.equalsIgnoreCase("CLASS")) { bClass = false; className = className.trim(); } else if (qName.equalsIgnoreCase("CONFIGURATION")) { bConfiguration = false; configuration = configuration.trim(); } else if (qName.equalsIgnoreCase("DEFAULT")) { bDefault = false; defaultMasker = defaultStr.trim(); } else if (qName.equalsIgnoreCase("MASKER")) { if (!name.isEmpty() && !className.isEmpty() && !configuration.isEmpty()) { try { Class<?> klass = Thread.currentThread().getContextClassLoader().loadClass(className); Masker masker = (Masker) klass.newInstance(); masker.init(engine,configuration); maskers.put(name,masker); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) { LOG.error(e); } } else { if (name.isEmpty()) { LOG.error("The name for a masker cannot be empty"); } if (className.isEmpty()) { LOG.error("The class name for a masker cannot be empty"); } if (configuration.isEmpty()) { LOG.error("The configuration for a masker cannot be empty"); } } name = ""; configuration = ""; className = ""; defaultStr = ""; } } public void characters(char ch[], int start, int length) throws SAXException { if (bName) { name += new String(ch, start, length); } else if (bClass) { className += new String(ch, start, length); } else if (bConfiguration) { configuration += new String(ch, start, length); } else if (bDefault) { defaultStr += new String(ch, start, length); } } }; saxParser.parse(in, handler); } catch (Exception e) { LOG.error(e); } } public Map<String,Masker> getMaskers() { return maskers; } public Masker getMasker() { return maskers.get(defaultMasker); } public Masker getMasker(String name) { return maskers.get(name); } public FinderEngine getFinderEngine() { return engine; } }
5,137
28.36
93
java
chlorine-finder
chlorine-finder-master/src/main/java/io/dataapps/chlorine/mask/Masker.java
/* * Copyright 2016, DataApps Corporation (http://dataApps.io) . * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.dataapps.chlorine.mask; import io.dataapps.chlorine.finder.FinderEngine; /** * A class which implements a masking operation using * a FinderEngine * */ public interface Masker { /** * initialize the Masker using the FinderEnginer and * a string which provides a pointer for Masker's configuration. * @param engine - FinderEngine * @param configuration -String containing configuration information for * Masker */ void init (FinderEngine engine, String configuration); /** * Accepts an input text and mask it. * @param input - text to be masked * @return masked text */ String mask(String input); }
1,273
27.311111
75
java
chlorine-finder
chlorine-finder-master/src/main/java/io/dataapps/chlorine/pattern/RegexFinder.java
/* * Copyright 2016, DataApps Corporation (http://dataApps.io) . * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.dataapps.chlorine.pattern; import io.dataapps.chlorine.finder.Finder; import io.dataapps.chlorine.finder.FinderResult; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class RegexFinder implements Finder { static final Log LOG = LogFactory.getLog(RegexFinder.class); public static final int DEFAULT_FLAGS = Pattern.CANON_EQ | Pattern.CASE_INSENSITIVE | Pattern.MULTILINE; private String name; Pattern pattern; public RegexFinder() {} /** * Construct a Regular expression Based Finder using a pattern and default flags. * @param name - name of the Finder * @param pattern - pattern of the regular expression. */ public RegexFinder(String name, String pattern) { this(name, pattern,DEFAULT_FLAGS); } /** * Construct a Regular expression Based Finder using pattern and flags. * @param name - name of the Finder * @param pattern - pattern of the regular expression. * @param flags - Flags to be used while compiling the pattern. */ public RegexFinder(String name, String pattern, int flags) { this.name = name; this.pattern = Pattern.compile(pattern, flags); } /** * set the name of the Finder * @param name */ public void setName(String name) { this.name = name; } /** * get Finder's name. */ public String getName() { return name; } /** * set the Pattern * @param pattern */ public void setPattern(Pattern pattern) { this.pattern = pattern; } /** * Get Pattern. */ public Pattern getPattern() { return pattern; } /** * Scan the list of inputs using the finders. * Return a list of actual matched values. * @return a list of matches */ public FinderResult find(String input) { List<String> matches = new ArrayList<>(); Matcher matcher = pattern.matcher(input); while (matcher.find()) { matches.add(input.substring(matcher.start(), matcher.end())); } return new FinderResult(matches, replace(input,"")); } static String removeCommas(String match) { if (match.endsWith(",")) { match = match.substring(0, match.length() - 1); } if (match.startsWith(",")) { match = match.substring(1); } return match; } private String replace(String input, String replacement) { Matcher matcher = pattern.matcher(input); return matcher.replaceAll(replacement); } }
3,085
24.716667
82
java
chlorine-finder
chlorine-finder-master/src/main/java/io/dataapps/chlorine/pattern/CompositeCreditCardFinder.java
/* * Copyright 2016, DataApps Corporation (http://dataApps.io) . * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.dataapps.chlorine.pattern; import io.dataapps.chlorine.finder.CompositeFinder; import io.dataapps.chlorine.finder.Finder; import io.dataapps.chlorine.finder.FinderResult; public class CompositeCreditCardFinder implements Finder { private CompositeFinder compositeFinder; /** * Build a Composite CreditCardFinder using a multiple CreditCardFinders * Each CreditCardFinder has patterns to identify different * Credit Card types like Visa, MasterCard etc. * */ public CompositeCreditCardFinder () { compositeFinder = new CompositeFinder("CreditCard"); String START_BLOCK = "([^\\d\\.-]|^)"; compositeFinder.add(new CreditCardFinder("Mastercard", START_BLOCK + "5[1-5][0-9]{2}(\\ |\\-|)[0-9]{4}(\\ |\\-|)[0-9]{4}(\\ |\\-|)[0-9]{4}(\\D|$)")); compositeFinder.add(new CreditCardFinder("Visa", START_BLOCK + "4[0-9]{3}(\\ |\\-|)[0-9]{4}(\\ |\\-|)[0-9]{4}(\\ |\\-|)[0-9]{4}(\\D|$)")); compositeFinder.add(new CreditCardFinder("AMEX", START_BLOCK + "(34|37)[0-9]{2}(\\ |\\-|)[0-9]{6}(\\ |\\-|)[0-9]{5}(\\D|$)")); compositeFinder.add(new CreditCardFinder("Diners Club 1", START_BLOCK + "30[0-5][0-9](\\ |\\-|)[0-9]{6}(\\ |\\-|)[0-9]{4}(\\D|$)")); compositeFinder.add(new CreditCardFinder("Diners Club 2", START_BLOCK + "(36|38)[0-9]{2}(\\ |\\-|)[0-9]{6}(\\ |\\-|)[0-9]{4}(\\D|$)")); compositeFinder.add(new CreditCardFinder("Discover", START_BLOCK + "6011(\\ |\\-|)[0-9]{4}(\\ |\\-|)[0-9]{4}(\\ |\\-|)[0-9]{4}(\\D|$)")); compositeFinder.add(new CreditCardFinder("JCB 1", START_BLOCK + "3[0-9]{3}(\\ |\\-|)[0-9]{4}(\\ |\\-|)[0-9]{4}(\\ |\\-|)[0-9]{4}(\\D|$)")); compositeFinder.add(new CreditCardFinder("JCB 2", START_BLOCK + "(2131|1800)[0-9]{11}(\\D|$)")); } @Override public FinderResult find(String sample) { return compositeFinder.find(sample); } @Override public String getName() { return compositeFinder.getName(); } }
2,505
43.75
151
java
chlorine-finder
chlorine-finder-master/src/main/java/io/dataapps/chlorine/pattern/CreditCardFinder.java
/* * Copyright 2016, DataApps Corporation (http://dataApps.io) . * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.dataapps.chlorine.pattern; import io.dataapps.chlorine.finder.FinderResult; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; public class CreditCardFinder extends RegexFinder { public CreditCardFinder(String name, String pattern) { super(name, pattern); } @Override public FinderResult find(String input) { List<String> matches = new ArrayList<>(); Matcher matcher = pattern.matcher(input); while (matcher.find()) { String match = input.substring(matcher.start()+1, matcher.end()-1); if (postMatchCheck(match)) { matches.add(match); } } return new FinderResult(matches, FinderUtil.removeMatches(input, matches)); } protected boolean postMatchCheck(String match) { String numerics = match.replaceAll("[^\\d.]", ""); int[] digits = new int[numerics.length()]; for (int i=0; i < digits.length; i++) { char c = numerics.charAt(i); digits[i] = c - '0'; } return luhnCheck(digits); } private static boolean luhnCheck(int[] digits) { // http://stackoverflow.com/questions/20740444/check-credit-card-validity-using-luhn-algorithm int sum = 0; int length = digits.length; for (int i = 0; i < length; i++) { int digit = digits[length - i - 1]; if (i % 2 == 1) { digit *= 2; } sum += digit > 9 ? digit - 9 : digit; } return sum % 10 == 0; } }
1,999
26.39726
96
java
chlorine-finder
chlorine-finder-master/src/main/java/io/dataapps/chlorine/pattern/FinderUtil.java
/* * Copyright 2016, DataApps Corporation (http://dataApps.io) . * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.dataapps.chlorine.pattern; import java.util.List; import java.util.regex.Pattern; public class FinderUtil { public static String removeMatches(String input, List<String> matches) { return replaceMatches(input, matches, ""); } public static String replaceMatches(String input, List<String> matches, String replacement) { if (matches.size() > 0) { StringBuilder sb = new StringBuilder("("); boolean first = true; for (String match:matches) { if (!first) { sb.append("|"); } sb.append(Pattern.quote(match)); first = false; } sb.append(")"); return input.replaceAll(sb.toString(), replacement); } else { return input; } } }
1,322
27.76087
94
java
chlorine-finder
chlorine-finder-master/src/main/java/io/dataapps/chlorine/finder/CompositeFinder.java
/* * Copyright 2016, DataApps Corporation (http://dataApps.io) . * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.dataapps.chlorine.finder; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; /** * A class which can contain a group of Finders. * Tries to match with all of the internal Finders * */ public class CompositeFinder implements Finder { private String name; private List<Finder> finders = new ArrayList<>(); /** * Create a CompositeFinder. * @param name */ public CompositeFinder(String name) { this.name = name; } /** * set the name. * @param name */ public void setName(String name) { this.name = name; } /** * Get name of the Finder. */ public String getName() { return name; } /** * Set a list of Finders on the CompositeFInder * @param finders */ public void setFinders(List<Finder> finders) { this.finders = finders; } /** * Get a list of all finders associated with the CompositeFinder. * @return All Finders associated with the CompositeFinder. */ public List<Finder> getFinders() { return finders; } /** * add a Finder to the CompositeFinder * @param finder */ public void add(Finder finder) { finders.add(finder); } /** * Scan the input using the finders. * Return a list of actual matched values. * @return a list of matches */ public FinderResult find(String input) { List<String> list = new ArrayList<>(); String temp = input; for (Finder finder : finders) { FinderResult result = finder.find(temp); list.addAll(result.getMatches()); temp = result.getMatchesRemoved(); } return new FinderResult(list, temp); } /** * Scan the list of inputs using the finders. * Return a map of finder to actual matched values. * @return a map of finder to the corresponding matches. */ public Map<String, List<String>> findWithType(String input) { Map<String, List<String>> map = new HashMap<>(); String temp = input; for (Finder finder : finders) { FinderResult result = finder.find(temp); addToMap(map, finder, result.getMatches()); temp = result.getMatchesRemoved(); } return map; } private void addToMap(Map<String, List<String>> map, Finder finder, List<String> matches) { if (!matches.isEmpty()) { List<String> existingMatches = map.get(finder.getName()); if (existingMatches == null) { existingMatches = new ArrayList<>(); map.put(finder.getName(), existingMatches); } existingMatches.addAll(matches); } } }
3,095
23.571429
92
java
chlorine-finder
chlorine-finder-master/src/main/java/io/dataapps/chlorine/finder/Finder.java
/* * Copyright 2016, DataApps Corporation (http://dataApps.io) . * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.dataapps.chlorine.finder; /** * Interface for Finders * To add a new Java Finder, one needs to implement Finder interface. * */ public interface Finder { /** * Name of the Finder * @return name of the Finder */ public String getName(); /** * Accepts an input value and * returns a collection of sensitive values found in the inputs. * @param input - String to be scanned. * @return List of sensitive values */ public FinderResult find(String input); }
1,139
26.142857
75
java
chlorine-finder
chlorine-finder-master/src/main/java/io/dataapps/chlorine/finder/FinderResult.java
/* * Copyright 2016, DataApps Corporation (http://dataApps.io) . * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.dataapps.chlorine.finder; import java.util.List; public class FinderResult { List<String> matches; String matchesRemoved; public FinderResult() {} public FinderResult (List<String> matches, String matchesRemoved) { this.matches = matches; this.matchesRemoved = matchesRemoved; } public List<String> getMatches() { return matches; } public void setMatches(List<String> matches) { this.matches = matches; } public String getMatchesRemoved() { return matchesRemoved; } public void setMatchesRemoved(String matchesRemoved) { this.matchesRemoved = matchesRemoved; } }
1,234
27.068182
75
java
chlorine-finder
chlorine-finder-master/src/main/java/io/dataapps/chlorine/finder/DefaultFinderProvider.java
/* * Copyright 2016, DataApps Corporation (http://dataApps.io) . * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.dataapps.chlorine.finder; import io.dataapps.chlorine.pattern.RegexFinder; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** * The default FinderProvider looks up finders.xml in the classpath. * Reads all the finders and uses it for Scanning. * A finders.xml , which is part of the library has definitions to find the following elements:<br/> * <ul> * <li>Credtcard - Different types of Credit cards with luhn check</li> * <li>Email </li> * <li>ip </li> * <li>SSN - ssn with spaces or dashes </li> * <li>Phone - US Phone format</li> * <li>Street Address - US format</li> * </ul> * The file syntax: * <?xml version="1.0" encoding="UTF-8" standalone="no"?> * <finders> * <finder> * <name>Email</name> * <pattern>(\D|^)[A-Z0-9._%+-]+@([A-Z0-9.-]+)\.([A-Z]{2,4})(\D|$)</pattern> * <enabled>true</enabled> * </finder> * ... * <finder> * <class>com.example.BirthDateFinder</class> * <enabled>true</enabled> * </finder> * ... * </finders> * */ public class DefaultFinderProvider implements FinderProvider { public static final String FINDERS_DEFAULT_XML = "finders_default.xml"; private static final Log LOG = LogFactory.getLog(DefaultFinderProvider.class); List<Finder> finders = new ArrayList<> (); boolean ignoreEnabledFlag = false; DefaultFinderProvider() { this(false); } DefaultFinderProvider(final boolean ignoreEnabledFlag) { this(DefaultFinderProvider.class.getClassLoader() .getResourceAsStream(FINDERS_DEFAULT_XML), ignoreEnabledFlag); } public DefaultFinderProvider(InputStream in) { this(in, false); } DefaultFinderProvider(InputStream in, final boolean ignoreEnabledFlag) { try { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); DefaultHandler handler = new DefaultHandler() { boolean bName = false; boolean bPattern = false; boolean bClass = false; boolean bEnabled = false; boolean bFlags = false; String name = ""; String pattern = ""; String className = ""; String strFlags = ""; int flags = RegexFinder.DEFAULT_FLAGS; String strEnabled = ""; boolean enabled = true; public void startElement(String uri, String localName,String qName, Attributes attributes) throws SAXException { if (qName.equalsIgnoreCase("NAME")) { bName = true; } else if (qName.equalsIgnoreCase("PATTERN")) { bPattern = true; } else if (qName.equalsIgnoreCase("CLASS")) { bClass = true; } else if (qName.equalsIgnoreCase("FLAGS")) { bFlags = true; } else if (qName.equalsIgnoreCase("ENABLED")) { bEnabled = true; } } public void endElement(String uri, String localName, String qName) throws SAXException { if (qName.equalsIgnoreCase("NAME")) { bName = false; name = name.trim(); } else if (qName.equalsIgnoreCase("PATTERN")) { bPattern = false; pattern = pattern.trim(); } else if (qName.equalsIgnoreCase("CLASS")) { bClass = false; className = className.trim(); } else if (qName.equalsIgnoreCase("FLAGS")) { bFlags = false; flags = Integer.parseInt(strFlags.trim()); } else if (qName.equalsIgnoreCase("ENABLED")) { bEnabled = false; enabled = Boolean.parseBoolean(strEnabled.trim()); } else if (qName.equalsIgnoreCase("FINDER")) { if (ignoreEnabledFlag || enabled) { if (!className.isEmpty()) { try { Class<?> klass = Thread.currentThread().getContextClassLoader().loadClass(className); finders.add((Finder) klass.newInstance()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) { LOG.error(e); } } else if (flags != RegexFinder.DEFAULT_FLAGS) { finders.add(new RegexFinder(name, pattern, flags )); } else { finders.add(new RegexFinder(name, pattern )); } } name = ""; pattern= ""; className = ""; flags = RegexFinder.DEFAULT_FLAGS; strFlags = ""; enabled = true; strEnabled = ""; } } public void characters(char ch[], int start, int length) throws SAXException { if (bName) { name += new String(ch, start, length); } else if (bPattern) { pattern += new String(ch, start, length); } else if (bClass) { className += new String(ch, start, length); } else if (bEnabled) { strEnabled += new String(ch, start, length); } else if (bFlags) { strFlags += new String(ch, start, length); } } }; saxParser.parse(in, handler); } catch (Exception e) { LOG.error(e); } } @Override public List<Finder> getFinders() { return finders; } }
5,738
29.04712
100
java
chlorine-finder
chlorine-finder-master/src/main/java/io/dataapps/chlorine/finder/FinderEngine.java
/* * Copyright 2016, DataApps Corporation (http://dataApps.io) . * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.dataapps.chlorine.finder; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * A class which houses a buch of Finders * The FinderEngine relies on a list of FinderProviders to create Finders. * It also accepts a list of Finders. * During initialization, a DefaultFinderProvider is used. * * */ public class FinderEngine extends CompositeFinder { private static final Log LOG = LogFactory.getLog(FinderEngine.class); /** * Creates a FinderEngine. * Adds all Default Finders. */ public FinderEngine() { this((List<Finder>)null, true); } /** * Creates a FinderEngine. * Reads all finders from file. * The file syntax is as follows : * <?xml version="1.0" encoding="UTF-8" standalone="no"?> * <finders> * <finder> * <name>Email</name> * <pattern>(\D|^)[A-Z0-9._%+-]+@([A-Z0-9.-]+)\.([A-Z]{2,4})(\D|$)</pattern> * <enabled>true</enabled> * </finder> * ... * <finder> * <class>com.example.BirthDateFinder</class> * <enabled>true</enabled> * </finder> * ... * </finders> * * * * </finders> * Adds all Default Finders. */ public FinderEngine(String fileName) { this(fileName, false); } /** * Creates a FinderEngine. * Reads all finders from file. * If fromClassPath is true, reads the file from the class path. * * Adds all Default Finders. */ public FinderEngine(String fileName, boolean fromClassPath) { this(fileName, fromClassPath, true); } /** * Creates a FinderEngine. * Reads all finders from file. * If fromClassPath is true, reads the file from the class path. * If addDefaultFinders is true, adds all Default Finders. */ public FinderEngine(String fileName, boolean fromClassPath, boolean addDefaultFinders) { this(new DefaultFinderProvider(getInputStream(fileName, fromClassPath)), addDefaultFinders); } private static InputStream getInputStream(String fileName, boolean fromClassPath) { InputStream in = null; if (fromClassPath) { in = FinderEngine.class.getClassLoader() .getResourceAsStream(fileName); } else { try { in = new FileInputStream(fileName); } catch (FileNotFoundException e) { LOG.warn(e.getMessage()); } } return in; } /** * Creates a FinderEngine. * Reads all finders from InputStream. * Adds all Default Finders. */ public FinderEngine(InputStream in) { this(new DefaultFinderProvider(in), true); } /** * Creates a FinderEngine. * Includes all finders from FinderProvider. * If addDefaultFinders is true, adds all Default Finders. */ public FinderEngine(InputStream in, boolean addDefaultFinders) { this(new DefaultFinderProvider(in), addDefaultFinders); } /** * Creates a FinderEngine. * Includes all finders from FinderProvider. * Adds all Default Finders. */ public FinderEngine(FinderProvider finderProvider) { this(finderProvider.getFinders(), true); } /** * Creates a FinderEngine. * Includes all finders from the given FinderProviders. * Adds all Default Finders. */ public FinderEngine(Set<FinderProvider> finderProviders) { this(createFinders(finderProviders), true); } /** * Creates a FinderEngine. * Includes all finders from the given FinderProvider. * If addDefaultFinders is true, adds all Default Finders. */ public FinderEngine(FinderProvider finderProvider, boolean addDefaultFinders) { this(finderProvider.getFinders(), addDefaultFinders); } /** * Creates a FinderEngine. * Include all finders from FinderProviders. * If addDefaultFinders is true, adds all Default Finders. */ public FinderEngine(Set<FinderProvider> finderProviders, boolean addDefaultFinders) { this(createFinders(finderProviders), addDefaultFinders); } /** * Creates a FinderEngine. * Includes all finders from the list of Finders. * Adds all Default Finders. */ public FinderEngine(List<Finder> finders) { this(finders, true); } /** * Creates a FinderEngine. * Includes all finders from the list of Finders. * If addDefaultFinders is true, adds all Default Finders. */ public FinderEngine(List<Finder> finders, boolean addDefaultFinders) { this(finders, addDefaultFinders, false); } /** * Creates a FinderEngine. * Includes all finders from the list of Finders. * If addDefaultFinders is true, adds all Default Finders. * If ignoreEnabledFlag is true, includes all disabled Finders too. This is used for testing. * */ public FinderEngine(List<Finder> finders, boolean addDefaultFinders, boolean ignoreEnabledFlag) { super("FinderEngine"); List<Finder> list = new ArrayList<>(); if (finders != null) { list.addAll(finders); } if (addDefaultFinders) { list.addAll(new DefaultFinderProvider(ignoreEnabledFlag).getFinders()); } setFinders(list); } private static List<Finder> createFinders(Set<FinderProvider> finderProviders) { List<Finder> finders = new ArrayList<>(); for (FinderProvider provider: finderProviders) { finders.addAll(provider.getFinders()); } return finders; } }
5,943
27.170616
99
java
chlorine-finder
chlorine-finder-master/src/main/java/io/dataapps/chlorine/finder/FinderProvider.java
/* * Copyright 2016, DataApps Corporation (http://dataApps.io) . * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.dataapps.chlorine.finder; import java.util.List; /** * A provider for Finders. * DefaultFinderProvider provides finders read from finders.xml */ public interface FinderProvider { /** * * @return a list of Finders */ List<Finder> getFinders(); }
898
28
75
java
cobra-icaps2015-icaps2015/src/main/java/tt/euclid2i/trajectory/DelayedStartTrajectory.java
cobra-icaps2015-icaps2015/src/main/java/tt/euclid2i/trajectory/DelayedStartTrajectory.java
package tt.euclid2i.trajectory; import tt.euclid2i.EvaluatedTrajectory; import tt.euclid2i.Point; import tt.euclid2i.Trajectory; public class DelayedStartTrajectory implements EvaluatedTrajectory { EvaluatedTrajectory baseTraj; int delay; public DelayedStartTrajectory(EvaluatedTrajectory baseTraj, int delay) { super(); this.baseTraj = baseTraj; this.delay = delay; } @Override public int getMinTime() { return baseTraj.getMinTime(); } @Override public int getMaxTime() { return baseTraj.getMaxTime() + delay; } @Override public Point get(int t) { if (t <= baseTraj.getMinTime() + delay) { return baseTraj.get(0); } else { return baseTraj.get(t-delay); } } @Override public double getCost() { return baseTraj.getCost(); } }
775
17.046512
73
java
cobra-icaps2015-icaps2015/src/main/java/tt/euclidtime3i/region/MovingCircleMinusPoint.java
cobra-icaps2015-icaps2015/src/main/java/tt/euclidtime3i/region/MovingCircleMinusPoint.java
package tt.euclidtime3i.region; import tt.euclidtime3i.Point; import tt.euclidtime3i.Region; public class MovingCircleMinusPoint implements Region { private MovingCircle movingCircle; private tt.euclid2i.Point pointToSubtract; public MovingCircleMinusPoint(MovingCircle movingCircle, tt.euclid2i.Point pointToSubtract) { super(); this.movingCircle = movingCircle; this.pointToSubtract = pointToSubtract; } @Override public boolean intersectsLine(Point p1, Point p2) { if (p1.getPosition().equals(pointToSubtract) && p2.getPosition().equals(pointToSubtract)) { return false; } return movingCircle.intersectsLine(p1, p2); } @Override public HyperRectangle getBoundingBox() { return movingCircle.getBoundingBox(); } @Override public String toString() { return (movingCircle.toString() + "\\" + pointToSubtract.toString()); } @Override public boolean isInside(Point p) { if (p.getPosition().equals(pointToSubtract)) { return false; } else { return movingCircle.isInside(p); } } }
1,084
23.111111
97
java
cobra-icaps2015-icaps2015/src/main/java/tt/euclidtime3i/region/CircleMovingToTarget.java
cobra-icaps2015-icaps2015/src/main/java/tt/euclidtime3i/region/CircleMovingToTarget.java
package tt.euclidtime3i.region; import tt.euclid2i.Trajectory; public class CircleMovingToTarget extends MovingCircle { private int targetReachedTime; public CircleMovingToTarget(Trajectory trajectory, int radius, int targetReachedTime) { super(trajectory, radius); this.targetReachedTime = targetReachedTime; } public int getTargetReachedTime() { return targetReachedTime; } @Override public String toString() { return "MC(" + Integer.toHexString(trajectory.hashCode()) + ", r=" + radius + ", tdest="+ targetReachedTime + ")"; } }
572
23.913043
122
java
cobra-icaps2015-icaps2015/src/main/java/tt/euclidtime3i/util/IntersectionCheckerWithProtectedPoint.java
cobra-icaps2015-icaps2015/src/main/java/tt/euclidtime3i/util/IntersectionCheckerWithProtectedPoint.java
package tt.euclidtime3i.util; import java.util.Collection; import tt.euclid2i.Point; import tt.euclid2i.util.SeparationDetector; import tt.euclidtime3i.Region; import tt.euclidtime3i.region.MovingCircle; import tt.util.NotImplementedException; public class IntersectionCheckerWithProtectedPoint { public static boolean intersect(Region thisRegion, Collection<? extends Region> obstacleCollection, Point protectedPoint) { assert(thisRegion != null); assert(!obstacleCollection.contains(null)); Region[] obstacles = obstacleCollection.toArray(new Region[1]); for (int j = 0; j < obstacles.length; j++) { if (obstacles[j] != null) { if (/*thisRegion.getBoundingBox().intersects(obstacles[j].getBoundingBox())*/ true) { if (intersectIgnoreProtectedPoint(thisRegion, obstacles[j], protectedPoint)) { return true; } } } } return false; } public static boolean intersectIgnoreProtectedPoint(Region thisRegion, Region otherRegion, Point protectedPoint) { if (thisRegion instanceof MovingCircle && otherRegion instanceof MovingCircle) { MovingCircle thisMc = (MovingCircle) thisRegion; MovingCircle otherMc = (MovingCircle) otherRegion; return SeparationDetector.hasConflictIgnoreProtectedPoint( thisMc.getTrajectory(), otherMc.getTrajectory(), protectedPoint, thisMc.getRadius() + otherMc.getRadius(), (int) Math.floor(Math.min(thisMc.getRadius(), otherMc.getRadius())/4.0)); } throw new NotImplementedException("The conflict checking of " + thisRegion.getClass() + " vs. " + otherRegion.getClass() + " not implemented yet"); } }
1,723
34.916667
149
java
cobra-icaps2015-icaps2015/src/main/java/cz/agents/alite/common/event/DurativeEventProcessor.java
cobra-icaps2015-icaps2015/src/main/java/cz/agents/alite/common/event/DurativeEventProcessor.java
package cz.agents.alite.common.event; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import java.util.PriorityQueue; import java.util.Queue; import java.util.SortedSet; import java.util.TreeSet; import org.apache.log4j.Level; import org.apache.log4j.Logger; import tt.util.Counters; import cz.agents.alite.common.event.ActivityLogEntry.Type; public class DurativeEventProcessor { private volatile boolean running = true; private volatile boolean finished = false; private long eventIdCounter = 0; private Thread thread = Thread.currentThread(); private final Queue<DurativeEvent> eventQueue = new PriorityQueue<DurativeEvent>(); private final Map<String,Long> processLastActivityFinishedTimes = new HashMap<String, Long>(); private final Map<String,Long> processIdleCounter = new HashMap<String, Long>(); private final Map<String,Long> processActiveCounter = new HashMap<String, Long>(); private long lastEventStartedAtNanos = 0; private long currentEventTime = 0; private boolean keepActivityLog = false; private Collection<ActivityLogEntry> activityLog = new LinkedList<ActivityLogEntry>(); public void run() { DurativeEvent event = eventQueue.poll(); while (event != null) { beforeProcessingEvent(event); long time = event.getTime(); String processName = event.getProcess(); long lastActivityFinishes = getProcessLastActivityFinishedTime(processName); if (keepActivityLog) activityLog.add(new ActivityLogEntry(processName, Type.EVENT_RECIEVED, time, 0, 0)); if (time >= lastActivityFinishes) { // process is idle long idleTime = time - lastActivityFinishes; processIdleCounter.put(processName, getProcessIdleCounter(processName) + idleTime); if (keepActivityLog && idleTime > 0) { activityLog.add(new ActivityLogEntry(processName, Type.IDLE, lastActivityFinishes, idleTime, 0)); } while (!running) { synchronized (thread) { try { if (!running) { thread.wait(); } } catch (InterruptedException ex) { Logger.getLogger(EventProcessor.class.getName()).log(Level.ERROR, null, ex); } } } int expandedStatesBefore = Counters.expandedStatesCounter; long duration = fireEvent(event); int expandedStatesAfter = Counters.expandedStatesCounter; processActiveCounter.put(processName, getProcessActiveCounter(processName) + duration); processLastActivityFinishedTimes.put(processName, time + duration); if (keepActivityLog) activityLog.add(new ActivityLogEntry(processName, Type.EVENT_HANDLED, time, duration, expandedStatesAfter - expandedStatesBefore)); } else { // move to future addEvent(lastActivityFinishes, processName, event.getHandler()); } event = eventQueue.poll(); } finished = true; running = false; } /** * Ends the the event processor by clearing the event queue. * * This method has to be called from the same thread as the run() method was called! */ public void clearQueue() { eventQueue.clear(); } public void addEvent(long time, String process, DurativeEventHandler eventHandler) { DurativeEvent event = new DurativeEvent(eventIdCounter++, time, process, eventHandler); eventQueue.add(event); } /** * Method pauses and un-pauses the processing of the events. * * The method can be called from other threads (than the run() method was called). * * @param running */ public void setRunning(boolean running) { this.running = running; if (running) { synchronized (thread) { thread.notify(); } } } /** * The method can be called from other threads (than the run() method was called). */ public boolean isRunning() { return running; } /** * The method can be called from other threads (than the run() method was called). */ public boolean isFinished() { return finished; } /** * The method can be called from other threads (than the run() method was called). */ public long getProcessLastActivityFinishedTime(String process) { if (processLastActivityFinishedTimes.containsKey(process)) { return processLastActivityFinishedTimes.get(process); } else { return 0; } } protected SortedSet<String> getProcessNames(){ return new TreeSet<String>(processLastActivityFinishedTimes.keySet()); } /** * The method can be called from other threads (than the run() method was called). */ public int getCurrentQueueLength() { return eventQueue.size(); } protected void breforeRunningTest(DurativeEvent event) { } /** * @return duration of the event handling */ private long fireEvent(DurativeEvent event) { if (event.getHandler() != null) { currentEventTime = event.getTime(); lastEventStartedAtNanos = System.nanoTime(); long duration = event.getHandler().handleEvent(event); if (duration == DurativeEventHandler.COUNT_SYSTEM_NANOS) { duration = getCurrentEventHandlingDurationNanos(); } return duration; } return 0; } public long getProcessIdleCounter(String processName) { if (processIdleCounter.containsKey(processName)) { return processIdleCounter.get(processName); } else { return 0; } } protected long getProcessActiveCounter(String processName) { if (processActiveCounter.containsKey(processName)) { return processActiveCounter.get(processName); } else { return 0; } } public long getCurrentEventHandlingDurationNanos() { if (lastEventStartedAtNanos != 0) { return System.nanoTime() - lastEventStartedAtNanos; } else { return 0; } } public long getCurrentEventTime() { return currentEventTime; } protected void beforeProcessingEvent(DurativeEvent event) {} public String getProcessTimesAsString() { StringBuilder sb = new StringBuilder(); for (String processName : getProcessNames()) { sb.append(processName); sb.append("@"); sb.append(processLastActivityFinishedTimes.get(processName)); sb.append(" "); } return sb.toString(); } public Collection<ActivityLogEntry> getActivityLog() { return activityLog; } public void setKeepActivityLog(boolean keepActivityLog) { this.keepActivityLog = keepActivityLog; } }
7,420
30.987069
148
java
cobra-icaps2015-icaps2015/src/main/java/cz/agents/alite/common/event/ActivityLogEntry.java
cobra-icaps2015-icaps2015/src/main/java/cz/agents/alite/common/event/ActivityLogEntry.java
package cz.agents.alite.common.event; public class ActivityLogEntry { public static enum Type {EVENT_HANDLED, IDLE, EVENT_RECIEVED}; public String processName; public Type type; public long startTime; public long duration; public long expandedStates; public ActivityLogEntry(String processName, Type type, long startTime, long duration, long expandedStates) { super(); this.processName = processName; this.type = type; this.startTime = startTime; this.duration = duration; this.expandedStates = expandedStates; } }
543
23.727273
71
java
cobra-icaps2015-icaps2015/src/main/java/cz/agents/alite/common/event/DurativeEventHandler.java
cobra-icaps2015-icaps2015/src/main/java/cz/agents/alite/common/event/DurativeEventHandler.java
package cz.agents.alite.common.event; public interface DurativeEventHandler { final static long COUNT_SYSTEM_NANOS = -1; public DurativeEventProcessor getEventProcessor(); /** * @return the duration of computation associated with handling the event, * in simulation time. * Returns {@link DurativeEventHandler#COUNT_SYSTEM_NANOS} * if the duration of the event should be determined automatically * using the walltime. */ public long handleEvent(DurativeEvent event); }
550
26.55
78
java
cobra-icaps2015-icaps2015/src/main/java/cz/agents/alite/common/event/DurativeEvent.java
cobra-icaps2015-icaps2015/src/main/java/cz/agents/alite/common/event/DurativeEvent.java
package cz.agents.alite.common.event; public final class DurativeEvent implements Comparable<DurativeEvent> { private final long id; private final long time; private final String process; private final DurativeEventHandler handler; public DurativeEvent(long id, long time, String process, DurativeEventHandler handler) { super(); this.id = id; this.time = time; this.process = process; this.handler = handler; } public long getTime() { return time; } public String getProcess() { return process; } public DurativeEventHandler getHandler() { return handler; } @Override public int compareTo(DurativeEvent event) { if (time == event.time) { if (id == event.id) { throw new RuntimeException("Found same event ids in comparation!"); } return (id < event.id ? -1 : 1); } else { return (time < event.time ? -1 : (time == event.time ? 0 : 1)); } } @Override public String toString() { return time + "@" + process + ": " + handler; } }
1,112
20.823529
92
java
cobra-icaps2015-icaps2015/src/main/java/cz/agents/alite/communication/InboxBasedCommunicator.java
cobra-icaps2015-icaps2015/src/main/java/cz/agents/alite/communication/InboxBasedCommunicator.java
package cz.agents.alite.communication; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import cz.agents.alite.communication.channel.CommunicationChannelException; import cz.agents.alite.communication.content.Content; import cz.agents.alite.communication.content.error.ErrorContent; import cz.agents.alite.communication.eventbased.ConcurrentProcessCommunicationChannel; public class InboxBasedCommunicator implements Communicator { private final String address; private ConcurrentProcessCommunicationChannel channel = null; private final List<MessageHandler> messageHandlers = new CopyOnWriteArrayList<MessageHandler>(); private int messagesSent = 0; private static long counter = System.currentTimeMillis(); /** * * @param address */ public InboxBasedCommunicator(String address) { this.address = address; } /** * Adds communication channel to the communicator. * * @param channel */ public void setChannel(ConcurrentProcessCommunicationChannel channel) { this.channel = channel; } @Override public String getAddress() { return address; } @Override public Message createMessage(Content content) { return new Message(address, content, generateId()); } @Override public Message createReply(Message message, Content content) { Message reply = new Message(address, content, generateId()); reply.addReceiver(message.getSender()); return reply; } @Override public void addMessageHandler(MessageHandler handler) { messageHandlers.add(handler); } @Override public void removeMessageHandler(MessageHandler handler) { messageHandlers.remove(handler); } @Override public void sendMessage(Message message) { try { messagesSent++; channel.sendMessage(message); } catch (CommunicationChannelException e) { Message errorMessage = createMessage(new ErrorContent(e)); errorMessage.addReceiver(getAddress()); receiveMessage(errorMessage); } }; @Override public synchronized void receiveMessage(Message message) { for (MessageHandler messageHandler : messageHandlers) { messageHandler.notify(message); } } private long generateId() { return address.hashCode() + counter; } public int getInboxSize() { return channel.getInboxSize(address); } public int getMessagesSent() { return messagesSent; } }
2,610
24.598039
100
java
cobra-icaps2015-icaps2015/src/main/java/cz/agents/alite/communication/eventbased/ConcurrentProcessCommunicationChannel.java
cobra-icaps2015-icaps2015/src/main/java/cz/agents/alite/communication/eventbased/ConcurrentProcessCommunicationChannel.java
package cz.agents.alite.communication.eventbased; import java.util.LinkedList; import java.util.List; import java.util.Map; import cz.agents.alite.common.event.DurativeEvent; import cz.agents.alite.common.event.DurativeEventHandler; import cz.agents.alite.common.event.DurativeEventProcessor; import cz.agents.alite.communication.CommunicationReceiver; import cz.agents.alite.communication.Message; import cz.agents.alite.communication.channel.CommunicationChannelException; import cz.agents.alite.communication.channel.DirectCommunicationChannel; public class ConcurrentProcessCommunicationChannel extends DirectCommunicationChannel { private final DurativeEventProcessor eventProcessor; private final long messageDelay = 0; private final Map<String, List<Long>> inboxCounters; public ConcurrentProcessCommunicationChannel(CommunicationReceiver communicator, DurativeEventProcessor eventProcessor, ReceiverTable channelReceiverTable, Map<String, List<Long>> inboxCounters) throws CommunicationChannelException { super(communicator, channelReceiverTable); this.eventProcessor = eventProcessor; this.inboxCounters = inboxCounters; } @Override protected void callDirectReceive(final CommunicationReceiver receiver, final Message message) { long lastEventDuration = eventProcessor .getCurrentEventHandlingDurationNanos(); /// This is probably wrong!!!! /* callDirectReceive( eventProcessor.getProcessLastActivityFinishedTime(this.getCommunicationReceiver() .getAddress()) + lastEventDuration + messageDelay, receiver, message); */ callDirectReceive( eventProcessor.getCurrentEventTime() + lastEventDuration + messageDelay, receiver, message); } protected void callDirectReceive(final long time, final CommunicationReceiver receiver, final Message message) { recordToInboxCounter(receiver.getAddress(), time); eventProcessor.addEvent(time, receiver.getAddress(), new DurativeEventHandler() { @Override public DurativeEventProcessor getEventProcessor() { return eventProcessor; } @Override public long handleEvent(DurativeEvent event) { removeFromInboxCounter(event.getProcess(), time); receiver.receiveMessage(message); return COUNT_SYSTEM_NANOS; } }); } private void recordToInboxCounter(String processName, long time) { if (!inboxCounters.containsKey(processName)) { inboxCounters.put(processName, new LinkedList<Long>()); } inboxCounters.get(processName).add(time); } private void removeFromInboxCounter(String processName, long time) { inboxCounters.get(processName).remove(time); } public int getInboxSize(String processName) { long currentTime = eventProcessor.getCurrentEventTime() + eventProcessor.getCurrentEventHandlingDurationNanos(); if (inboxCounters.containsKey(processName)) { int counter = 0; for (long timeStamp : inboxCounters.get(processName)) { if (timeStamp <= currentTime) { counter++; } } return counter; } else { return 0; } } }
3,470
34.783505
237
java
cobra-icaps2015-icaps2015/src/main/java/cz/agents/alite/simulation/ConcurrentProcessSimulation.java
cobra-icaps2015-icaps2015/src/main/java/cz/agents/alite/simulation/ConcurrentProcessSimulation.java
package cz.agents.alite.simulation; import org.apache.log4j.Level; import org.apache.log4j.Logger; import cz.agents.alite.common.event.DurativeEvent; import cz.agents.alite.common.event.DurativeEventProcessor; import cz.agents.alite.common.event.EventProcessor; public class ConcurrentProcessSimulation extends DurativeEventProcessor { private Logger LOGGER = Logger.getLogger(ConcurrentProcessSimulation.class); private long eventCount = 0; private long runTime; private int printouts = 10000; private double simulationSpeed = 0; public ConcurrentProcessSimulation() { } @Override public void run() { runTime = System.currentTimeMillis(); LOGGER.info(">>> CONCURRENT PROCESS SIMULATION START"); super.run(); LOGGER.info(">>> SIMULATION FINISH"); for (String processName : getProcessNames()) { LOGGER.info(String.format(">>> PROCESS TERMINATION TIME: %s %.4fs (Active: %.4fs Idle: %.4fs)", processName,getProcessLastActivityFinishedTime(processName)/1e9d, getProcessActiveCounter(processName)/1e9d, getProcessIdleCounter(processName)/1e9f)); } LOGGER.info(String.format(">>> EVENT COUNT: %d", eventCount)); LOGGER.info(String.format(">>> RUNTIME: %.2fs", (System.currentTimeMillis() - runTime) / 1000.0)); } public long getEventCount() { return eventCount; } /** print every n-th event */ public void setPrintouts(int n) { this.printouts = n; } @Override protected void beforeProcessingEvent(DurativeEvent event) { ++eventCount; long timeToSleep = (long) ((event.getTime() - getCurrentEventTime()) * simulationSpeed); if ((simulationSpeed > 0) && (timeToSleep > 0)) { try { Thread.sleep(timeToSleep / 1000000); } catch (InterruptedException ex) { Logger.getLogger(EventProcessor.class.getName()).log(Level.ERROR, null, ex); } } if (eventCount % printouts == 0) { LOGGER.debug(String.format( ">>> SIM. TIME: %s / RUNTIME: %.2fs / EVENTS: %d / QUEUE: %d", getProcessTimesAsString(), (System.currentTimeMillis() - runTime) / 1000.0, eventCount, getCurrentQueueLength())); } } public long getCumulativeActiveRuntime() { long result = 0; for (String processName : getProcessNames() ) { result += getProcessLastActivityFinishedTime(processName) - getProcessIdleCounter(processName); } return result; } public long getCumulativeIdleRuntime() { long result = 0; long wallclock = getWallclockRuntime(); for (String processName : getProcessNames() ) { result += getProcessIdleCounter(processName); result += wallclock - this.getProcessLastActivityFinishedTime(processName); } return result; } public long getWallclockRuntime() { long max = 0; for (String processName : getProcessNames() ) { long processLastActivityFinished = getProcessLastActivityFinishedTime(processName); if (processLastActivityFinished > max) { max = processLastActivityFinished; } } return max; } /** 0 means maximum */ public void setSimulationSpeed(final double simulationSpeed) { this.simulationSpeed = simulationSpeed; } public double getSimulationSpeed() { return simulationSpeed; } }
3,655
32.236364
259
java
cobra-icaps2015-icaps2015/src/main/java/cz/agents/alite/simulation/vis/SimulationControlLayer.java
cobra-icaps2015-icaps2015/src/main/java/cz/agents/alite/simulation/vis/SimulationControlLayer.java
package cz.agents.alite.simulation.vis; import java.awt.Color; import java.awt.Graphics2D; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.text.MessageFormat; import cz.agents.alite.vis.Vis; import cz.agents.alite.vis.layer.AbstractLayer; import cz.agents.alite.vis.layer.VisLayer; import cz.agents.alite.vis.layer.toggle.KeyToggleLayer; public class SimulationControlLayer extends AbstractLayer { static public interface SimulationControlProvider { double getTime(); boolean isRunning(); void setRunning(boolean running); float getSpeed(); void setSpeed(float f); } private final SimulationControlProvider simulationCtrl; private KeyListener keyListener; SimulationControlLayer(SimulationControlProvider simulationControlProvider) { this.simulationCtrl = simulationControlProvider; } @Override public void init(Vis vis) { super.init(vis); keyListener = new KeyListener() { @Override public void keyTyped(KeyEvent e) { } @Override public void keyReleased(KeyEvent e) { } @Override public void keyPressed(KeyEvent e) { if (e.getKeyChar() == '+') { simulationCtrl.setSpeed(simulationCtrl.getSpeed() * 0.8f); } else if (e.getKeyChar() == '-') { simulationCtrl.setSpeed(simulationCtrl.getSpeed() * 1.2f); } else if (e.getKeyChar() == '*') { simulationCtrl.setSpeed(1.0f); } else if (e.getKeyChar() == ' ') { if (simulationCtrl.isRunning()) { simulationCtrl.setRunning(false); } else { simulationCtrl.setRunning(true); } } } }; vis.addKeyListener(keyListener); } @Override public void deinit(Vis vis) { super.deinit(vis); vis.removeKeyListener(keyListener); } @Override public void paint(Graphics2D canvas) { StringBuilder label = new StringBuilder(); label.append("Time: "); label.append(String.format("%.2f", simulationCtrl.getTime())); label.append(" "); if (simulationCtrl.isRunning()) { label.append("("); label.append(MessageFormat.format("{0,number,#.##}", 1/simulationCtrl.getSpeed())); label.append("x)"); } else { label.append("(PAUSED)"); } canvas.setColor(Color.BLUE); canvas.drawString(label.toString(), 15, 20); } public static VisLayer create( SimulationControlProvider simulationCtrlProvider) { VisLayer simulationControl = new SimulationControlLayer( simulationCtrlProvider); KeyToggleLayer toggle = KeyToggleLayer.create("s"); toggle.addSubLayer(simulationControl); toggle.setHelpOverrideString(simulationControl.getLayerDescription() + "\n" + "By pressing 's', the simulation info can be turned off and on."); return toggle; } }
2,745
23.963636
95
java
cobra-icaps2015-icaps2015/src/main/java/cz/agents/map4rt/CommonTime.java
cobra-icaps2015-icaps2015/src/main/java/cz/agents/map4rt/CommonTime.java
package cz.agents.map4rt; public class CommonTime { static long startedAt = System.currentTimeMillis(); public static int currentTimeMs() { return (int) (System.currentTimeMillis() - startedAt); } }
208
19.9
56
java
cobra-icaps2015-icaps2015/src/main/java/cz/agents/map4rt/ScenarioCreator.java
cobra-icaps2015-icaps2015/src/main/java/cz/agents/map4rt/ScenarioCreator.java
package cz.agents.map4rt; import java.awt.Color; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.text.DecimalFormat; import java.util.Arrays; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Random; import org.apache.log4j.Logger; import org.jgrapht.DirectedGraph; import tt.euclid2i.Line; import tt.euclid2i.Point; import tt.euclid2i.Trajectory; import tt.euclid2i.probleminstance.Environment; import tt.jointeuclid2ni.probleminstance.RelocationTaskCoordinationProblem; import tt.jointeuclid2ni.probleminstance.TrajectoryCoordinationProblemXMLDeserializer; import tt.jointeuclid2ni.probleminstance.VisUtil; import tt.jointeuclid2ni.solver.Parameters; import tt.util.AgentColors; import tt.util.Args; import tt.vis.FastTrajectoriesLayer; import tt.vis.FastTrajectoriesLayer.ColorProvider; import tt.vis.FastTrajectoriesLayer.TrajectoriesProvider; import tt.vis.LabeledCircleLayer; import cz.agents.alite.simulation.vis.SimulationControlLayer; import cz.agents.alite.simulation.vis.SimulationControlLayer.SimulationControlProvider; import cz.agents.alite.vis.VisManager; import cz.agents.alite.vis.layer.toggle.KeyToggleLayer; import cz.agents.map4rt.agent.Agent; import cz.agents.map4rt.agent.CurrentTasks; import cz.agents.map4rt.agent.COBRAAgent; import cz.agents.map4rt.agent.ORCAAgent; import cz.agents.map4rt.agent.PlanningAgent; public class ScenarioCreator { /* * Units: * time: 1 time unit = 1ms; * distance: 1 distance unit = depending on the map, 2cm typically. * speed: in du/ms (distance units / millisecond), typically 0.05 du/ms represents roughly 1m/1s */ //////////////////////////////////////////////////////////////////////// public static void main(String[] args) { createFromArgs(args); } /////////////////////////////////////////////////////////////////////// static long simulationStartedAt; static Logger LOGGER = Logger.getLogger(ScenarioCreator.class); enum Method { COBRA, ORCA } private static RelocationTaskCoordinationProblem problem; public static void createFromArgs(String[] args) { simulationStartedAt = System.currentTimeMillis(); Parameters params = new Parameters(); String xml = Args.getArgumentValue(args, "-problemfile", true); String methodStr = Args.getArgumentValue(args, "-method", true); String maxTimeStr = Args.getArgumentValue(args, "-maxtime", true); params.maxTime = Integer.parseInt(maxTimeStr); String timeStepStr = Args.getArgumentValue(args, "-timestep", true); params.timeStep = Integer.parseInt(timeStepStr); params.showVis = Args.isArgumentSet(args, "-showvis"); params.verbose = Args.isArgumentSet(args, "-verbose"); String timeoutStr = Args.getArgumentValue(args, "-timeout", false); params.summaryPrefix = Args.getArgumentValue(args, "-summaryprefix", false, ""); params.activityLogFile = Args.getArgumentValue(args, "-activitylog", false, null); String bgImgFileName = Args.getArgumentValue(args, "-bgimg", false, null); String simSpeedStr = Args.getArgumentValue(args, "-simspeed", false, "1"); params.simSpeed = Double.parseDouble(simSpeedStr); String nTasksStr = Args.getArgumentValue(args, "-ntasks", true); params.nTasks = Integer.parseInt(nTasksStr); String seedStr = Args.getArgumentValue(args, "-seed", true); params.random = new Random(Integer.parseInt(seedStr)); File file = new File(xml); params.fileName = file.getName(); // Load the PNG image as a background, if provided if (bgImgFileName != null) { File bgImgFile = new File(bgImgFileName); if (bgImgFile.exists()) { params.bgImageFile = bgImgFile; } } try { problem = TrajectoryCoordinationProblemXMLDeserializer.deserialize(new FileInputStream(file)); } catch (FileNotFoundException e) { throw new RuntimeException(e); } Method method = Method.valueOf(methodStr); params.runtimeDeadlineMs = 3600*1000; /* default timeout is 1 hour */ if (timeoutStr != null) { int timeout = Integer.parseInt(timeoutStr); params.runtimeDeadlineMs = timeout; killAt(System.currentTimeMillis() + timeout, params.summaryPrefix, params.noOfClusters); } create(problem, method, params); } private static void killAt(final long killAtMs, final String summaryPrefix, final int clusters) { Thread t = new Thread() { @Override public void run() { while (System.currentTimeMillis() < killAtMs) { try { Thread.sleep(50); } catch (InterruptedException e) {} } printSummary(summaryPrefix, Status.TIMEOUT, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1); System.exit(0); } }; t.start(); } public static void create(RelocationTaskCoordinationProblem problem, Method method, final Parameters params) { if (params.showVis) { VisUtil.initVisualization(problem.getEnvironment(), "Trajectory Tools ("+method.toString()+")", params.bgImageFile, params.timeStep/2); VisUtil.visualizeRelocationTaskCoordinationProblem(problem); } switch (method) { case COBRA: solveCOBRA(problem, params); break; case ORCA: solveORCA(problem, params); break; default: throw new RuntimeException("Unknown method"); } } private static void solveCOBRA(final RelocationTaskCoordinationProblem problem, final Parameters params) { simulate(problem, new AgentFactory() { @Override public Agent createAgent(String name, int i, Point start, int nTasks, Environment env, DirectedGraph<Point, Line> planningGraph, int agentBodyRadius, float speed) { PlanningAgent agent = new COBRAAgent(name, start, nTasks, env, planningGraph, agentBodyRadius, speed, params.maxTime, params.timeStep, params.random); return agent; } }, params); } private static void solveORCA(final RelocationTaskCoordinationProblem problem, final Parameters params) { simulate(problem, new AgentFactory() { @Override public Agent createAgent(String name, int i, Point start, int nTasks, Environment env, DirectedGraph<Point, Line> planningGraph, int agentBodyRadius, float speed) { Agent agent = new ORCAAgent(name, start, nTasks, env, planningGraph, agentBodyRadius, speed, params.maxTime, params.timeStep, params.showVis, params.random); return agent; } }, params); } interface AgentFactory { Agent createAgent(String name, int priority, Point start, int nTasks, Environment env, DirectedGraph<Point, Line> planningGraph, int agentBodyRadius, float speed); } private static void simulate(final RelocationTaskCoordinationProblem problem, final AgentFactory agentFactory, final Parameters params) { simulationStartedAt = System.currentTimeMillis(); CurrentTasks.docks = Arrays.asList(problem.getDocks()); // Create agents final List<Agent> agents = new LinkedList<Agent>(); for (int i=0; i<problem.getStarts().length; i++) { agents.add(agentFactory.createAgent( "a" + new DecimalFormat("00").format(i), i, problem.getStart(i), params.nTasks, problem.getEnvironment(), problem.getPlanningGraph(), problem.getBodyRadius(i), problem.getMaxSpeed(i))); } // Simulation Control Layer VisManager.registerLayer(SimulationControlLayer.create(new SimulationControlProvider() { @Override public void setSpeed(float f) {} @Override public void setRunning(boolean running) {} @Override public boolean isRunning() { return true; } @Override public double getTime() { return (CommonTime.currentTimeMs() / 1000.0); } @Override public float getSpeed() { return 1; } })); initAgentVisualization(agents, params.timeStep); LOGGER.info("=== All Agents initialized"); final int FIRST_TASK_WINDOW = 30000; final long initalizedAtMs = CommonTime.currentTimeMs(); for (final Agent agent : agents) { Thread thread = new Thread(agent.getName()) { @Override public void run() { agent.setIssueFirstTaskAt(initalizedAtMs + params.random.nextInt(FIRST_TASK_WINDOW)); agent.start(); while (!allDone(agents)) { try { Thread.sleep(100); } catch (InterruptedException e) {} agent.tick(CommonTime.currentTimeMs()); } LOGGER.info("Agent " + agent.getName() + " completed all tasks"); } }; thread.start(); } while (!allDone(agents)) { try { Thread.sleep(100); } catch (InterruptedException e) {} } long baseSum = 0; long baseSumSq = 0; long waitSum = 0; long waitSumSq = 0; long planSum = 0; long planSumSq = 0; long pWindowSum = 0; long pWindowSumSq = 0; long prolongTSum = 0; long prolongTSumSq = 0; long prolongRSum = 0; long prolongRSumSq = 0; for (Agent agent : agents) { baseSum += agent.baseSum; baseSumSq += agent.baseSumSq ; waitSum += agent.waitSum; waitSumSq += agent.waitSumSq; planSum += agent.planSum; planSumSq += agent.planSumSq; pWindowSum += agent.pWindowSum; pWindowSumSq += agent.pWindowSumSq; prolongTSum += agent.prolongTSum; prolongTSumSq += agent.prolongTSumSq; prolongRSum += agent.prolongRSum; prolongRSumSq += agent.prolongRSumSq; } long n = agents.size() * params.nTasks; long avgBase = avg(baseSum, n); long varBase = sd(baseSumSq, avgBase, n); long avgWait = avg(waitSum, n); long varWait = sd(waitSumSq, avgWait, n); long avgPlan = avg(planSum, n); long varPlan = sd(planSumSq, avgPlan, n); long avgPWindow = avg(pWindowSum, n); long varPWindow = sd(pWindowSumSq, avgPWindow, n); long avgProlongT = avg(prolongTSum, n); long varProlongT = sd(prolongTSumSq, avgProlongT, n); long avgProlongR = avg(prolongRSum, n); long varProlongR = sd(prolongRSumSq, avgProlongR, n); // avgBase;varBase;avgWait;varWait;avgPlan;varPlan;avgPWindow;varPWindow;avgProlongT;varProlongT;avgProlongR;varProlongR;makespan printSummary(params.summaryPrefix, Status.SUCCESS, avgBase,varBase, avgWait,varWait, avgPlan,varPlan, avgPWindow,varPWindow, avgProlongT,varProlongT, avgProlongR,varProlongR, CommonTime.currentTimeMs() - initalizedAtMs); } private static boolean allDone(List<Agent> agents) { for (final Agent agent : agents) { if (!agent.hasCompletedAllTasks()) return false; } return true; } private static void initAgentVisualization(final List<Agent> agents, int timeStep) { // trajectories VisManager.registerLayer( KeyToggleLayer.create("t", true, FastTrajectoriesLayer.create(new TrajectoriesProvider() { @Override public Trajectory[] getTrajectories() { Trajectory[] trajsArr = new Trajectory[agents.size()]; for (int i = 0; i < trajsArr.length; i++) { trajsArr[i] = agents.get(i).getCurrentTrajectory(); } return trajsArr; } },new ColorProvider() { @Override public Color getColor(int i) { return AgentColors.getColorForAgent(i); } }, 3, timeStep))); // positions VisManager.registerLayer( KeyToggleLayer.create("b", true, LabeledCircleLayer.create(new LabeledCircleLayer.LabeledCircleProvider<tt.euclid2i.Point>() { @Override public Collection<LabeledCircleLayer.LabeledCircle<tt.euclid2i.Point>> getLabeledCircles() { LinkedList<LabeledCircleLayer.LabeledCircle<tt.euclid2i.Point>> list = new LinkedList<LabeledCircleLayer.LabeledCircle<tt.euclid2i.Point>>(); for (int i = 0; i < agents.size(); i++) { Point pos = agents.get(i).getCurrentPos(); list.add(new LabeledCircleLayer.LabeledCircle<tt.euclid2i.Point>(pos, agents.get(i).getAgentBodyRadius(), "" + i , AgentColors.getColorForAgent(i), AgentColors.getColorForAgent(i), Color.WHITE)); } return list; } }, new tt.euclid2i.vis.ProjectionTo2d()))); // tasks VisManager.registerLayer(LabeledCircleLayer.create(new LabeledCircleLayer.LabeledCircleProvider<tt.euclid2i.Point>() { @Override public Collection<LabeledCircleLayer.LabeledCircle<tt.euclid2i.Point>> getLabeledCircles() { LinkedList<LabeledCircleLayer.LabeledCircle<tt.euclid2i.Point>> list = new LinkedList<LabeledCircleLayer.LabeledCircle<tt.euclid2i.Point>>(); for (Map.Entry<String, Point> entry : CurrentTasks.getTasks().entrySet()) { list.add(new LabeledCircleLayer.LabeledCircle<tt.euclid2i.Point>(entry.getValue(), 27, "\n"+entry.getKey() , Color.GREEN)); } return list; } }, new tt.euclid2i.vis.ProjectionTo2d())); } enum Status {SUCCESS, FAIL, TIMEOUT} private static void printSummary(String prefix, Status status, long avgBase, long varBase, long avgWait, long varWait, long avgPlan, long varPlan, long avgPWindow, long varPWindow, long avgProlongT, long varProlongT, long avgProlongR, long varProlongR, long makespan ) { System.out.println(prefix + status.toString() + ";" + avgBase + ";" + varBase + ";" + avgWait + ";" + varWait + ";" + avgPlan + ";" + varPlan + ";" + avgPWindow + ";" + varPWindow + ";" + avgProlongT + ";" + varProlongT + ";" + avgProlongR + ";" + varProlongR + ";" + makespan ); System.exit(0); } static long avg(long sum, long n) { return sum / n; } static long sd(long sumSq, long mean, long n) { double var = (sumSq/n) - (mean*mean); return (long) Math.round(Math.sqrt(var)); } }
15,017
33.763889
214
java
cobra-icaps2015-icaps2015/src/main/java/cz/agents/map4rt/agent/BestResponse.java
cobra-icaps2015-icaps2015/src/main/java/cz/agents/map4rt/agent/BestResponse.java
package cz.agents.map4rt.agent; import java.awt.Color; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedList; import java.util.List; import org.apache.log4j.Logger; import org.jgrapht.DirectedGraph; import org.jgrapht.Graph; import org.jgrapht.GraphPath; import org.jgrapht.alg.AStarShortestPathSimple; import org.jgrapht.graph.GraphPathImpl; import org.jgrapht.util.HeuristicToGoal; import org.jgrapht.util.Goal; import org.omg.PortableInterceptor.LOCATION_FORWARD; import tt.euclid2i.EvaluatedTrajectory; import tt.euclid2i.Line; import tt.euclid2i.Point; import tt.euclid2i.Region; import tt.euclid2i.Trajectory; import tt.euclid2i.discretization.ObstacleWrapper; import tt.euclid2i.trajectory.DelayedStartTrajectory; import tt.euclid2i.trajectory.LineSegmentsConstantSpeedTrajectory; import tt.euclid2i.trajectory.StraightSegmentTrajectory; import tt.euclid2i.vis.RegionsLayer; import tt.euclidtime3i.discretization.ConstantSpeedTimeExtension; import tt.euclidtime3i.discretization.ControlEffortWrapper; import tt.euclidtime3i.discretization.FreeOnTargetWaitExtension; import tt.euclidtime3i.discretization.Straight; import tt.euclidtime3i.region.MovingCircle; import tt.euclidtime3i.vis.TimeParameterProjectionTo2d; import tt.vis.GraphLayer; import tt.vis.TimeParameterHolder; import cz.agents.alite.vis.VisManager; import cz.agents.alite.vis.layer.VisLayer; public class BestResponse { private final static Logger LOGGER = Logger.getLogger(BestResponse.class); private static final boolean DEBUG_VIS = false; public static EvaluatedTrajectory computeBestResponse( final Point start, final int minTime, final int depTime, final Point goal, final float maxSpeed, final DirectedGraph<tt.euclid2i.Point, tt.euclid2i.Line> spatialGraph, final HeuristicToGoal<tt.euclidtime3i.Point> heuristic, final Collection<tt.euclidtime3i.Region> dynamicObstacles, final int maxTime, final int timeStep, final int runtimeLimitMs) { VisLayer graphLayer;VisLayer sobstLayer;VisLayer dobstLayer; if (DEBUG_VIS) { // --- debug visio --- begin //visualize the graph graphLayer = GraphLayer.create( new GraphLayer.GraphProvider<tt.euclid2i.Point, tt.euclid2i.Line>() { @Override public Graph<tt.euclid2i.Point, tt.euclid2i.Line> getGraph() { return ((ObstacleWrapper<Point, Line>) spatialGraph).generateFullGraph(start); } }, new tt.euclid2i.vis.ProjectionTo2d(), Color.BLUE, Color.BLUE, 1, 4); dobstLayer = tt.euclidtime3i.vis.RegionsLayer.create(new tt.euclidtime3i.vis.RegionsLayer.RegionsProvider() { @Override public Collection<tt.euclidtime3i.Region> getRegions() { return dynamicObstacles; } }, new TimeParameterProjectionTo2d(TimeParameterHolder.time), Color.BLACK, null); VisManager.registerLayer(graphLayer); VisManager.registerLayer(sobstLayer); VisManager.registerLayer(dobstLayer); // --- debug visio --- end } // time-extension DirectedGraph<tt.euclidtime3i.Point, Straight> motions = createMotions(spatialGraph, goal, maxSpeed, dynamicObstacles, maxTime, timeStep); Goal<tt.euclidtime3i.Point> goalCond = new Goal<tt.euclidtime3i.Point>() { @Override public boolean isGoal(tt.euclidtime3i.Point current) { return current.getPosition().equals(goal) && current.getTime() > (maxTime - timeStep - 1); // last space-time node might not be placed at MAX_TIME } }; AStarShortestPathSimple<tt.euclidtime3i.Point, Straight> astar = new AStarShortestPathSimple<>(motions, heuristic, new tt.euclidtime3i.Point(start, depTime), goalCond); long startedAt = System.currentTimeMillis(); GraphPath<tt.euclidtime3i.Point, Straight> path = astar.findPathRuntimeLimit(Integer.MAX_VALUE, runtimeLimitMs); long runtime = System.currentTimeMillis()-startedAt; LOGGER.debug("Planning finshed in " + runtime + "ms; " + astar.getIterationCount() + " iterations; " + (int) (astar.getIterationCount() / (runtime / 1000.0)) + " it/sec " + " path-length:" + ((path != null) ? path.getEdgeList().size() : "NONE")); if (path != null) { if (DEBUG_VIS) { VisManager.unregisterLayer(graphLayer); VisManager.unregisterLayer(sobstLayer); VisManager.unregisterLayer(dobstLayer); } // add initial 'wait at start' segments List<Straight> edgeList = new ArrayList<Straight>(); assert (depTime-minTime) % timeStep == 0 : depTime + " - " + minTime + " is not divisible by " + timeStep; for (int t=minTime; t < depTime; t += timeStep) { edgeList.add(new Straight(new tt.euclidtime3i.Point(start, t), new tt.euclidtime3i.Point(start, t+timeStep))); } assert edgeList.isEmpty() || edgeList.get(edgeList.size()-1).getEnd().getTime() == depTime; edgeList.addAll(path.getEdgeList()); GraphPathImpl<tt.euclidtime3i.Point, Straight> path2 = new GraphPathImpl<tt.euclidtime3i.Point, Straight>(path.getGraph(), path.getStartVertex(), path.getEndVertex(), edgeList, path.getWeight()); // this should be constant step return new StraightSegmentTrajectory(path2, maxTime-minTime); } else { return null; } } public static EvaluatedTrajectory computeBestResponseByDelayMethod( final tt.euclidtime3i.Point start, final Point goal, final float maxSpeed, final DirectedGraph<tt.euclid2i.Point, tt.euclid2i.Line> spatialGraph, final HeuristicToGoal<tt.euclid2i.Point> heuristic, final Collection<tt.euclidtime3i.Region> dynamicObstacles, final int maxTime, final int timeStep, final int runtimeLimitMs) { long startedAt = System.currentTimeMillis(); EvaluatedTrajectory path = computeShortestPath(start.getPosition(), start.getTime(), goal, maxSpeed, maxTime, spatialGraph, heuristic); int delay = 0; while (true) { DelayedStartTrajectory delayedTraj = new DelayedStartTrajectory(path, delay); if (collisionFree(delayedTraj, dynamicObstacles, 200)) { return delayedTraj; } if (System.currentTimeMillis() > startedAt + runtimeLimitMs) { return null; } delay += timeStep; } } public static boolean collisionFree(Trajectory traj, Collection<tt.euclidtime3i.Region> dynamicObstacles, int samplingInterval) { for (int t=traj.getMinTime(); t<traj.getMaxTime(); t += samplingInterval) { tt.euclidtime3i.Point pos = new tt.euclidtime3i.Point(traj.get(t), t); for (tt.euclidtime3i.Region dobst : dynamicObstacles) { if (dobst.isInside(pos)) { return false; } } } return true; } public static EvaluatedTrajectory computeShortestPath( final Point start, final int departureTime, final Point goal, final float maxSpeed, final int maxTime, final DirectedGraph<tt.euclid2i.Point, tt.euclid2i.Line> spatialGraph, HeuristicToGoal<Point> heuristic) { GraphPath<Point, Line> path = AStarShortestPathSimple.findPathBetween(spatialGraph, heuristic, start, goal); return new LineSegmentsConstantSpeedTrajectory<Point, Line>(departureTime, path, maxSpeed, maxTime-departureTime); } public static DirectedGraph<tt.euclidtime3i.Point,Straight> createMotions(DirectedGraph<Point, Line> spatialGraph, Point goal, float maxSpeed, Collection<? extends tt.euclidtime3i.Region> dynamicObstacles, int maxTime, int timeStep) { DirectedGraph<tt.euclidtime3i.Point, Straight> motions = new ConstantSpeedTimeExtension(spatialGraph, maxTime, new float[] {maxSpeed}, dynamicObstacles, timeStep, timeStep); motions = new FreeOnTargetWaitExtension(motions, goal); motions = new ControlEffortWrapper(motions, 0.01); return motions; } public static double minDistance(Trajectory traj, Collection<tt.euclidtime3i.Region> dObsts, int timeStep) { double minDist = Double.MAX_VALUE; for (int t = traj.getMinTime(); t <= traj.getMaxTime(); t += timeStep ) { Point trajPos = traj.get(t); for (tt.euclidtime3i.Region dobst : dObsts) { assert dobst instanceof MovingCircle; Point otherPos = ((MovingCircle) dobst).getTrajectory().get(t); double dist = trajPos.distance(otherPos); if (dist < minDist) { minDist = dist; } } } return minDist; } }
8,582
38.736111
235
java
cobra-icaps2015-icaps2015/src/main/java/cz/agents/map4rt/agent/Agent.java
cobra-icaps2015-icaps2015/src/main/java/cz/agents/map4rt/agent/Agent.java
package cz.agents.map4rt.agent; import java.util.Collection; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Random; import org.apache.log4j.Logger; import org.jgrapht.DirectedGraph; import org.jgrapht.GraphPath; import org.jgrapht.alg.AStarShortestPathSimple; import org.jgrapht.util.HeuristicToGoal; import tt.euclid2i.EvaluatedTrajectory; import tt.euclid2i.Line; import tt.euclid2i.Point; import tt.euclid2i.Region; import tt.euclid2i.discretization.AdditionalPointsExtension; import tt.euclid2i.probleminstance.Environment; import cz.agents.alite.communication.Communicator; import cz.agents.alite.communication.InboxBasedCommunicator; import cz.agents.alite.communication.Message; import cz.agents.alite.communication.MessageHandler; import cz.agents.alite.communication.content.Content; import cz.agents.map4rt.CommonTime; public abstract class Agent { static final Logger LOGGER = Logger.getLogger(Agent.class); String name; Point start; int nTasks; Environment environment; int agentBodyRadius; Communicator communicator; List<String> agents; float maxSpeed; Collection<Region> inflatedObstacles; DirectedGraph<Point, Line> planningGraph; Point currentTask = null; Random random; long lastTaskIssuedAt; long lastTaskReachedAtMs; long issueFirstTaskAt = 0; protected long currentTaskBaseDuration; public long baseSum; public long baseSumSq; public long waitSum; public long waitSumSq; public long planSum; public long planSumSq; public long pWindowSum; public long pWindowSumSq; public long prolongTSum; public long prolongTSumSq; public long prolongRSum; public long prolongRSumSq; private double maxEdgeLength; public Agent(String name, Point start, int nTasks, Environment environment, DirectedGraph<Point, Line> planningGraph, int agentBodyRadius, float maxSpeed, Random random) { super(); this.name = name; this.start = start; this.nTasks = nTasks; this.random = random; this.environment = environment; this.agentBodyRadius = agentBodyRadius; this.inflatedObstacles = tt.euclid2i.util.Util.inflateRegions(environment.getObstacles(), agentBodyRadius); this.inflatedObstacles.addAll(tt.euclid2i.util.Util.inflateRegions(Collections.singleton(environment.getBoundary()), agentBodyRadius)); this.maxSpeed = maxSpeed; this.planningGraph = planningGraph; maxEdgeLength = 0; for (Line edge : getPlanningGraph().edgeSet()) { if (edge.getDistance() > maxEdgeLength) { maxEdgeLength = edge.getDistance(); } } assert CurrentTasks.tryToRegisterTask(name, start); } public synchronized Point getStart() { return start; } public String getName() { return name; } public int getAgentBodyRadius() { return agentBodyRadius; } public abstract EvaluatedTrajectory getCurrentTrajectory(); public tt.euclidtime3i.Region getOccupiedRegion() { if (getCurrentTrajectory() != null) { return new tt.euclidtime3i.region.MovingCircle(getCurrentTrajectory(), agentBodyRadius); } else { return null; } } public void setCommunicator(Communicator communicator, List<String> agents) { this.communicator = communicator; this.agents = agents; this.communicator.addMessageHandler(new MessageHandler() { @Override public void notify(Message message) { Agent.this.notify(message); } }); } protected Communicator getCommunicator() { return communicator; } public abstract void start(); // messaging protected void broadcast(Content content) { Message msg = getCommunicator().createMessage(content); LinkedList<String> receivers = new LinkedList<String>(agents); receivers.remove(getName()); msg.addReceivers(receivers); getCommunicator().sendMessage(msg); } protected void send(String receiver, Content content) { Message msg = getCommunicator().createMessage(content); LinkedList<String> receivers = new LinkedList<String>(); receivers.add(receiver); msg.addReceivers(receivers); getCommunicator().sendMessage(msg); } protected void notify(Message message) { //LOGGER.trace(getName() + " >>> received message " + message.getContent()); } public void tick(int timeMs) { //LOGGER.info(getName() + " Tick @ " + time/1000.0 + "s"); if (currentTask == null && CommonTime.currentTimeMs() > issueFirstTaskAt && nTasks > 0) { lastTaskIssuedAt = CommonTime.currentTimeMs(); synchronized (Agent.class) { long waitDuration = CommonTime.currentTimeMs() - lastTaskIssuedAt; waitSum += waitDuration; waitSumSq += waitDuration * waitDuration; currentTask = CurrentTasks.assignRandomDestination(getName(), random); currentTaskBaseDuration = getTaskDuration(getCurrentPos(), currentTask); baseSum += currentTaskBaseDuration; baseSumSq += currentTaskBaseDuration * currentTaskBaseDuration; LOGGER.info(getName() + " Carrying out new task " + currentTask + ", baseline duration is " + currentTaskBaseDuration + ". There is " + nTasks + " tasks in the stack to be carried out."); handleNewTask(currentTask); nTasks--; } } if (currentTask != null && currentTaskDestinationReached()) { if (nTasks == 0) { LOGGER.info(getName() + " finished all tasks"); lastTaskReachedAtMs = CommonTime.currentTimeMs(); } currentTask = null; } } protected abstract boolean currentTaskDestinationReached(); /** * @return true if the task has been handled, false if the task could not been handled at this point */ protected abstract void handleNewTask(Point task); public String getStatus() { return getName(); } public DirectedGraph<Point, Line> getPlanningGraph() { return planningGraph; } public abstract Point getCurrentPos(); public boolean hasCompletedAllTasks() { return currentTask==null && nTasks == 0; } public int getMessageSentCounter() { return ((InboxBasedCommunicator) communicator).getMessagesSent(); } public int getInboxSize() { return ((InboxBasedCommunicator) communicator).getInboxSize(); } public long getLastTaskReachedTime() { return lastTaskReachedAtMs; } public void setIssueFirstTaskAt(long issueFirstTaskAt) { this.issueFirstTaskAt = issueFirstTaskAt; } protected long getTaskDuration(final Point startPoint, final Point goal) { HeuristicToGoal<Point> heuristic = new HeuristicToGoal<Point>() { @Override public double getCostToGoalEstimate(Point current) { return current.distance(goal); } }; AdditionalPointsExtension graph = new AdditionalPointsExtension(getPlanningGraph(), Collections.singleton(startPoint), (int) Math.ceil(maxEdgeLength)); GraphPath<Point, Line> path = AStarShortestPathSimple.findPathBetween(graph, heuristic, startPoint, goal); return (long) (path.getWeight()/maxSpeed); } }
7,428
29.322449
194
java
cobra-icaps2015-icaps2015/src/main/java/cz/agents/map4rt/agent/PositionBlackboard.java
cobra-icaps2015-icaps2015/src/main/java/cz/agents/map4rt/agent/PositionBlackboard.java
package cz.agents.map4rt.agent; import java.util.HashMap; import java.util.Map; import tt.euclid2d.Point; import tt.euclid2d.Vector; public class PositionBlackboard { public static class Record { public Record(int agentId, Point position, Vector velocity, double radius) { this.agentId = agentId; this.position = position; this.velocity = velocity; this.radius = radius; } final int agentId; final Point position; final Vector velocity; final double radius; } static Map<String, Record> records = new HashMap<>(); public static synchronized void recordNewPosition(String name, int agentId, Point position, Vector velocity, double radius) { records.put(name, new Record(agentId, position, velocity, radius)); } public static synchronized Map<String, Record> getRecords() { return new HashMap<String, Record>(records); } }
874
24.735294
127
java
cobra-icaps2015-icaps2015/src/main/java/cz/agents/map4rt/agent/ORCAAgent.java
cobra-icaps2015-icaps2015/src/main/java/cz/agents/map4rt/agent/ORCAAgent.java
package cz.agents.map4rt.agent; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Random; import org.apache.log4j.Logger; import org.jgrapht.DirectedGraph; import rvolib.KdTree; import rvolib.RVOAgent; import rvolib.RVOObstacle; import rvolib.RVOUtil; import rvolib.Vector2; import tt.euclid2d.Vector; import tt.euclid2i.EvaluatedTrajectory; import tt.euclid2i.Line; import tt.euclid2i.Point; import tt.euclid2i.Region; import tt.euclid2i.probleminstance.Environment; import tt.euclid2i.region.Polygon; import tt.euclid2i.trajectory.TimePointArrayTrajectory; import tt.euclid2i.util.Util; import tt.jointeuclid2ni.probleminstance.RelocationTask; import util.DesiredControl; import util.GraphBasedOptimalPolicyController; import cz.agents.alite.communication.Message; import cz.agents.map4rt.CommonTime; import cz.agents.map4rt.agent.PositionBlackboard.Record; import cz.agents.map4rt.msg.InformNewPosition; public class ORCAAgent extends Agent { static final Logger LOGGER = Logger.getLogger(ORCAAgent.class); private static final int MAX_NEIGHBORS = 50; private static final float NEIGHBOR_DIST = 500; private static final float TIME_HORIZON_AGENT = 5000; private static final float TIME_HORIZON_OBSTACLE = 1000; private static final double NEAR_GOAL_EPS = 0.0f; private RVOAgent rvoAgent; private HashMap<String, RVOAgent> neighbors; private KdTree kdTree; private ArrayList<RVOObstacle> obstacles; float maxSpeed; DesiredControl desiredControl; private static final long UNKNOWN = -1; private static final double GOAL_REACHED_TOLERANCE = 3; private long lastTickTime = UNKNOWN; private boolean showVis; private Collection<Region> ttObstaclesLessInflated; private double DesiredControlNodeSearchRadius; private Point currentGoal; public ORCAAgent(String name, Point start, int nTasks, Environment environment, DirectedGraph<Point, Line> planningGraph, int agentBodyRadius, float maxSpeed, int maxTime, int timeStep, boolean showVis, Random random) { super(name, start, nTasks, environment, planningGraph, agentBodyRadius, maxSpeed, random); this.showVis = showVis; this.maxSpeed = maxSpeed; rvoAgent = new RVOAgent(); rvoAgent.position_ = new Vector2(start); rvoAgent.velocity_ = new Vector2(0,0); rvoAgent.maxNeighbors_ = MAX_NEIGHBORS; rvoAgent.maxSpeed_ = maxSpeed; rvoAgent.neighborDist_ = NEIGHBOR_DIST; rvoAgent.radius_ = (float) Math.ceil(agentBodyRadius + 1); rvoAgent.timeHorizon_ = TIME_HORIZON_AGENT; rvoAgent.timeHorizonObst_ = TIME_HORIZON_OBSTACLE; rvoAgent.clearTrajectory(); rvoAgent.id_ = Integer.parseInt(name.substring(1)); rvoAgent.showVis = showVis; if (showVis) { rvoAgent.initVisualization(); } LinkedList<tt.euclid2i.Region> ttObstacles = new LinkedList<tt.euclid2i.Region>(); ttObstacles.add(environment.getBoundary()); ttObstacles.addAll(environment.getObstacles()); this.ttObstaclesLessInflated = Util.inflateRegions(ttObstacles, agentBodyRadius-1); DesiredControlNodeSearchRadius = longestEdgeLength(planningGraph)+1; // Used to be: ((float) Math.ceil(agentBodyRadius * RADIUS_GRACE_MULTIPLIER) * 3) + 1; // approx. sqrt(2) * 2 * radius desiredControl = new DesiredControl() { @Override public Vector getDesiredControl(tt.euclid2d.Point currentPosition) { return new Vector(0,0); } }; currentGoal = start; kdTree = new KdTree(); // Add obstacles obstacles = new ArrayList<RVOObstacle>(); for (tt.euclid2i.Region region : ttObstacles) { if (!(region instanceof Polygon)) { throw new RuntimeException("Only polygons are supported"); } ArrayList<Vector2> obstacle = RVOUtil.regionToVectorList((Polygon) region); RVOUtil.addObstacle(obstacle, obstacles); } kdTree.buildObstacleTree(obstacles.toArray(new RVOObstacle[0]), this.obstacles); neighbors = new HashMap<String, RVOAgent>(); neighbors.put(getName(), rvoAgent); } private double longestEdgeLength(DirectedGraph<Point, Line> planningGraph) { double longestEdgeLength = 0; for (Line edge : planningGraph.edgeSet()) { if (longestEdgeLength < edge.getDistance()) { longestEdgeLength = edge.getDistance(); } } return longestEdgeLength; } public EvaluatedTrajectory getEvaluatedTrajectory(Point goal) { ArrayList<tt.euclidtime3i.Point> rvoTraj = new ArrayList<tt.euclidtime3i.Point>(rvoAgent.timePointTrajectory); tt.euclidtime3i.Point[] timePointArray = new tt.euclidtime3i.Point[rvoTraj.size()]; for (int i=0; i<rvoTraj.size(); i++) { timePointArray[i] = new tt.euclidtime3i.Point( rvoTraj.get(i).getPosition(), rvoTraj.get(i).getTime()); } double cost = RVOAgent.evaluateCost(timePointArray, goal); TimePointArrayTrajectory traj = new TimePointArrayTrajectory(timePointArray, cost); return traj; } @Override public void start() { } @Override public void tick(int time) { if (currentTask != null && currentTaskDestinationReached()) { long prolongT = (CommonTime.currentTimeMs() - lastTaskIssuedAt) - currentTaskBaseDuration; prolongTSum += prolongT; prolongTSumSq += prolongT * prolongT; } super.tick(time); if (showVis) { // try { // Thread.sleep(10); // } catch (InterruptedException e) {} } if (lastTickTime == UNKNOWN) { lastTickTime = time; return; } float timeStep = (float) (time - lastTickTime); lastTickTime = time; doStep(timeStep); } private void doStep(float timeStep) { LOGGER.trace(getName() + " -- doStep"); updateNeighborsFromBlackboard(); setPreferredVelocity(timeStep); RVOAgent[] rvoAgents = neighbors.values().toArray(new RVOAgent[neighbors.values().size()]); kdTree.clearAgents(); kdTree.buildAgentTree(rvoAgents); rvoAgent.computeNeighbors(kdTree); Vector2 newVelocity = rvoAgent.computeNewVelocity(timeStep); rvoAgent.update(timeStep, newVelocity); PositionBlackboard.recordNewPosition(getName(), rvoAgent.id_, rvoAgent.position_.toPoint2d(), rvoAgent.velocity_.toVector2d(), rvoAgent.radius_); } private void setPreferredVelocity(float timeStep) { Vector2 currentPosition = rvoAgent.position_; double distanceToGoal = currentPosition.toPoint2i().distance(getCurrentGoal()); //if (currentPosition.toPoint2i().distance(getCurrentGoal()) < NEAR_GOAL_EPS) { //rvoAgent.setPrefVelocity(new Vector2(0, 0)); //} else { Vector desiredVelocity = desiredControl.getDesiredControl(rvoAgent.position_.toPoint2d()); assert !Double.isNaN(desiredVelocity.x) && !Double.isNaN(desiredVelocity.y); double desiredSpeed = desiredVelocity.length(); Vector desiredDir = new Vector(desiredVelocity); if (desiredDir.length() != 0) { desiredDir.normalize(); } // Adjust if the agent is near the goal if (distanceToGoal <= timeStep * desiredSpeed) { // goal will be reached in the next time step double speed = distanceToGoal / timeStep; desiredVelocity = desiredDir; desiredVelocity.scale(speed); } rvoAgent.setPrefVelocity(new Vector2(desiredVelocity)); //} } protected void updateNeighborsFromBlackboard() { for (Map.Entry<String, Record> entry : PositionBlackboard.getRecords().entrySet()) { if (!entry.getKey().equals(getName())) { RVOAgent neighborRVOAgent = new RVOAgent(); neighborRVOAgent.id_ = entry.getValue().agentId; neighborRVOAgent.position_ = new Vector2(entry.getValue().position); neighborRVOAgent.velocity_ = new Vector2(entry.getValue().velocity); neighborRVOAgent.radius_ = (float) entry.getValue().radius; neighbors.put(entry.getKey(), neighborRVOAgent); } } } public Point getCurrentGoal() { return currentGoal; } public Point getCurrentPos() { return rvoAgent.position_.toPoint2i(); } public Vector getCurrentVelocity() { return rvoAgent.velocity_.toVector2d(); } @Override protected void handleNewTask(Point task) { desiredControl = new GraphBasedOptimalPolicyController(planningGraph, task, ttObstaclesLessInflated, maxSpeed, DesiredControlNodeSearchRadius, showVis); currentGoal = task; } @Override public EvaluatedTrajectory getCurrentTrajectory() { return null; } @Override protected boolean currentTaskDestinationReached() { return currentTask.distance(getCurrentPos()) < GOAL_REACHED_TOLERANCE; } }
8,899
30.338028
223
java
cobra-icaps2015-icaps2015/src/main/java/cz/agents/map4rt/agent/COBRAAgent.java
cobra-icaps2015-icaps2015/src/main/java/cz/agents/map4rt/agent/COBRAAgent.java
package cz.agents.map4rt.agent; import java.util.LinkedList; import java.util.Random; import org.jgrapht.DirectedGraph; import org.jgrapht.util.HeuristicToGoal; import org.jgrapht.util.heuristics.PerfectHeuristic; import tt.euclid2i.EvaluatedTrajectory; import tt.euclid2i.Line; import tt.euclid2i.Point; import tt.euclid2i.probleminstance.Environment; import tt.euclidtime3i.Region; import tt.euclidtime3i.region.MovingCircle; import cz.agents.map4rt.CommonTime; public class COBRAAgent extends PlanningAgent { private int samplingInterval; public COBRAAgent(String name, Point start, int nTasks, Environment env, DirectedGraph<Point, Line> planningGraph, int agentBodyRadius, final float maxSpeed, int maxTime, int timeStep, Random random) { super(name, start, nTasks, env, planningGraph, agentBodyRadius, maxSpeed, maxTime, timeStep, random); assert timeStep % 2 == 0; samplingInterval = timeStep/2; final HeuristicToGoal<tt.euclid2i.Point> spatialHeuristic = new PerfectHeuristic<tt.euclid2i.Point, Line>(planningGraph, start); final HeuristicToGoal<tt.euclidtime3i.Point> spaceTimeHeuristic = new HeuristicToGoal<tt.euclidtime3i.Point>() { @Override public double getCostToGoalEstimate(tt.euclidtime3i.Point current) { return spatialHeuristic.getCostToGoalEstimate(current.getPosition()) / (double) maxSpeed; } }; EvaluatedTrajectory traj = BestResponse.computeBestResponse(start, 0, 0, start, maxSpeed, getPlanningGraph(), spaceTimeHeuristic, new LinkedList<Region>(), maxTime, timeStep, T_PLANNING); int samplingInterval = timeStep/2; Token.register(getName(), new MovingCircle(traj, agentBodyRadius, samplingInterval)); currentTrajectory = traj; } @Override protected void handleNewTask(Point task) { long planningStartedAt = CommonTime.currentTimeMs(); // nearest timestep in past int minTime = ((int) Math.floor( (double) CommonTime.currentTimeMs() / (double) timeStep) ) * timeStep; // start at a multiple of timestep int depTime = ((int) Math.ceil( (double) (CommonTime.currentTimeMs() + T_PLANNING) / (double) timeStep) ) * timeStep; EvaluatedTrajectory traj = getBestResponseTrajectory( getCurrentPos(), minTime, depTime, task, Token.getReservedRegions(getName()), maxTime); Token.register(getName(), new MovingCircle(traj, agentBodyRadius, samplingInterval)); currentTrajectory = traj; lastTaskTravelStartedAt = depTime; currentTaskTouchedGoal = false; long planningDuration = (CommonTime.currentTimeMs() - planningStartedAt); planSum += planningDuration; planSumSq += planningDuration * planningDuration; long pWindowDuration = depTime - planningStartedAt; pWindowSum += pWindowDuration; pWindowSumSq += pWindowDuration * pWindowDuration; } @Override public void start() {} }
2,826
34.78481
130
java
cobra-icaps2015-icaps2015/src/main/java/cz/agents/map4rt/agent/CurrentTasks.java
cobra-icaps2015-icaps2015/src/main/java/cz/agents/map4rt/agent/CurrentTasks.java
package cz.agents.map4rt.agent; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Random; import tt.euclid2i.Point; import tt.jointeuclid2ni.probleminstance.RelocationTask; public class CurrentTasks { public static List<Point> docks = null; static Map<String, Point> tasks = new HashMap<String, Point>(); synchronized public static boolean tryToRegisterTask(String name, Point dest) { HashMap<String, Point> tasksWithoutAgent = new HashMap<String, Point>(tasks); tasksWithoutAgent.remove(name); boolean free = !tasksWithoutAgent.values().contains(dest); if (free) { tasks.put(name, dest); return true; } else { return false; } } synchronized public static Map<String, Point> getTasks() { return new HashMap<String, Point>(tasks); } synchronized public static Point assignRandomDestination(String name, Random rnd) { List<Point> unassignedDestinations = new LinkedList<Point>(docks); unassignedDestinations.removeAll(tasks.values()); Point[] dests = unassignedDestinations.toArray(new Point[0]); Point destination = dests[rnd.nextInt(dests.length)]; tasks.put(name, destination); return destination; } }
1,229
26.954545
84
java
cobra-icaps2015-icaps2015/src/main/java/cz/agents/map4rt/agent/Token.java
cobra-icaps2015-icaps2015/src/main/java/cz/agents/map4rt/agent/Token.java
package cz.agents.map4rt.agent; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import tt.euclidtime3i.Region; import tt.euclidtime3i.region.MovingCircle; public class Token { static boolean locked; static Map<String, Region> regions = new HashMap<String, Region>(); static List<Region> getReservedRegions(String askingAgent) { List<Region> reservedRegions = new LinkedList<Region>(); for (String agentName : regions.keySet()) { if (!agentName.equals(askingAgent)) reservedRegions.add(regions.get(agentName)); } return reservedRegions; } public static void register(String name, MovingCircle movingCircle) { regions.put(name, movingCircle); } synchronized static boolean tryLock() { if (!locked) { locked = true; return true; } else { return false; } } synchronized static void unlock() { locked = false; } }
921
20.44186
70
java
cobra-icaps2015-icaps2015/src/main/java/cz/agents/map4rt/agent/PlanningAgent.java
cobra-icaps2015-icaps2015/src/main/java/cz/agents/map4rt/agent/PlanningAgent.java
package cz.agents.map4rt.agent; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.Random; import org.apache.log4j.Logger; import org.jgrapht.DirectedGraph; import org.jgrapht.util.HeuristicToGoal; import org.jgrapht.util.heuristics.PerfectHeuristic; import cz.agents.map4rt.CommonTime; import tt.euclid2i.EvaluatedTrajectory; import tt.euclid2i.Line; import tt.euclid2i.Point; import tt.euclid2i.SegmentedTrajectory; import tt.euclid2i.probleminstance.Environment; import tt.euclid2i.region.Circle; import tt.euclid2i.trajectory.BasicSegmentedTrajectory; import tt.euclidtime3i.Region; import tt.euclidtime3i.ShortestPathHeuristic; import tt.euclidtime3i.discretization.Straight; import tt.euclidtime3i.region.MovingCircle; import tt.euclidtime3i.region.MovingCircleMinusPoint; import tt.jointeuclid2ni.probleminstance.RelocationTask; /** * An agent that resolves conflict by finding new conflict-free plans. */ public abstract class PlanningAgent extends Agent { final int T_PLANNING = 3000; Logger LOGGER = Logger.getLogger(PlanningAgent.class); EvaluatedTrajectory trajectory; protected final int timeStep; protected final int maxTime; protected EvaluatedTrajectory currentTrajectory; protected int goalReachedTime; protected Point currentPos; long lastTaskTravelStartedAt; protected boolean currentTaskTouchedGoal; public PlanningAgent(String name, Point start, int nTasks, Environment environment, DirectedGraph<Point, Line> planningGraph, int agentBodyRadius, float maxSpeed, int maxTime, int timeStep, Random random) { super(name, start, nTasks, environment, planningGraph, agentBodyRadius, maxSpeed, random); this.maxTime = maxTime; this.timeStep = timeStep; this.currentPos = start; } protected EvaluatedTrajectory getBestResponseTrajectory( Point start, int minTime, int depTime, Point goal, Collection<Region> dynamicObst, int maxTime) { LOGGER.debug(getName() + " started planning " + start + "@" + minTime + "/" + depTime + " -> " + goal + " maxtime=" + maxTime); long startedAt = System.currentTimeMillis(); EvaluatedTrajectory traj; LinkedList<Region> dObstInflated = inflateDynamicObstacles(dynamicObst, agentBodyRadius); final HeuristicToGoal<tt.euclid2i.Point> spatialHeuristic = new PerfectHeuristic<tt.euclid2i.Point, Line>(planningGraph, goal); final HeuristicToGoal<tt.euclidtime3i.Point> spaceTimeHeuristic = new HeuristicToGoal<tt.euclidtime3i.Point>() { @Override public double getCostToGoalEstimate(tt.euclidtime3i.Point current) { return spatialHeuristic.getCostToGoalEstimate(current.getPosition()) / (double)maxSpeed; } }; traj = BestResponse.computeBestResponse(start, minTime, depTime, goal, maxSpeed, getPlanningGraph(), spaceTimeHeuristic, dObstInflated, maxTime, timeStep, T_PLANNING); if (traj == null) { LOGGER.error(" >>>>>>>>>>>>>>> !!!!! No trajectory found within the runtime limit of " + T_PLANNING + " ms !!!! <<<<<<<<<<<<<<<<<<<<<"); throw new RuntimeException("Failed to find a trajectory"); } goalReachedTime = computeDestinationReachedTime((SegmentedTrajectory) traj, goal); LOGGER.debug(getName() + " finished planning in " + (System.currentTimeMillis() - startedAt) + "ms. Goal will be reached in " + goalReachedTime); return traj; } private int computeDestinationReachedTime(SegmentedTrajectory traj, Point goal) { List<Straight> segments = traj.getSegments(); assert segments.get(segments.size()-1).getEnd().getPosition().equals(goal); int i = segments.size()-1; while (i > 0 && segments.get(i).getStart().getPosition().equals(segments.get(i).getEnd().getPosition())) i--; return segments.get(i).getEnd().getTime(); } protected static LinkedList<tt.euclid2i.Region> inflateStaticObstacles(Collection<tt.euclid2i.Region> sObst, int radius) { // Inflate static obstacles LinkedList<tt.euclid2i.Region> sObstInflated = new LinkedList<tt.euclid2i.Region>(); for (tt.euclid2i.Region region : sObst) { assert region instanceof Circle; Circle circle = (Circle) region; sObstInflated.add(new Circle(circle.getCenter(), circle.getRadius() + radius)); } return sObstInflated; } protected static LinkedList<tt.euclidtime3i.Region> inflateDynamicObstacles(Collection<tt.euclidtime3i.Region> dObst, int radius) { // Inflate static obstacles LinkedList<tt.euclidtime3i.Region> dObstInflated = new LinkedList<tt.euclidtime3i.Region>(); for (tt.euclidtime3i.Region region : dObst) { assert region instanceof MovingCircle; MovingCircle mc = (MovingCircle) region; dObstInflated.add(new MovingCircle(mc.getTrajectory(), mc.getRadius() + radius, mc.getSamplingInterval())); } return dObstInflated; } @Override public EvaluatedTrajectory getCurrentTrajectory() { return currentTrajectory; } @Override public Point getCurrentPos() { if (currentTrajectory != null && currentTrajectory.get(CommonTime.currentTimeMs()) != null) { currentPos = currentTrajectory.get(CommonTime.currentTimeMs()); } return currentPos; } @Override protected boolean currentTaskDestinationReached() { return currentTask != null && CommonTime.currentTimeMs() >= goalReachedTime; } @Override public void tick(int timeMs) { if (currentTask != null && !currentTaskTouchedGoal && getCurrentPos().equals(currentTask)) { // DESTINATION TOUCHED long prolongT = (CommonTime.currentTimeMs() - lastTaskTravelStartedAt) - this.currentTaskBaseDuration; prolongTSum += prolongT; prolongTSumSq += prolongT * prolongT; currentTaskTouchedGoal = true; } if (currentTask != null && currentTaskDestinationReached()) { // DESTINATION REACHED AND THE ROBOT CAN REST long prolongR = (CommonTime.currentTimeMs() - lastTaskTravelStartedAt) - this.currentTaskBaseDuration; prolongRSum += prolongR; prolongRSumSq += prolongR * prolongR; } super.tick(timeMs); } }
5,985
34.211765
147
java
cobra-icaps2015-icaps2015/src/main/java/cz/agents/map4rt/msg/InformNewPosition.java
cobra-icaps2015-icaps2015/src/main/java/cz/agents/map4rt/msg/InformNewPosition.java
package cz.agents.map4rt.msg; import javax.vecmath.Tuple2i; import tt.euclid2d.Point; import tt.euclid2d.Vector; import cz.agents.alite.communication.content.Content; public class InformNewPosition extends Content { final String agentName; final int agentId; final Point position; final Vector velocity; final double radius; public InformNewPosition(String agentName, int agentId, Point position, Vector velocity, double radius) { super(null); this.agentName = agentName; this.agentId = agentId; this.position = position; this.velocity = velocity; this.radius = radius; } @Override public String toString() { return "InformNewPosition [agentName=" + agentName + ", agentId=" + agentId + ", position=" + position + ", velocity=" + velocity + ", radius=" + radius + "]"; } public String getAgentName() { return agentName; } public int getAgentId() { return agentId; } public Point getPosition() { return position; } public Vector getVelocity() { return velocity; } public double getRadius() { return radius; } }
1,082
18.339286
106
java
cobra-icaps2015-icaps2015/src/main/java/cz/agents/map4rt/msg/ValueMsg.java
cobra-icaps2015-icaps2015/src/main/java/cz/agents/map4rt/msg/ValueMsg.java
package cz.agents.map4rt.msg; import tt.euclidtime3i.Region; public class ValueMsg extends InformNewTrajectory { public ValueMsg(String agentName, Region region) { super(agentName, region); } @Override public String toString() { return "Value [agentName=" + agentName + ", region=" + region + "]"; } }
343
19.235294
76
java
cobra-icaps2015-icaps2015/src/main/java/cz/agents/map4rt/msg/InformAgentFinishedRound.java
cobra-icaps2015-icaps2015/src/main/java/cz/agents/map4rt/msg/InformAgentFinishedRound.java
package cz.agents.map4rt.msg; import cz.agents.alite.communication.content.Content; public class InformAgentFinishedRound extends Content { final String agentName; final int round; public InformAgentFinishedRound(String agentName, int round) { super(null); this.agentName = agentName; this.round = round; } public String getAgentName() { return agentName; } public int getRound() { return round; } @Override public String toString() { return "InformAgentFinishedRound [agentName=" + agentName + ", round=" + round + "]"; } }
616
19.566667
72
java
cobra-icaps2015-icaps2015/src/main/java/cz/agents/map4rt/msg/InformNewTrajectory.java
cobra-icaps2015-icaps2015/src/main/java/cz/agents/map4rt/msg/InformNewTrajectory.java
package cz.agents.map4rt.msg; import tt.euclidtime3i.Region; import cz.agents.alite.communication.content.Content; public class InformNewTrajectory extends Content { final String agentName; final tt.euclidtime3i.Region region; final double weight; public InformNewTrajectory(String agentName, Region region) { super(null); this.agentName = agentName; this.region = region; this.weight = Double.POSITIVE_INFINITY; } public InformNewTrajectory(String agentName, Region region, double weight) { super(null); this.agentName = agentName; this.region = region; this.weight = weight; } public String getAgentName() { return agentName; } public tt.euclidtime3i.Region getRegion() { return region; } @Override public String toString() { return "InformNewTrajectory [agentName=" + agentName + ", region=" + region + ", weight=" + weight + "]"; } public double getWeight() { return weight; } }
1,032
23.023256
80
java
cobra-icaps2015-icaps2015/src/main/java/cz/agents/map4rt/msg/InformNewRound.java
cobra-icaps2015-icaps2015/src/main/java/cz/agents/map4rt/msg/InformNewRound.java
package cz.agents.map4rt.msg; import cz.agents.alite.communication.content.Content; public class InformNewRound extends Content { final int roundNo; public InformNewRound(int roundNo) { super(null); this.roundNo = roundNo; } public int getRoundNo() { return roundNo; } @Override public String toString() { return "InformNewRound [roundNo=" + roundNo + "]"; } }
415
17.086957
53
java
cobra-icaps2015-icaps2015/src/main/java/cz/agents/map4rt/msg/InformAgentFailed.java
cobra-icaps2015-icaps2015/src/main/java/cz/agents/map4rt/msg/InformAgentFailed.java
package cz.agents.map4rt.msg; import cz.agents.alite.communication.content.Content; public class InformAgentFailed extends Content { final String agentName; public InformAgentFailed(String agentName) { super(null); this.agentName = agentName; } public String getAgentName() { return agentName; } @Override public String toString() { return "InformAgentFailed [agentName=" + agentName + "]"; } }
449
19.454545
59
java
cobra-icaps2015-icaps2015/src/main/java/cz/agents/map4rt/msg/InformAgentFinished.java
cobra-icaps2015-icaps2015/src/main/java/cz/agents/map4rt/msg/InformAgentFinished.java
package cz.agents.map4rt.msg; import cz.agents.alite.communication.content.Content; public class InformAgentFinished extends Content { final String agentName; public InformAgentFinished(String agentName) { super(null); this.agentName = agentName; } public String getAgentName() { return agentName; } @Override public String toString() { return "InformAgentFinished [agentName=" + agentName + "]"; } }
455
19.727273
61
java
cobra-icaps2015-icaps2015/src/main/java/cz/agents/map4rt/msg/InformSuccessfulConvergence.java
cobra-icaps2015-icaps2015/src/main/java/cz/agents/map4rt/msg/InformSuccessfulConvergence.java
package cz.agents.map4rt.msg; import cz.agents.alite.communication.content.Content; public class InformSuccessfulConvergence extends Content { public InformSuccessfulConvergence() { super(null); } @Override public String toString() { return "InformGloballyConverged []"; } }
291
16.176471
58
java
jkind
jkind-master/jkind-common/src/jkind/SolverOption.java
package jkind; public enum SolverOption { SMTINTERPOL, Z3, YICES, YICES2, CVC4, MATHSAT; @Override public String toString() { return name().toLowerCase(); } }
167
14.272727
47
java
jkind
jkind-master/jkind-common/src/jkind/Assert.java
package jkind; public class Assert { public static void isNotNull(Object o) { if (o == null) { throw new JKindException("Object unexpectedly null"); } } public static void isTrue(boolean b) { if (!b) { throw new JKindException("Assertion failed"); } } public static void isFalse(boolean b) { if (b) { throw new JKindException("Assertion failed"); } } }
383
16.454545
56
java
jkind
jkind-master/jkind-common/src/jkind/JKindException.java
package jkind; /** * An exception generated from JKind or the JKind API */ public class JKindException extends RuntimeException { private static final long serialVersionUID = 1L; public JKindException(String message) { super(message); } public JKindException(String message, Throwable t) { super(message, t); } }
327
18.294118
54
java
jkind
jkind-master/jkind-common/src/jkind/AllIvcsAlgorithm.java
package jkind; public enum AllIvcsAlgorithm { OFFLINE_MIVC_ENUM_ALG, ONLINE_MIVC_ENUM_ALG; @Override public String toString() { return name().toLowerCase(); } }
168
15.9
45
java
jkind
jkind-master/jkind-common/src/jkind/lustre/NamedType.java
package jkind.lustre; import jkind.Assert; import jkind.lustre.visitors.TypeVisitor; public class NamedType extends Type { public final String name; public NamedType(Location location, String name) { super(location); Assert.isNotNull(name); Assert.isFalse(name.equals(BOOL.toString())); Assert.isFalse(name.equals(INT.toString())); Assert.isFalse(name.equals(REAL.toString())); this.name = name; } public NamedType(String name) { this(Location.NULL, name); } /* * Private constructor for built-in types */ private NamedType(String name, @SuppressWarnings("unused") Object unused) { super(Location.NULL); this.name = name; } @Override public String toString() { return name; } public static final NamedType BOOL = new NamedType("bool", null); public static final NamedType INT = new NamedType("int", null); public static final NamedType REAL = new NamedType("real", null); public boolean isBuiltin() { return this == REAL || this == BOOL || this == INT; } public static NamedType get(String name) { switch (name) { case "int": return NamedType.INT; case "real": return NamedType.REAL; case "bool": return NamedType.BOOL; default: return new NamedType(name); } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof NamedType)) { return false; } NamedType other = (NamedType) obj; if (name == null) { if (other.name != null) { return false; } } else if (!name.equals(other.name)) { return false; } return true; } @Override public <T> T accept(TypeVisitor<T> visitor) { return visitor.visit(this); } }
1,880
19.67033
76
java
jkind
jkind-master/jkind-common/src/jkind/lustre/NodeCallExpr.java
package jkind.lustre; import java.util.Arrays; import java.util.List; import jkind.Assert; import jkind.lustre.visitors.ExprVisitor; import jkind.util.Util; public class NodeCallExpr extends Expr { public final String node; public final List<Expr> args; public NodeCallExpr(Location loc, String node, List<Expr> args) { super(loc); Assert.isNotNull(node); this.node = node; this.args = Util.safeList(args); } public NodeCallExpr(String node, List<Expr> args) { this(Location.NULL, node, args); } public NodeCallExpr(String node, Expr... args) { this(Location.NULL, node, Arrays.asList(args)); } @Override public <T> T accept(ExprVisitor<T> visitor) { return visitor.visit(this); } }
715
20.058824
66
java
jkind
jkind-master/jkind-common/src/jkind/lustre/CondactExpr.java
package jkind.lustre; import java.util.Arrays; import java.util.List; import jkind.Assert; import jkind.lustre.visitors.ExprVisitor; import jkind.util.Util; public class CondactExpr extends Expr { public final Expr clock; public final NodeCallExpr call; public final List<Expr> args; public CondactExpr(Location loc, Expr clock, NodeCallExpr call, List<Expr> args) { super(loc); Assert.isNotNull(clock); Assert.isNotNull(call); this.clock = clock; this.call = call; this.args = Util.safeList(args); } public CondactExpr(Expr clock, NodeCallExpr call, List<Expr> args) { this(Location.NULL, clock, call, args); } public CondactExpr(Expr clock, NodeCallExpr call, Expr... args) { this(Location.NULL, clock, call, Arrays.asList(args)); } @Override public <T> T accept(ExprVisitor<T> visitor) { return visitor.visit(this); } }
860
22.27027
83
java
jkind
jkind-master/jkind-common/src/jkind/lustre/ArrayUpdateExpr.java
package jkind.lustre; import jkind.Assert; import jkind.lustre.visitors.ExprVisitor; public class ArrayUpdateExpr extends Expr { public final Expr array; public final Expr index; public final Expr value; public ArrayUpdateExpr(Location location, Expr array, Expr index, Expr value) { super(location); Assert.isNotNull(array); Assert.isNotNull(index); Assert.isNotNull(value); this.array = array; this.index = index; this.value = value; } public ArrayUpdateExpr(Expr array, Expr index, Expr value) { this(Location.NULL, array, index, value); } @Override public <T> T accept(ExprVisitor<T> visitor) { return visitor.visit(this); } }
663
21.896552
80
java
jkind
jkind-master/jkind-common/src/jkind/lustre/ArrayAccessExpr.java
package jkind.lustre; import jkind.Assert; import jkind.lustre.visitors.ExprVisitor; public class ArrayAccessExpr extends Expr { public final Expr array; public final Expr index; public ArrayAccessExpr(Location location, Expr array, Expr index) { super(location); Assert.isNotNull(array); Assert.isNotNull(index); this.array = array; this.index = index; } public ArrayAccessExpr(Expr array, Expr index) { this(Location.NULL, array, index); } public ArrayAccessExpr(Expr array, int index) { this(array, new IntExpr(index)); } @Override public <T> T accept(ExprVisitor<T> visitor) { return visitor.visit(this); } }
645
20.533333
68
java
jkind
jkind-master/jkind-common/src/jkind/lustre/LustreUtil.java
package jkind.lustre; import static jkind.lustre.NamedType.BOOL; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.function.BiFunction; import jkind.lustre.builders.NodeBuilder; public class LustreUtil { /* Binary Expressions */ public static Expr and(Expr left, Expr right) { return new BinaryExpr(left, BinaryOp.AND, right); } public static Expr or(Expr left, Expr right) { return new BinaryExpr(left, BinaryOp.OR, right); } public static Expr implies(Expr left, Expr right) { return new BinaryExpr(left, BinaryOp.IMPLIES, right); } public static Expr xor(Expr left, Expr right) { return new BinaryExpr(left, BinaryOp.XOR, right); } public static Expr arrow(Expr left, Expr right) { return new BinaryExpr(left, BinaryOp.ARROW, right); } public static Expr less(Expr left, Expr right) { return new BinaryExpr(left, BinaryOp.LESS, right); } public static Expr lessEqual(Expr left, Expr right) { return new BinaryExpr(left, BinaryOp.LESSEQUAL, right); } public static Expr greater(Expr left, Expr right) { return new BinaryExpr(left, BinaryOp.GREATER, right); } public static Expr greaterEqual(Expr left, Expr right) { return new BinaryExpr(left, BinaryOp.GREATEREQUAL, right); } public static Expr equal(Expr left, Expr right) { return new BinaryExpr(left, BinaryOp.EQUAL, right); } public static Expr notEqual(Expr left, Expr right) { return new BinaryExpr(left, BinaryOp.NOTEQUAL, right); } public static Expr plus(Expr left, Expr right) { return new BinaryExpr(left, BinaryOp.PLUS, right); } public static Expr minus(Expr left, Expr right) { return new BinaryExpr(left, BinaryOp.MINUS, right); } public static Expr multiply(Expr left, Expr right) { return new BinaryExpr(left, BinaryOp.MULTIPLY, right); } public static Expr mod(Expr left, Expr right) { return new BinaryExpr(left, BinaryOp.MODULUS, right); } public static Expr intDivide(Expr left, Expr right) { return new BinaryExpr(left, BinaryOp.INT_DIVIDE, right); } public static Expr divide(Expr left, Expr right) { return new BinaryExpr(left, BinaryOp.DIVIDE, right); } /* Unary Expressions */ public static Expr negative(Expr expr) { return new UnaryExpr(UnaryOp.NEGATIVE, expr); } public static Expr not(Expr expr) { return new UnaryExpr(UnaryOp.NOT, expr); } public static Expr pre(Expr expr) { return new UnaryExpr(UnaryOp.PRE, expr); } public static Expr optimizeNot(Expr expr) { if (expr instanceof UnaryExpr) { UnaryExpr ue = (UnaryExpr) expr; if (ue.op == UnaryOp.NOT) { return ue.expr; } } return new UnaryExpr(UnaryOp.NOT, expr); } /* IdExpr Expressions */ public static IdExpr id(String id) { return new IdExpr(id); } public static IdExpr id(VarDecl vd) { return new IdExpr(vd.id); } /* Literal Expressions */ public static RealExpr real(BigInteger bi) { return new RealExpr(new BigDecimal(bi)); } public static RealExpr real(String str) { return new RealExpr(new BigDecimal(str)); } public static RealExpr real(int i) { return new RealExpr(new BigDecimal(i)); } public static IntExpr integer(int i) { return new IntExpr(i); } public static Expr TRUE = new BoolExpr(true); public static Expr FALSE = new BoolExpr(false); /* Cast Expressions */ public static Expr castInt(Expr expr) { return new CastExpr(NamedType.INT, expr); } public static Expr castReal(Expr expr) { return new CastExpr(NamedType.REAL, expr); } /* Miscellaneous Expressions */ public static Expr and(List<Expr> conjuncts) { return conjuncts.stream().reduce((acc, e) -> and(acc, e)).orElse(TRUE); } public static Expr and(Expr... e) { return and(Arrays.asList(e)); } public static Expr or(List<Expr> disjuncts) { return disjuncts.stream().reduce((acc, e) -> or(acc, e)).orElse(FALSE); } public static Expr or(Expr... e) { return or(Arrays.asList(e)); } public static Expr xor(List<Expr> disjuncts) { return disjuncts.stream().reduce((acc, e) -> xor(acc, e)).orElse(FALSE); } public static Expr xor(Expr... e) { return xor(Arrays.asList(e)); } public static Expr chainRelation(BiFunction<Expr, Expr, Expr> f, Expr... e) { List<Expr> conjuncts = new ArrayList<>(); for (int i = 0; i < e.length - 1; i++) { conjuncts.add(f.apply(e[i], e[i + 1])); } return and(conjuncts); } public static Expr lessEqual(Expr... e) { return chainRelation(LustreUtil::lessEqual, e); } public static Expr less(Expr... e) { return chainRelation(LustreUtil::less, e); } public static Expr greaterEqual(Expr... e) { return chainRelation(LustreUtil::greaterEqual, e); } public static Expr greater(Expr... e) { return chainRelation(LustreUtil::greater, e); } public static Expr equal(Expr... e) { return chainRelation(LustreUtil::equal, e); } public static Expr ite(Expr cond, Expr thenExpr, Expr elseExpr) { return new IfThenElseExpr(cond, thenExpr, elseExpr); } public static Expr typeConstraint(String id, Type type) { if (type instanceof SubrangeIntType) { return subrangeConstraint(id, (SubrangeIntType) type); } else if (type instanceof EnumType) { return enumConstraint(id, (EnumType) type); } else { return null; } } public static Expr subrangeConstraint(String id, SubrangeIntType subrange) { return boundConstraint(id, new IntExpr(subrange.low), new IntExpr(subrange.high)); } public static Expr enumConstraint(String id, EnumType et) { return boundConstraint(id, new IntExpr(0), new IntExpr(et.values.size() - 1)); } private static Expr boundConstraint(String id, Expr low, Expr high) { return and(lessEqual(low, id(id)), lessEqual(id(id), high)); } /* Decls */ public static VarDecl varDecl(String name, Type type) { return new VarDecl(name, type); } public static Equation eq(IdExpr id, Expr expr) { return new Equation(id, expr); } /* Nodes */ public static Node historically() { return historically("historically"); } public static Node historically(String name) { NodeBuilder historically = new NodeBuilder(name); IdExpr signal = historically.createInput("signal", BOOL); IdExpr holds = historically.createOutput("holds", BOOL); // historically: holds = signal and (true -> pre holds); Equation equation = eq(holds, and(signal, arrow(TRUE, pre(holds)))); historically.addEquation(equation); return historically.build(); } public static Node once() { return once("once"); } public static Node once(String name) { NodeBuilder once = new NodeBuilder(name); IdExpr signal = once.createInput("signal", BOOL); IdExpr holds = once.createOutput("holds", BOOL); // once: holds = signal or (false -> pre holds); Equation equation = eq(holds, or(signal, arrow(FALSE, pre(holds)))); once.addEquation(equation); return once.build(); } public static Node since() { return since("since"); } public static Node since(String name) { NodeBuilder since = new NodeBuilder(name); IdExpr a = since.createInput("a", BOOL); IdExpr b = since.createInput("b", BOOL); IdExpr holds = since.createOutput("holds", BOOL); // since: holds = b or (a and (false -> pre holds)) Equation equation = eq(holds, or(b, and(a, arrow(FALSE, pre(holds))))); since.addEquation(equation); return since.build(); } public static Node triggers() { return triggers("triggers"); } public static Node triggers(String name) { NodeBuilder triggers = new NodeBuilder(name); IdExpr a = triggers.createInput("a", BOOL); IdExpr b = triggers.createInput("b", BOOL); IdExpr holds = triggers.createOutput("holds", BOOL); // triggers: holds = b and (a or (true -> pre holds)) Equation equation = eq(holds, and(b, or(a, arrow(TRUE, pre(holds))))); triggers.addEquation(equation); return triggers.build(); } }
7,887
24.04127
84
java
jkind
jkind-master/jkind-common/src/jkind/lustre/Equation.java
package jkind.lustre; import java.util.Collections; import java.util.List; import jkind.Assert; import jkind.lustre.visitors.AstVisitor; import jkind.util.Util; public class Equation extends Ast { public final List<IdExpr> lhs; public final Expr expr; public Equation(Location location, List<IdExpr> lhs, Expr expr) { super(location); Assert.isNotNull(expr); this.lhs = Util.safeList(lhs); this.expr = expr; } public Equation(Location location, IdExpr id, Expr expr) { super(location); this.lhs = Collections.singletonList(id); this.expr = expr; } public Equation(List<IdExpr> lhs, Expr expr) { this(Location.NULL, lhs, expr); } public Equation(IdExpr id, Expr expr) { this(Location.NULL, id, expr); } @Override public <T, S extends T> T accept(AstVisitor<T, S> visitor) { return visitor.visit(this); } }
845
20.692308
66
java
jkind
jkind-master/jkind-common/src/jkind/lustre/RealExpr.java
package jkind.lustre; import java.math.BigDecimal; import jkind.Assert; import jkind.lustre.visitors.ExprVisitor; public class RealExpr extends Expr { public final BigDecimal value; public RealExpr(Location location, BigDecimal value) { super(location); Assert.isNotNull(value); this.value = value; } public RealExpr(BigDecimal value) { this(Location.NULL, value); } @Override public <T> T accept(ExprVisitor<T> visitor) { return visitor.visit(this); } }
479
17.461538
55
java
jkind
jkind-master/jkind-common/src/jkind/lustre/RecordType.java
package jkind.lustre; import java.util.Map; import java.util.SortedMap; import jkind.Assert; import jkind.lustre.visitors.TypeVisitor; import jkind.util.Util; public class RecordType extends Type { public final String id; public final SortedMap<String, Type> fields; public RecordType(Location location, String id, Map<String, Type> fields) { super(location); Assert.isNotNull(id); Assert.isNotNull(fields); Assert.isTrue(fields.size() > 0); this.id = id; this.fields = Util.safeStringSortedMap(fields); } public RecordType(String id, Map<String, Type> fields) { this(Location.NULL, id, fields); } @Override public String toString() { return id; } @Override public int hashCode() { return id.hashCode(); } @Override public boolean equals(Object obj) { if (obj instanceof RecordType) { RecordType rt = (RecordType) obj; return id.equals(rt.id); } return false; } @Override public <T> T accept(TypeVisitor<T> visitor) { return visitor.visit(this); } }
1,008
19.18
76
java
jkind
jkind-master/jkind-common/src/jkind/lustre/Node.java
package jkind.lustre; import java.util.List; import jkind.Assert; import jkind.lustre.visitors.AstVisitor; import jkind.util.Util; public class Node extends Ast { public final String id; public final List<VarDecl> inputs; public final List<VarDecl> outputs; public final List<VarDecl> locals; public final List<Equation> equations; public final List<String> properties; public final List<Expr> assertions; public final List<String> ivc; public final List<String> realizabilityInputs; // Nullable public final Contract contract; // Nullable public Node(Location location, String id, List<VarDecl> inputs, List<VarDecl> outputs, List<VarDecl> locals, List<Equation> equations, List<String> properties, List<Expr> assertions, List<String> realizabilityInputs, Contract contract, List<String> ivc) { super(location); Assert.isNotNull(id); this.id = id; this.inputs = Util.safeList(inputs); this.outputs = Util.safeList(outputs); this.locals = Util.safeList(locals); this.equations = Util.safeList(equations); this.properties = Util.safeList(properties); this.assertions = Util.safeList(assertions); this.ivc = Util.safeList(ivc); this.realizabilityInputs = Util.safeNullableList(realizabilityInputs); this.contract = contract; } public Node(String id, List<VarDecl> inputs, List<VarDecl> outputs, List<VarDecl> locals, List<Equation> equations, List<String> properties, List<Expr> assertions, List<String> realizabilityInputs, Contract contract, List<String> ivc) { this(Location.NULL, id, inputs, outputs, locals, equations, properties, assertions, realizabilityInputs, contract, ivc); } @Override public <T, S extends T> T accept(AstVisitor<T, S> visitor) { return visitor.visit(this); } }
1,754
34.816327
116
java
jkind
jkind-master/jkind-common/src/jkind/lustre/RecordAccessExpr.java
package jkind.lustre; import jkind.Assert; import jkind.lustre.visitors.ExprVisitor; public class RecordAccessExpr extends Expr { public final Expr record; public final String field; public RecordAccessExpr(Location location, Expr record, String field) { super(location); Assert.isNotNull(record); Assert.isNotNull(field); this.record = record; this.field = field; } public RecordAccessExpr(Expr record, String field) { this(Location.NULL, record, field); } @Override public <T> T accept(ExprVisitor<T> visitor) { return visitor.visit(this); } }
573
21.076923
72
java
jkind
jkind-master/jkind-common/src/jkind/lustre/Expr.java
package jkind.lustre; import jkind.lustre.visitors.AstVisitor; import jkind.lustre.visitors.ExprVisitor; public abstract class Expr extends Ast { public Expr(Location location) { super(location); } @SuppressWarnings("unchecked") @Override public <T, S extends T> S accept(AstVisitor<T, S> visitor) { return accept((ExprVisitor<S>) visitor); } public abstract <T> T accept(ExprVisitor<T> visitor); }
413
22
61
java
jkind
jkind-master/jkind-common/src/jkind/lustre/Contract.java
package jkind.lustre; import java.util.List; import jkind.lustre.visitors.AstVisitor; import jkind.util.Util; public class Contract extends Ast { public final List<Expr> requires; public final List<Expr> ensures; public Contract(Location location, List<Expr> requires, List<Expr> ensures) { super(location); this.requires = Util.safeList(requires); this.ensures = Util.safeList(ensures); } public Contract(List<Expr> requires, List<Expr> ensures) { this(Location.NULL, requires, ensures); } @Override public <T, S extends T> T accept(AstVisitor<T, S> visitor) { return visitor.visit(this); } }
619
21.962963
78
java
jkind
jkind-master/jkind-common/src/jkind/lustre/BoolExpr.java
package jkind.lustre; import jkind.Assert; import jkind.lustre.visitors.ExprVisitor; public class BoolExpr extends Expr { public final boolean value; public BoolExpr(Location location, boolean value) { super(location); Assert.isNotNull(value); this.value = value; } public BoolExpr(boolean value) { this(Location.NULL, value); } @Override public <T> T accept(ExprVisitor<T> visitor) { return visitor.visit(this); } }
440
17.375
52
java
jkind
jkind-master/jkind-common/src/jkind/lustre/BinaryOp.java
package jkind.lustre; public enum BinaryOp { PLUS("+"), MINUS("-"), MULTIPLY("*"), DIVIDE("/"), INT_DIVIDE("div"), MODULUS("mod"), EQUAL("="), NOTEQUAL( "<>"), GREATER(">"), LESS("<"), GREATEREQUAL( ">="), LESSEQUAL("<="), OR("or"), AND("and"), XOR("xor"), IMPLIES("=>"), ARROW("->"); private String str; private BinaryOp(String str) { this.str = str; } @Override public String toString() { return str; } public static BinaryOp fromString(String string) { for (BinaryOp op : BinaryOp.values()) { if (op.toString().equals(string)) { return op; } } throw new IllegalArgumentException("Unknown binary operator: " + string); } }
667
22.857143
108
java
jkind
jkind-master/jkind-common/src/jkind/lustre/Program.java
package jkind.lustre; import java.util.Arrays; import java.util.List; import jkind.lustre.visitors.AstVisitor; import jkind.util.Util; public class Program extends Ast { public final List<TypeDef> types; public final List<Constant> constants; public final List<Function> functions; public final List<Node> nodes; public final String main; public Program(Location location, List<TypeDef> types, List<Constant> constants, List<Function> functions, List<Node> nodes, String main) { super(location); this.types = Util.safeList(types); this.constants = Util.safeList(constants); this.functions = Util.safeList(functions); this.nodes = Util.safeList(nodes); if (main == null && nodes != null && nodes.size() > 0) { this.main = nodes.get(nodes.size() - 1).id; } else { this.main = main; } } public Program(Node... nodes) { this(Location.NULL, null, null, null, Arrays.asList(nodes), null); } public Node getMainNode() { for (Node node : nodes) { if (node.id.equals(main)) { return node; } } return null; } @Override public <T, S extends T> T accept(AstVisitor<T, S> visitor) { return visitor.visit(this); } }
1,167
23.851064
107
java
jkind
jkind-master/jkind-common/src/jkind/lustre/Constant.java
package jkind.lustre; import jkind.Assert; import jkind.lustre.visitors.AstVisitor; public class Constant extends Ast { public final String id; public final Type type; public final Expr expr; public Constant(Location location, String id, Type type, Expr expr) { super(location); Assert.isNotNull(id); // 'type' can be null Assert.isNotNull(expr); this.id = id; this.type = type; this.expr = expr; } public Constant(String id, Type type, Expr expr) { this(Location.NULL, id, type, expr); } @Override public <T, S extends T> T accept(AstVisitor<T, S> visitor) { return visitor.visit(this); } }
624
20.551724
70
java
jkind
jkind-master/jkind-common/src/jkind/lustre/UnaryOp.java
package jkind.lustre; public enum UnaryOp { NEGATIVE("-"), NOT("not"), PRE("pre"); private String str; private UnaryOp(String str) { this.str = str; } @Override public String toString() { return str; } public static UnaryOp fromString(String string) { for (UnaryOp op : UnaryOp.values()) { if (op.toString().equals(string)) { return op; } } return null; } }
392
14.115385
50
java
jkind
jkind-master/jkind-common/src/jkind/lustre/EnumType.java
package jkind.lustre; import java.util.List; import jkind.Assert; import jkind.lustre.visitors.TypeVisitor; import jkind.util.Util; public class EnumType extends Type { public final String id; public final List<String> values; public EnumType(Location location, String id, List<String> values) { super(location); Assert.isNotNull(id); this.id = id; this.values = Util.safeList(values); } public EnumType(String id, List<String> values) { this(Location.NULL, id, values); } public String getValue(int i) { return values.get(i); } @Override public String toString() { return id; } @Override public int hashCode() { return id.hashCode(); } @Override public boolean equals(Object obj) { if (obj instanceof EnumType) { EnumType et = (EnumType) obj; return id.equals(et.id); } return false; } @Override public <T> T accept(TypeVisitor<T> visitor) { return visitor.visit(this); } }
934
17.333333
69
java
jkind
jkind-master/jkind-common/src/jkind/lustre/TupleType.java
package jkind.lustre; import java.util.List; import java.util.StringJoiner; import jkind.lustre.visitors.TypeVisitor; import jkind.util.Util; public class TupleType extends Type { public final List<Type> types; public TupleType(List<? extends Type> types) { super(Location.NULL); if (types != null && types.size() == 1) { throw new IllegalArgumentException("Cannot construct singleton tuple type"); } this.types = Util.safeList(types); } public static Type compress(List<? extends Type> types) { if (types.size() == 1) { return types.get(0); } return new TupleType(types); } @Override public String toString() { StringJoiner text = new StringJoiner(", ", "(", ")"); types.forEach(t -> text.add(t.toString())); return text.toString(); } @Override public int hashCode() { return types.hashCode(); } @Override public boolean equals(Object obj) { if (obj instanceof TupleType) { TupleType tt = (TupleType) obj; return types.equals(tt.types); } return false; } @Override public <T> T accept(TypeVisitor<T> visitor) { return visitor.visit(this); } }
1,111
20.384615
79
java
jkind
jkind-master/jkind-common/src/jkind/lustre/Function.java
package jkind.lustre; import java.util.Collections; import java.util.List; import jkind.Assert; import jkind.lustre.visitors.AstVisitor; import jkind.util.Util; public class Function extends Ast { public final String id; public final List<VarDecl> inputs; public final List<VarDecl> outputs; public Function(Location location, String id, List<VarDecl> inputs, List<VarDecl> outputs) { super(location); Assert.isNotNull(id); this.id = id; this.inputs = Util.safeList(inputs); this.outputs = Util.safeList(outputs); } public Function(String id, List<VarDecl> inputs, List<VarDecl> outputs) { this(Location.NULL, id, inputs, outputs); } public Function(String id, List<VarDecl> inputs, VarDecl output) { this(Location.NULL, id, inputs, Collections.singletonList(output)); } @Override public <T, S extends T> T accept(AstVisitor<T, S> visitor) { return visitor.visit(this); } }
909
24.277778
93
java
jkind
jkind-master/jkind-common/src/jkind/lustre/ArrayExpr.java
package jkind.lustre; import java.util.List; import jkind.lustre.visitors.ExprVisitor; import jkind.util.Util; public class ArrayExpr extends Expr { public final List<Expr> elements; public ArrayExpr(Location loc, List<Expr> elements) { super(loc); this.elements = Util.safeList(elements); } public ArrayExpr(List<Expr> elements) { this(Location.NULL, elements); } @Override public <T> T accept(ExprVisitor<T> visitor) { return visitor.visit(this); } }
475
18.04
54
java
jkind
jkind-master/jkind-common/src/jkind/lustre/CastExpr.java
package jkind.lustre; import jkind.Assert; import jkind.lustre.visitors.ExprVisitor; public class CastExpr extends Expr { public final Type type; public final Expr expr; public CastExpr(Location location, Type type, Expr expr) { super(location); Assert.isNotNull(type); Assert.isNotNull(expr); this.type = type; this.expr = expr; } public CastExpr(Type type, Expr expr) { this(Location.NULL, type, expr); } @Override public <T> T accept(ExprVisitor<T> visitor) { return visitor.visit(this); } }
523
18.407407
59
java
jkind
jkind-master/jkind-common/src/jkind/lustre/Type.java
package jkind.lustre; import jkind.Assert; import jkind.lustre.visitors.TypeVisitor; public abstract class Type { public final Location location; protected Type(Location location) { Assert.isNotNull(location); this.location = location; } public abstract <T> T accept(TypeVisitor<T> visitor); }
306
18.1875
54
java
jkind
jkind-master/jkind-common/src/jkind/lustre/ArrayType.java
package jkind.lustre; import jkind.Assert; import jkind.lustre.visitors.TypeVisitor; public class ArrayType extends Type { public final Type base; public final int size; public ArrayType(Location location, Type base, int size) { super(location); Assert.isNotNull(base); Assert.isTrue(size > 0); this.base = base; this.size = size; } public ArrayType(Type base, int size) { this(Location.NULL, base, size); } @Override public String toString() { return base + "[" + size + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((base == null) ? 0 : base.hashCode()); result = prime * result + size; return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof ArrayType)) { return false; } ArrayType other = (ArrayType) obj; if (base == null) { if (other.base != null) { return false; } } else if (!base.equals(other.base)) { return false; } if (size != other.size) { return false; } return true; } @Override public <T> T accept(TypeVisitor<T> visitor) { return visitor.visit(this); } }
1,231
17.953846
67
java
jkind
jkind-master/jkind-common/src/jkind/lustre/IfThenElseExpr.java
package jkind.lustre; import jkind.Assert; import jkind.lustre.visitors.ExprVisitor; public class IfThenElseExpr extends Expr { public final Expr cond; public final Expr thenExpr; public final Expr elseExpr; public IfThenElseExpr(Location location, Expr cond, Expr thenExpr, Expr elseExpr) { super(location); Assert.isNotNull(cond); Assert.isNotNull(thenExpr); Assert.isNotNull(elseExpr); this.cond = cond; this.thenExpr = thenExpr; this.elseExpr = elseExpr; } public IfThenElseExpr(Expr cond, Expr thenExpr, Expr elseExpr) { this(Location.NULL, cond, thenExpr, elseExpr); } @Override public <T> T accept(ExprVisitor<T> visitor) { return visitor.visit(this); } }
696
22.233333
84
java
jkind
jkind-master/jkind-common/src/jkind/lustre/BinaryExpr.java
package jkind.lustre; import jkind.Assert; import jkind.lustre.visitors.ExprVisitor; public class BinaryExpr extends Expr { public final Expr left; public final BinaryOp op; public final Expr right; public BinaryExpr(Location location, Expr left, BinaryOp op, Expr right) { super(location); Assert.isNotNull(left); Assert.isNotNull(op); Assert.isNotNull(right); this.left = left; this.op = op; this.right = right; } public BinaryExpr(Expr left, BinaryOp op, Expr right) { this(Location.NULL, left, op, right); } @Override public <T> T accept(ExprVisitor<T> visitor) { return visitor.visit(this); } }
632
20.827586
75
java
jkind
jkind-master/jkind-common/src/jkind/lustre/RecordExpr.java
package jkind.lustre; import java.util.Map; import java.util.SortedMap; import jkind.Assert; import jkind.lustre.visitors.ExprVisitor; import jkind.util.Util; public class RecordExpr extends Expr { public final String id; public final SortedMap<String, Expr> fields; public RecordExpr(Location loc, String id, Map<String, Expr> fields) { super(loc); Assert.isNotNull(id); Assert.isNotNull(fields); Assert.isTrue(fields.size() > 0); this.id = id; this.fields = Util.safeStringSortedMap(fields); } public RecordExpr(String id, Map<String, Expr> fields) { this(Location.NULL, id, fields); } @Override public <T> T accept(ExprVisitor<T> visitor) { return visitor.visit(this); } }
707
21.125
71
java
jkind
jkind-master/jkind-common/src/jkind/lustre/RecordUpdateExpr.java
package jkind.lustre; import jkind.Assert; import jkind.lustre.visitors.ExprVisitor; public class RecordUpdateExpr extends Expr { public final Expr record; public final String field; public final Expr value; public RecordUpdateExpr(Location location, Expr record, String field, Expr value) { super(location); Assert.isNotNull(record); Assert.isNotNull(field); Assert.isNotNull(value); this.record = record; this.field = field; this.value = value; } public RecordUpdateExpr(Expr record, String field, Expr value) { this(Location.NULL, record, field, value); } @Override public <T> T accept(ExprVisitor<T> visitor) { return visitor.visit(this); } }
679
22.448276
84
java
jkind
jkind-master/jkind-common/src/jkind/lustre/Location.java
package jkind.lustre; public class Location { public final int line; public final int charPositionInLine; public Location(int line, int charPositionInLine) { this.line = line; this.charPositionInLine = charPositionInLine; } @Override public String toString() { return line + ":" + charPositionInLine; } public static final Location NULL = new Location(0, 0); }
379
19
56
java
jkind
jkind-master/jkind-common/src/jkind/lustre/TupleExpr.java
package jkind.lustre; import java.util.List; import jkind.lustre.visitors.ExprVisitor; import jkind.util.Util; public class TupleExpr extends Expr { public final List<Expr> elements; public TupleExpr(Location loc, List<? extends Expr> elements) { super(loc); if (elements != null && elements.size() == 1) { throw new IllegalArgumentException("Cannot construct singleton tuple"); } this.elements = Util.safeList(elements); } public TupleExpr(List<? extends Expr> elements) { this(Location.NULL, elements); } public static Expr compress(List<? extends Expr> exprs) { if (exprs.size() == 1) { return exprs.get(0); } return new TupleExpr(exprs); } @Override public <T> T accept(ExprVisitor<T> visitor) { return visitor.visit(this); } }
773
21.114286
74
java
jkind
jkind-master/jkind-common/src/jkind/lustre/IntExpr.java
package jkind.lustre; import java.math.BigInteger; import jkind.Assert; import jkind.lustre.visitors.ExprVisitor; public class IntExpr extends Expr { public final BigInteger value; public IntExpr(Location location, BigInteger value) { super(location); Assert.isNotNull(value); this.value = value; } public IntExpr(BigInteger value) { this(Location.NULL, value); } public IntExpr(int value) { this(Location.NULL, BigInteger.valueOf(value)); } @Override public <T> T accept(ExprVisitor<T> visitor) { return visitor.visit(this); } }
559
17.666667
54
java
jkind
jkind-master/jkind-common/src/jkind/lustre/TypeDef.java
package jkind.lustre; import jkind.Assert; import jkind.lustre.visitors.AstVisitor; public class TypeDef extends Ast { public final String id; public final Type type; public TypeDef(Location location, String id, Type type) { super(location); Assert.isNotNull(id); Assert.isNotNull(type); this.id = id; this.type = type; } public TypeDef(String id, Type type) { this(Location.NULL, id, type); } @Override public <T, S extends T> T accept(AstVisitor<T, S> visitor) { return visitor.visit(this); } }
524
19.192308
61
java
jkind
jkind-master/jkind-common/src/jkind/lustre/UnaryExpr.java
package jkind.lustre; import jkind.Assert; import jkind.lustre.visitors.ExprVisitor; public class UnaryExpr extends Expr { public final UnaryOp op; public final Expr expr; public UnaryExpr(Location location, UnaryOp op, Expr expr) { super(location); Assert.isNotNull(op); Assert.isNotNull(expr); this.op = op; this.expr = expr; } public UnaryExpr(UnaryOp op, Expr expr) { this(Location.NULL, op, expr); } @Override public <T> T accept(ExprVisitor<T> visitor) { return visitor.visit(this); } }
521
18.333333
61
java