Commit 1e657922 authored by Tobias Meuser's avatar Tobias Meuser
Browse files

Merged tm/vehicular-services into master-integration

parents 2a24c1a4 2c04ab95
......@@ -408,13 +408,10 @@
</dependency>
<!-- Traci as a Service -->
<!--
<dependency>
<groupId>maki</groupId>
<artifactId>simonstrator-traci</artifactId>
<version>0.2-SNAPSHOT</version>
</dependency>
-->
</dependencies>
</project>
......@@ -2,17 +2,17 @@
* Copyright (c) 2005-2010 KOM – Multimedia Communications Lab
*
* This file is part of PeerfactSim.KOM.
*
*
* PeerfactSim.KOM is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
*
* PeerfactSim.KOM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*
* You should have received a copy of the GNU General Public License
* along with PeerfactSim.KOM. If not, see <http://www.gnu.org/licenses/>.
*
......@@ -31,10 +31,10 @@ import de.tudarmstadt.maki.simonstrator.api.component.network.NetworkComponent.N
* all parameter-related stuff has to be implemented in the {@link Link}. This
* enum is used throughout the new {@link LinkLayer} and also on application
* level if you want to explicitly specify which component to use.
*
*
* It provides basic defaults for MTU and Drop rates in the medium, which might
* be used inside the MacLayer or as part of a {@link Link}
*
*
* @author Bjoern Richerzhagen
* @version 1.0, 25.02.2012
*
......@@ -48,16 +48,16 @@ public enum PhyType {
* Direct wireless connections between adjacent hosts or AP-based (decided
* by the MAC/TopologyView used). Based on
* "WiFi in Ad Hoc Mode: A Meaurement Study" by Anastasi et al. (2004),
*
*
* Assuming the following defaults: 1% drop-rate of LinkLayer-Packets
* (LinkLayer might add retransmission behavior as in 802.11), 5MBit/s netto
* (802.11b) BW, 500us latency, 2,2kB MTU, Broadcast
*/
WIFI(NetInterfaceName.WIFI, 0.01, 5 * Rate.Mbit_s, 500 * Time.MICROSECOND,
WIFI(NetInterfaceName.WIFI, 0.01, 12 * Rate.Mbit_s, 500 * Time.MICROSECOND,
2334, true),
/**
* A wired connection based on a TopologyView
*
*
* Assuming the following defaults: 0.1% link-layer loss, 100 Mbit/s, 1ms
* Link-Latency, 1,5kB MTU
*/
......@@ -75,7 +75,7 @@ public enum PhyType {
500 * Simulator.MICROSECOND_UNIT, 1472, false),
/**
*
*
* Bluetooth, short-ranged wireless transmissions between adjacent hosts
*
* Assuming the following defaults: zero link-layer packet loss, 3Mbit/s BW,
......@@ -122,7 +122,7 @@ public enum PhyType {
private NetInterfaceName netInterfaceName;
/**
*
*
* @param defaultDropProbability
* @param defaultRawBW
* bw in bit/s
......@@ -154,7 +154,7 @@ public enum PhyType {
/**
* The Default BW of a link (unidirectional) in bit/s
*
*
* @return
*/
public long getDefaultBW() {
......@@ -165,7 +165,7 @@ public enum PhyType {
* has to return true if the medium is by its nature a broadcast medium (ie.
* sending a message will prohibit sending for all other hosts in range). If
* the medium supports Multiplexing such as UMTS, set this to false.
*
*
* @return
*/
public boolean isBroadcastMedium() {
......@@ -174,7 +174,7 @@ public enum PhyType {
/**
* Long-term replacement of PHY
*
*
* @return
*/
public NetInterfaceName getNetInterfaceName() {
......
......@@ -2,17 +2,17 @@
* Copyright (c) 2005-2010 KOM – Multimedia Communications Lab
*
* This file is part of PeerfactSim.KOM.
*
*
* PeerfactSim.KOM is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
*
* PeerfactSim.KOM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*
* You should have received a copy of the GNU General Public License
* along with PeerfactSim.KOM. If not, see <http://www.gnu.org/licenses/>.
*
......@@ -38,7 +38,7 @@ import de.tudarmstadt.maki.simonstrator.api.util.XMLConfigurableConstructor;
* basic filter for more complex statistical computations on the provided
* dataset. Common functions are included as inner classes in this abstract
* filter.
*
*
* @author Bjoern Richerzhagen
* @version 1.0, 08.08.2012
*/
......@@ -92,23 +92,22 @@ public abstract class StatisticsFilter extends
if (values == null || values.isEmpty()) {
return null;
}
LinkedList<MetricValue> mvs = new LinkedList<MetricValue>(values);
return new StatisticsMetricValue(mvs);
return new StatisticsMetricValue(values);
}
/**
* Computes statistics such as svg, sum, std...
*
*
* @author Bjoern Richerzhagen
* @version 1.0, 08.08.2012
*/
private class StatisticsMetricValue implements MetricValue<Double> {
private final List<MetricValue> inputs;
private final List<? extends MetricValue<?>> inputs;
private Double result = Double.NaN;
public StatisticsMetricValue(List<MetricValue> inputs) {
public StatisticsMetricValue(List<? extends MetricValue<?>> inputs) {
this.inputs = inputs;
}
......@@ -175,7 +174,7 @@ public abstract class StatisticsFilter extends
/**
* Function that has to compute sth. on the double-list. For convenience,
* some basic statistical values are already included.
*
*
* @param incoming
* @param count
* number of values
......@@ -191,7 +190,7 @@ public abstract class StatisticsFilter extends
/**
* Standard deviation
*
*
* @author Bjoern Richerzhagen
* @version 1.0, 08.08.2012
*/
......@@ -208,7 +207,7 @@ public abstract class StatisticsFilter extends
/**
* Average
*
*
* @author Bjoern Richerzhagen
* @version 1.0, 08.08.2012
*/
......@@ -231,7 +230,7 @@ public abstract class StatisticsFilter extends
/**
* Minimum
*
*
* @author Bjoern Richerzhagen
* @version 1.0, 08.08.2012
*/
......@@ -250,7 +249,7 @@ public abstract class StatisticsFilter extends
/**
* Maximum
*
*
* @author Bjoern Richerzhagen
* @version 1.0, 08.08.2012
*/
......@@ -271,7 +270,7 @@ public abstract class StatisticsFilter extends
* The Percentile, pass a value between 0 (exclusive) and 100 (inclusive).
* The resulting metric will be called "P20_incomingmetric" in the case of
* the 20th percentile.
*
*
* @author Bjoern Richerzhagen
* @version 1.0, 08.08.2012
*/
......
......@@ -2,17 +2,17 @@
* Copyright (c) 2005-2010 KOM – Multimedia Communications Lab
*
* This file is part of PeerfactSim.KOM.
*
*
* PeerfactSim.KOM is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
*
* PeerfactSim.KOM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*
* You should have received a copy of the GNU General Public License
* along with PeerfactSim.KOM. If not, see <http://www.gnu.org/licenses/>.
*
......@@ -31,7 +31,7 @@ import de.tudarmstadt.maki.simonstrator.api.common.metric.Metric.MetricValue;
/**
* Live Monitoring of all configured {@link Metric}s
*
*
* @author Bjoern Richerzhagen
* @version 1.0, 07.08.2012
*/
......@@ -55,7 +55,7 @@ public class MetricOutputLive extends AbstractOutput {
/**
* Just matching the {@link ProgressValue}-interface to the
* {@link TransitMetric} interface.
*
*
* @author Bjoern Richerzhagen
* @version 1.0, 07.08.2012
*/
......
/*
* Copyright (c) 2005-2010 KOM – Multimedia Communications Lab
*
* This file is part of PeerfactSim.KOM.
*
* PeerfactSim.KOM is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* PeerfactSim.KOM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with PeerfactSim.KOM. If not, see <http://www.gnu.org/licenses/>.
*
*/
package de.tud.kom.p2psim.impl.analyzer.metric.spatial;
import java.util.ArrayList;
import java.util.List;
import de.tudarmstadt.maki.simonstrator.api.common.metric.AbstractMetric;
import de.tudarmstadt.maki.simonstrator.api.common.metric.ActiveSpatialMetric;
import de.tudarmstadt.maki.simonstrator.api.common.metric.Metric;
public abstract class AbstractSpatialMetric<T extends AbstractSpatialMetricValue<?>> extends AbstractMetric<T> implements Metric<T>, ActiveSpatialMetric<T> {
protected boolean aggregate = false;
public AbstractSpatialMetric(String pDescription, MetricUnit pUnit) {
super(pDescription, pUnit);
}
public AbstractSpatialMetric(String pName, String pDescription, MetricUnit pUnit) {
super(pName, pDescription, pUnit);
}
protected void setOverallMetric(T aggregate) {
super.setOverallMetric(aggregate);
}
@Override
public boolean isAggregated() {
return aggregate;
}
private List<ActiveSpatialMetricListener> _listeners = new ArrayList<>();
@Override
public void addActiveSpatialMetricListener(ActiveSpatialMetricListener pListener) {
_listeners.add(pListener);
}
@Override
public void notifyListeners() {
for (ActiveSpatialMetricListener activeSpatialMetricListener : _listeners) {
activeSpatialMetricListener.onMetricUpdate(this);
}
}
}
/*
* Copyright (c) 2005-2010 KOM – Multimedia Communications Lab
*
* This file is part of PeerfactSim.KOM.
*
* PeerfactSim.KOM is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* PeerfactSim.KOM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with PeerfactSim.KOM. If not, see <http://www.gnu.org/licenses/>.
*
*/
package de.tud.kom.p2psim.impl.analyzer.metric.spatial;
import de.tudarmstadt.maki.simonstrator.api.common.metric.ActiveSpatialMetric;
import de.tudarmstadt.maki.simonstrator.api.common.metric.ActiveSpatialMetric.SpatialMetricValue;
import de.tudarmstadt.maki.simonstrator.api.component.sensor.location.Location;
public abstract class AbstractSpatialMetricValue<S extends Object> implements SpatialMetricValue<S> {
private S value;
private Location location;
private ActiveSpatialMetric<?> metric;
public AbstractSpatialMetricValue(ActiveSpatialMetric<?> pMetric) {
metric = pMetric;
}
public AbstractSpatialMetricValue(ActiveSpatialMetric<?> pMetric, S pValue) {
metric = pMetric;
value = pValue;
}
public void setValue(S pValue, Location pLocation) {
value = pValue;
location = pLocation;
metric.notifyListeners();
}
@Override
public S getValue() {
return value;
}
@Override
public Location getLocation() {
return location;
}
}
\ No newline at end of file
......@@ -2,17 +2,17 @@
* Copyright (c) 2005-2011 KOM - Multimedia Communications Lab
*
* This file is part of PeerfactSim.KOM.
*
*
* PeerfactSim.KOM is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
*
* PeerfactSim.KOM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*
* You should have received a copy of the GNU General Public License
* along with PeerfactSim.KOM. If not, see <http://www.gnu.org/licenses/>.
*
......@@ -44,7 +44,7 @@ import de.tudarmstadt.maki.simonstrator.api.component.core.MonitorComponent;
/**
* New Monitor-Component to work with the simonstrator-API (provides
* overlay-access to analyzers)
*
*
* @author Bjoern Richerzhagen
* @version 1.0, Jul 8, 2013
*/
......@@ -119,7 +119,7 @@ public class DefaultMonitor implements MonitorComponent, EventHandler,
/**
* Called by the Configurator
*
*
* @param analyzer
*/
public void setAnalyzer(Analyzer analyzer) {
......@@ -128,7 +128,7 @@ public class DefaultMonitor implements MonitorComponent, EventHandler,
/**
* Specifies where to write the monitoring results to.
*
*
* @param output
* writer (e.g. FileWriter, StringWriter, ...)
*/
......@@ -143,7 +143,7 @@ public class DefaultMonitor implements MonitorComponent, EventHandler,
public void setTableName(String tableName) {
System.out.println("Table Name is set to: " + tableName);
if (tableName != null && !tableName.equals("")) {
DAO.database = tableName;
DAO.setDatabase(tableName);
}
}
......
......@@ -2,17 +2,17 @@
* Copyright (c) 2005-2010 KOM – Multimedia Communications Lab
*
* This file is part of PeerfactSim.KOM.
*
*
* PeerfactSim.KOM is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
*
* PeerfactSim.KOM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*
* You should have received a copy of the GNU General Public License
* along with PeerfactSim.KOM. If not, see <http://www.gnu.org/licenses/>.
*
......@@ -60,16 +60,16 @@ import de.tudarmstadt.maki.simonstrator.api.component.network.NetID;
* As with the {@link ModularLinkLayer} you should extend this class to add a
* more advanced MAC to ensure basic functionality and consistent behavior. For
* this reason, some methods in this class are marked as final...
*
*
* If a MAC wants to implement a protocol (ie. send messages to other MACs
* without triggering a deliver to higher layers) it can do so by implementing a
* corresponding Message type and/or {@link MacEventInformation}. <b>A Message
* is only delivered to the higher layers if notifyLinkLayer is called</b>.
*
*
* This Layer takes care of energy consumption, as long as the sendUnicast and
* sendBroadcast-methods are used to dispatch all messages (also the
* control-messages, if a protocol is implemented)
*
*
* @author Bjoern Richerzhagen
* @version 1.0, 21.02.2012
*/
......@@ -98,7 +98,7 @@ public abstract class AbstractMacLayer implements MacLayer {
* Our own MacAddress on this PHY
*/
private MacAddress macAddress;
/**
* Our own IP used by the NetLayer on this PHY. Not available during initialization.
*/
......@@ -127,7 +127,7 @@ public abstract class AbstractMacLayer implements MacLayer {
private final boolean enableErrorControl;
/**
*
*
*/
private boolean isOnline;
......@@ -156,7 +156,7 @@ public abstract class AbstractMacLayer implements MacLayer {
* Returns an approximation of the current bandwidth
*/
protected final BandwidthEstimator currentBandwidth;
private final Random random = Randoms.getRandom(AbstractMacLayer.class);
/*
......@@ -179,7 +179,7 @@ public abstract class AbstractMacLayer implements MacLayer {
/**
* Create a new MacLayer without bounds on the outgoing message queue (ie.
* endless size, no limit on the waiting time).
*
*
* @param ownMacAddress
* @param phy
* @param maxRetransmissions
......@@ -198,7 +198,7 @@ public abstract class AbstractMacLayer implements MacLayer {
/**
* Create a new MacLayer with a bounded outgoing queue (max length) and a
* timeout for messages in said queue.
*
*
* @param ownMacAddress
* @param phy
* @param maxQueueLength
......@@ -291,7 +291,7 @@ public abstract class AbstractMacLayer implements MacLayer {
/**
* Use this component to account for energy consumption. This is safe to
* use, as it is always backed by a stub - it is never null.
*
*
* @return
*/
@Override
......@@ -301,7 +301,7 @@ public abstract class AbstractMacLayer implements MacLayer {
/**
* Current size of the outgoing Queue
*
*
* @return
*/
protected final int getQueueSize() {
......@@ -310,7 +310,7 @@ public abstract class AbstractMacLayer implements MacLayer {
/**
* Maximum length of the outgoing queue, if equal to zero there is no limit
*
*
* @return
*/
protected final int getMaxQueueLength() {
......@@ -319,7 +319,7 @@ public abstract class AbstractMacLayer implements MacLayer {
/**
* Gets the maximal retransmissions.
*
*
* @return the maximal retransmissions.
*/
public final int getMaxRetransmissions() {
......@@ -329,7 +329,7 @@ public abstract class AbstractMacLayer implements MacLayer {
/**
* Maximum time a message is kept in the outgoing queue. If equal to zero
* there is no limit.
*
*
* @return
*/
protected final long getMaxTimeInQueue() {
......@@ -339,7 +339,7 @@ public abstract class AbstractMacLayer implements MacLayer {
/**
* Retrieves and <b>removes</b> the first element in the Queue, after all
* entries that already timed out are deleted.
*
*
* @return
*/
protected final QueueEntry getQueueHead() {
......@@ -351,7 +351,7 @@ public abstract class AbstractMacLayer implements MacLayer {
* Removes all messages that are already waiting longer than maxTimeInQueue,
* notifying messageDropped() for each dropped message. The reason will be
* QUEUE_TIMEOUT in this case.
*
*
*/
private void removeOutdatedQueueEntries() {
if (maxTimeInQueue == 0) {
......@@ -371,11 +371,11 @@ public abstract class AbstractMacLayer implements MacLayer {
/**
* This is called whenever a drop occurs within the MAC/PHY. A great
* opportunity to add an Analyzer or some error handling for higher layers.
*
*
* Please note, that this might happen asynchronously - the messages are not
* removed from the queue the second their timeout expires but instead as
* soon as a new send() or a new getQueueHead() is issued.
*
*
* @param reason
* @param msg
*/
......@@ -402,7 +402,7 @@ public abstract class AbstractMacLayer implements MacLayer {
/**
* Notification: a message arrived!
*
*
* @param message
* the message itself
* @param info
......@@ -413,7 +413,7 @@ public abstract class AbstractMacLayer implements MacLayer {
/**
* This is to be called by the MAC if a Message should be passed to upper
* layers (ie. it is no MAC_ctrl-Message)
*
*
* @param eventInfo
*/
protected final void notifyLinkLayer(LinkMessageEvent eventInfo) {
......@@ -424,7 +424,7 @@ public abstract class AbstractMacLayer implements MacLayer {
/**
* Send a Message to the MAC on the receiver-side (event scheduling).
*
*
* @param receiver
* @param eventInformation
* @param delay
......@@ -454,7 +454,7 @@ public abstract class AbstractMacLayer implements MacLayer {
/**
* Use this method to dispatch a broadcast message in your MAC-Layer. It
* will take care of energy consumption and scheduling.
*
*
* @param eventInfo
* an implementation of {@link MacEventInformation} containing
* information about the message to send as well as the message
......@@ -516,7 +516,7 @@ public abstract class AbstractMacLayer implements MacLayer {
/**
* Send an unicast message
*
*
* @param toSend
*/
protected final long sendUnicast(MacEventInformation eventInfo) {
......@@ -592,13 +592,13 @@ public abstract class AbstractMacLayer implements MacLayer {
* broadcast, the BW should be constant across all links (we assume the PHY
* selects a fixed, more robust modulation for Broadcasts), as there is no
* handshaking. Therefore, Broadcasts have no retransmits.
*
*
* This method <b>must be called exactly once</b> for every receiver of a
* message (in the unicast case, it will be called only once). The receiver
* is determined by the link-object. Access this method via the sendUnicast
* and sendBroadcast methods to ensure correct behavior of all callbacks and
* events.
*
*
* @param eventInfo
* containing the Message
* @param l
......@@ -758,10 +758,10 @@ public abstract class AbstractMacLayer implements MacLayer {
* sending would be possible at the full RawBandwidth of the PHY). A more
* advanced MAC will add some coding (making the message larger) and access
* control scheme for multiple transmissions.
*
*
* This time is later used to account for energy consumption at sender and
* receiver.
*
*
* @param msg
* @param l
* @return
......@@ -782,7 +782,7 @@ public abstract class AbstractMacLayer implements MacLayer {
/**
* Overwrite this method to implement additional event handling, if needed.
*
*
* @param se
*/
protected void handleEvent(Object data, int type) {
......@@ -898,7 +898,7 @@ public abstract class AbstractMacLayer implements MacLayer {
public final MacAddress getMacAddress() {
return macAddress;
}
@Override
public NetID getNetId() {
if (netID == null) {
......@@ -928,7 +928,7 @@ public abstract class AbstractMacLayer implements MacLayer {
/**
* An entry in the Message queue of the MAC
*
*
* @author Bjoern Richerzhagen
* @version 1.0, 21.02.2012
*/
......@@ -967,7 +967,7 @@ public abstract class AbstractMacLayer implements MacLayer {
* A Stub for an {@link EnergyCommunicationComponent} to allow simulations
* without an energy model. Otherwise we would have to flood the code with
* if == null statements.
*
*
* @author Bjoern Richerzhagen
* @version 1.0, 27.02.2012
*/
......@@ -1031,14 +1031,14 @@ public abstract class AbstractMacLayer implements MacLayer {
@Override
public void doFakeStateChange() {
// TODO Auto-generated method stub
}
}
/**
* A Live-Analyzer that aggregates Message Drop reasons inside the MAC.
*
*
* @author Bjoern Richerzhagen
* @version 1.0, 26.03.2012
*/
......
......@@ -2,17 +2,17 @@
* Copyright (c) 2005-2010 KOM – Multimedia Communications Lab
*
* This file is part of PeerfactSim.KOM.
*
*
* PeerfactSim.KOM is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
*
* PeerfactSim.KOM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*
* You should have received a copy of the GNU General Public License
* along with PeerfactSim.KOM. If not, see <http://www.gnu.org/licenses/>.
*
......@@ -37,7 +37,7 @@ import de.tudarmstadt.maki.simonstrator.api.Time;
* the other (this does not imply that this MAC handles collisions on a
* broadcast medium). It just mimics the behavior of the ModularNetLayer with a
* TrafficControl-Strategy enabled.
*
*
* @author Bjoern Richerzhagen
* @version 1.0, 24.03.2012
*/
......@@ -64,7 +64,7 @@ public class EnqueuingMac extends AbstractMacLayer {
* A MAC that provides an outgoing queue (messages are sent one after the
* other). This may lead to packet drop if the queue is bound or if a
* timeout is configured and the message has been in the queue for too long.
*
*
* @param ownMacAddress
* @param phy
* @param maxQueueLength
......
......@@ -2,17 +2,17 @@
* Copyright (c) 2005-2011 KOM - Multimedia Communications Lab
*
* This file is part of PeerfactSim.KOM.
*
*
* PeerfactSim.KOM is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
*
* PeerfactSim.KOM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*
* You should have received a copy of the GNU General Public License
* along with PeerfactSim.KOM. If not, see <http://www.gnu.org/licenses/>.
*
......@@ -37,6 +37,7 @@ import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.sound.midi.Synthesizer;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
......@@ -70,11 +71,11 @@ import de.tudarmstadt.maki.simonstrator.api.util.XMLConfigurableConstructor;
/**
* The default implementation of the configuration mechanism. For a detailed
* explanation, see {@link Configurator}.
*
*
* @author Konstantin Pussep
* @author Sebastian Kaune
* @version 3.0, 14.12.2007
*
*
*/
public class DefaultConfigurator implements Configurator {
......@@ -84,7 +85,7 @@ public class DefaultConfigurator implements Configurator {
* this name. They will be treated as if they were direct children of the
* parent of this fake container element.
* </p>
*
*
* <p>
* Needed to work around the lack of support for XPointer in the XInclude
* implementation of Apache Xerces (which should be the most common
......@@ -145,10 +146,12 @@ public class DefaultConfigurator implements Configurator {
private Map<String, String> variables = new LinkedHashMap<String, String>();
private boolean _parseOnly = false;
/**
* Create new configurator instance with the configuration data in the given
* XML file.
*
*
* @param file
* XML config file
*/
......@@ -158,7 +161,7 @@ public class DefaultConfigurator implements Configurator {
/**
* Gets the name of the configuration file.
*
*
* @return Name of the configuration file.
*/
public File getConfigFile() {
......@@ -167,7 +170,7 @@ public class DefaultConfigurator implements Configurator {
/**
* Return a copy of the map with variables.
*
*
* @return A copy of stored variables.
*/
public Map<String, String> getVariables() {
......@@ -183,7 +186,7 @@ public class DefaultConfigurator implements Configurator {
/**
* Register a specific component module by the provided name.
*
*
* @param name
* unique name for the component module
* @param component
......@@ -199,11 +202,18 @@ public class DefaultConfigurator implements Configurator {
}
}
public Map<String, String> parseAllDefaults() throws ConfigurationException {
_parseOnly = true;
configureAll();
_parseOnly = false;
return getVariables();
}
/**
* Configure all components of the simulator. The single components are
* either registered via the <code>register(name, component)</code> method
* or specified in the config file.
*
*
* @return a collection of components.
* @throws ConfigurationException
*/
......@@ -258,7 +268,7 @@ public class DefaultConfigurator implements Configurator {
/**
* Process the XML subtree.
*
*
* @param parent
* root of the subtree
*/
......@@ -273,7 +283,7 @@ public class DefaultConfigurator implements Configurator {
} else if (elem.getName().equals(Configurator.DEFAULT_TAG)) {
configureDefaults(elem);
} else {
configureComponent(elem);
configureComponent(elem);
}
}
}
......@@ -281,7 +291,7 @@ public class DefaultConfigurator implements Configurator {
/**
* Processes a <code><Default></code> Tag by setting the respective
* variables.
*
*
* @param defaultElement
*/
private void configureDefaults(Element elem) {
......@@ -304,13 +314,12 @@ public class DefaultConfigurator implements Configurator {
/**
* Create (if not existent yet) and configure a configurable component by
* parsing the XML subtree.
*
*
* @param elem
* XML subtree with configuration data
* @return configured component
*/
public Object configureComponent(Element elem) {
String name = elem.getName();
if (Configurator.SPECIAL_IF_EQUAL_STR.equalsIgnoreCase(name)) {
processIfEqualStr(elem, new ToConfigureCallback() {
......@@ -347,47 +356,56 @@ public class DefaultConfigurator implements Configurator {
Monitor.log(DefaultConfigurator.class, Level.DEBUG,
"Configure component " + name);
/*
* FIXED (BR) - if a component specifies a class-tag, do NOT reuse the
* old component for configuration. Instead, create a new component.
*/
// Constructor Attributes
Object component = configurables.get(name);
Set<String> consAttrs = new HashSet<String>();
String clazz = getAttributeValue(elem.attribute(CLASS_TAG));
if (clazz != null) {
// Create component
component = createComponent(elem, consAttrs);
}
// configure it
if (component != null) {
Monitor.log(DefaultConfigurator.class, Level.INFO,
"Configure component "
+ component.getClass().getSimpleName()
+ " with element " + name);
configureAttributes(component, elem, consAttrs);
// configure subcomponents
if (component instanceof Builder) {
Monitor.log(DefaultConfigurator.class, Level.INFO,
"Configure builder " + component);
Builder builder = (Builder) component;
builder.parse(elem, this);
} else {
for (Iterator iter = elem.elementIterator(); iter.hasNext();) {
Element child = (Element) iter.next();
if (!consAttrs.contains(child.getName().toLowerCase())) {
processChild(component, child, consAttrs);
}
}
}
if (!_parseOnly) {
/*
* FIXED (BR) - if a component specifies a class-tag, do NOT reuse the
* old component for configuration. Instead, create a new component.
*/
// Constructor Attributes
Object component = configurables.get(name);
Set<String> consAttrs = new HashSet<String>();
String clazz = getAttributeValue(elem.attribute(CLASS_TAG));
if (clazz != null) {
// Create component
component = createComponent(elem, consAttrs);
}
// configure it
if (component != null) {
Monitor.log(DefaultConfigurator.class, Level.INFO,
"Configure component "
+ component.getClass().getSimpleName()
+ " with element " + name);
configureAttributes(component, elem, consAttrs);
// configure subcomponents
if (component instanceof Builder) {
Monitor.log(DefaultConfigurator.class, Level.INFO,
"Configure builder " + component);
Builder builder = (Builder) component;
builder.parse(elem, this);
} else {
for (Iterator iter = elem.elementIterator(); iter.hasNext();) {
Element child = (Element) iter.next();
if (!consAttrs.contains(child.getName().toLowerCase())) {
processChild(component, child, consAttrs);
}
}
}
} else {
// component cannot be created and has not been registered
if (!name.equals("Description"))
Monitor.log(DefaultConfigurator.class, Level.WARN,
"Skip element " + name);
}
return component;
} else {
// component cannot be created and has not been registered
if (!name.equals("Description"))
Monitor.log(DefaultConfigurator.class, Level.WARN,
"Skip element " + name);
for (Iterator iter = elem.elementIterator(); iter.hasNext();) {
Element child = (Element) iter.next();
processChild(null, child, null);
}
return null;
}
return component;
}
private Object createComponent(Element elem, Set<String> consAttrs) {
......@@ -414,7 +432,7 @@ public class DefaultConfigurator implements Configurator {
}
/**
*
*
* @param component
* @param child
* @param consAttrs
......@@ -456,42 +474,44 @@ public class DefaultConfigurator implements Configurator {
Object subcomponent = configureComponent(child);
String prefix = SET_METHOD_PREFIX_TAG;
String methodName = getMethodName(prefix, child.getName());
Method[] methods = component.getClass().getMethods();
Method match = null;
for (int i = 0; i < methods.length; i++) {
if (methodName.equals(methods[i].getName())) {
match = methods[i];
Monitor.log(DefaultConfigurator.class, Level.DEBUG,
"Match " + match);
break;
}
}
if (match == null) {
Monitor.log(DefaultConfigurator.class, Level.WARN,
"Cannot set " + subcomponent + " as there is no method "
+ methodName + " declared in " + component);
throw new ConfigurationException(
"Cannot set " + subcomponent + " as there is no method "
+ methodName + " declared in " + component);
} else {
Class[] types = match.getParameterTypes();
Monitor.log(DefaultConfigurator.class, Level.DEBUG,
"Param types" + Arrays.asList(types));
if (types.length == 1) {
try {
match.invoke(component, types[0].cast(subcomponent));
} catch (Exception e) {
throw new ConfigurationException(
"Failed to configure " + methodName + " in "
+ component + " with " + subcomponent,
e);
}
} else {
throw new ConfigurationException("Wrong number of params for "
+ methodName + " in " + component);
}
if (!_parseOnly) {
String prefix = SET_METHOD_PREFIX_TAG;
String methodName = getMethodName(prefix, child.getName());
Method[] methods = component.getClass().getMethods();
Method match = null;
for (int i = 0; i < methods.length; i++) {
if (methodName.equals(methods[i].getName())) {
match = methods[i];
Monitor.log(DefaultConfigurator.class, Level.DEBUG,
"Match " + match);
break;
}
}
if (match == null) {
Monitor.log(DefaultConfigurator.class, Level.WARN,
"Cannot set " + subcomponent + " as there is no method "
+ methodName + " declared in " + component);
throw new ConfigurationException(
"Cannot set " + subcomponent + " as there is no method "
+ methodName + " declared in " + component);
} else {
Class[] types = match.getParameterTypes();
Monitor.log(DefaultConfigurator.class, Level.DEBUG,
"Param types" + Arrays.asList(types));
if (types.length == 1) {
try {
match.invoke(component, types[0].cast(subcomponent));
} catch (Exception e) {
throw new ConfigurationException(
"Failed to configure " + methodName + " in "
+ component + " with " + subcomponent,
e);
}
} else {
throw new ConfigurationException("Wrong number of params for "
+ methodName + " in " + component);
}
}
}
}
......@@ -586,7 +606,7 @@ public class DefaultConfigurator implements Configurator {
/**
* Automagically convert the string value to desired type. Supported types
* are all simple types, i.e. boolean, int, long, double.
*
*
* @param value
* @param typeClass
* @return converted
......@@ -629,8 +649,9 @@ public class DefaultConfigurator implements Configurator {
}
param = lvals;
} else {
throw new IllegalArgumentException(
"Parameter type " + typeClass + " is not supported");
param = value;
// throw new IllegalArgumentException(
// "Parameter type " + typeClass + " is not supported");
}
return param;
}
......@@ -646,7 +667,7 @@ public class DefaultConfigurator implements Configurator {
/**
* Can be either a variable (if starts with $) or a plain value
*
*
* @param attr
* @return proper value
*/
......@@ -694,7 +715,7 @@ public class DefaultConfigurator implements Configurator {
/*
* (non-Javadoc)
*
*
* @see
* de.tud.kom.p2psim.impl.scenario.ConfigurablesManager#getComponent(java
* .lang.String)
......@@ -712,7 +733,7 @@ public class DefaultConfigurator implements Configurator {
* (full) class name and the optional method name. If the method name is
* null, the default constructor will be used. The method's signature should
* have no arguments.
*
*
* @param className
* @param staticMethod
* @param consAttrs
......@@ -728,6 +749,9 @@ public class DefaultConfigurator implements Configurator {
if (staticMethod == null) {
Constructor[] cs = forName.getConstructors();
Constructor currentConstructor = null;
String[] usedArgs = null;
Object[] parameters = null;
for (Constructor<?> c : cs) {
XMLConfigurableConstructor a = c
......@@ -760,7 +784,7 @@ public class DefaultConfigurator implements Configurator {
break;
}
consArgs[i] = configureComponent(elem);
if (consArgs[i].getClass()
if (!consArgs[i].getClass()
.isAssignableFrom(types[i]))
throw new ConfigurationException(
"The type of the component configured for the parameter '"
......@@ -778,16 +802,23 @@ public class DefaultConfigurator implements Configurator {
}
if (!incompatible) {
component = c.newInstance(consArgs);
for (String consAttr : cArgs) {
consAttrs.add(consAttr.toLowerCase());
}
break;
if (currentConstructor == null || parameters.length < consArgs.length) {
currentConstructor = c;
parameters = consArgs;
usedArgs = cArgs;
}
}
}
}
if (currentConstructor != null) {
component = currentConstructor.newInstance(parameters);
for (String consAttr : usedArgs) {
consAttrs.add(consAttr.toLowerCase());
}
}
if (component == null)
component = forName.newInstance();
......@@ -808,7 +839,7 @@ public class DefaultConfigurator implements Configurator {
/**
* Set variables with values which replace the variable names in the
* configuration file. Default values will be overwritten.
*
*
* @param variables
*/
public void setVariables(Map<String, String> variables) {
......@@ -824,11 +855,11 @@ public class DefaultConfigurator implements Configurator {
* number followed by a "ms", "s", "m" or "h" for milliseconds, seconds
* etc.. The conversion is done according to the constants defined in the
* {@link Time} class.
*
*
* If no time-unit is found, we search for bandwidth-units and parse
* according to the unit, and if that does not work as well, the long is
* returned.
*
*
* @param value
* - time value to parse
* @return parsed value
......@@ -837,10 +868,10 @@ public class DefaultConfigurator implements Configurator {
public static <T extends Number> T parseNumber(String value,
Class<T> targetClass) {
assert value != null;
if(value == null)
if(value == null)
System.out.println("");
String number = value;
double factor = 1;
// Time
......@@ -880,6 +911,9 @@ public class DefaultConfigurator implements Configurator {
} else {
throw new IllegalStateException("Invalid bandwidth unit.");
}
} else if (value.matches("\\d+%") || value.matches("\\d+\\.\\d+%")) {
factor = 0.01;
number = value.substring(0, value.length() - 1);
}
// Size (Byte)
if (value.matches("\\d+(B|KB|MB)")) {
......@@ -915,11 +949,11 @@ public class DefaultConfigurator implements Configurator {
/**
* You can create elements like
*
*
* &lt;IfEqualStr arg0="$variable" arg1="value"&gt; [...your configuration
* ... ] &lt;/IfEqualStr&gt;, and they will be applied only if the strings
* are equal.
*
*
* @param ifClause
* @param toExecuteOnTrue
* @return
......@@ -957,11 +991,11 @@ public class DefaultConfigurator implements Configurator {
/**
* You can create elements like
*
*
* &lt;IfNotEqualStr arg0="$variable" arg1="value"&gt; [...your
* configuration ... ] &lt;/IfNotEqualStr&gt;, and they will be applied only
* if the strings are NOT equal.
*
*
* @param ifClause
* @param toExecuteOnFalse
* @return
......@@ -1000,7 +1034,7 @@ public class DefaultConfigurator implements Configurator {
/**
* Gets the parsed XML-Configuration File. So are the included tags
* resolved.
*
*
* @param configFile
* The File of the config
* @return The parsed config as text.
......
......@@ -32,6 +32,7 @@ import de.tudarmstadt.maki.simonstrator.api.Monitor;
import de.tudarmstadt.maki.simonstrator.api.Monitor.Level;
import de.tudarmstadt.maki.simonstrator.api.Time;
import de.tudarmstadt.maki.simonstrator.api.component.core.SchedulerComponent;
import de.tudarmstadt.maki.simonstrator.api.component.core.SimulationRuntimeAnalyzer;
import de.tudarmstadt.maki.simonstrator.api.component.core.TimeComponent;
/**
......@@ -57,7 +58,7 @@ SchedulerComponent, TimeComponent {
private long statusInterval = SCHEDULER_WAKEUP_INTERVAL_IN_VIRTUALTIME;
private static final int INITIAL_QUEUE_CAPACITY = 5000;
private static final int INITIAL_QUEUE_CAPACITY = 50000;
private long processedEventCounter;
......@@ -93,6 +94,9 @@ SchedulerComponent, TimeComponent {
protected static final int TYPE_END = 3;
private SimulationRuntimeAnalyzer _simulationRuntimeAnalyzer;
private boolean _simulationRuntimeAnalyzerInit;
/**
* Constructs a new scheduler instance using a calendar queue. If desired,
* status events about the progress of the simulation will be plotted.
......@@ -267,8 +271,14 @@ SchedulerComponent, TimeComponent {
processedEventCounter++;
currentTime = realEvent.getSimulationTime();
if (hasSimulationRuntimeAnalyzer()) {
getSimulationRuntimeAnalyzer().startEventExecution(realEvent.handler, realEvent.type);
}
EventHandler handler = realEvent.handler;
handler.eventOccurred(realEvent.data, realEvent.type);
if (hasSimulationRuntimeAnalyzer()) {
getSimulationRuntimeAnalyzer().endEventExecution(realEvent.handler, realEvent.type);
}
notifyListeners(realEvent, realEvent.handler);
if (realEvent.schedulerType == TYPE_END)
......@@ -298,8 +308,15 @@ SchedulerComponent, TimeComponent {
assert (realEvent.simTime == Long.MIN_VALUE);
realEvent.simTime = currentTime;
if (hasSimulationRuntimeAnalyzer()) {
getSimulationRuntimeAnalyzer().startEventExecution(realEvent.handler, realEvent.type);
}
EventHandler handler = realEvent.handler;
handler.eventOccurred(realEvent.data, realEvent.type);
if (hasSimulationRuntimeAnalyzer()) {
getSimulationRuntimeAnalyzer().endEventExecution(realEvent.handler, realEvent.type);
}
notifyListeners(realEvent, realEvent.handler);
}
......@@ -403,8 +420,14 @@ SchedulerComponent, TimeComponent {
}
currentTime = realEvent.getSimulationTime();
if (hasSimulationRuntimeAnalyzer()) {
getSimulationRuntimeAnalyzer().startEventExecution(realEvent.handler, realEvent.type);
}
EventHandler handler = realEvent.handler;
handler.eventOccurred(realEvent.data, realEvent.type);
if (hasSimulationRuntimeAnalyzer()) {
getSimulationRuntimeAnalyzer().endEventExecution(realEvent.handler, realEvent.type);
}
notifyListeners(realEvent, realEvent.handler);
if (realEvent.schedulerType == TYPE_END) {
......@@ -612,4 +635,16 @@ SchedulerComponent, TimeComponent {
}
}
private SimulationRuntimeAnalyzer getSimulationRuntimeAnalyzer() {
return _simulationRuntimeAnalyzer;
}
private boolean hasSimulationRuntimeAnalyzer() {
if (!_simulationRuntimeAnalyzerInit) {
_simulationRuntimeAnalyzer = Monitor.getOrNull(SimulationRuntimeAnalyzer.class);
_simulationRuntimeAnalyzerInit = true;
}
return _simulationRuntimeAnalyzer != null;
}
}
......@@ -401,8 +401,7 @@ public class Simulator implements RandomGeneratorComponent, GlobalComponent {
if (randomGenerators.containsKey(source)) {
return randomGenerators.get(source);
} else {
long thisSeed = source.toString().hashCode() + 31
* seed;
long thisSeed = source.toString().hashCode() * seed + seed;
Monitor.log(Simulator.class, Level.INFO,
"Created a new Random Source for %s with seed %d", source,
thisSeed);
......@@ -487,7 +486,7 @@ public class Simulator implements RandomGeneratorComponent, GlobalComponent {
*/
@Deprecated
public void setDatabase(String database) {
DAO.database = database;
DAO.setDatabase(database);
}
/**
......
......@@ -142,13 +142,13 @@ public class RSUMovementModel implements MovementModel {
*/
protected void initializeModel() {
if (this.sumoExe != null) {
_controller = TraciSimulationController.createSimulationController(sumoExe, sumoConfigFile);
_controller.init();
_controller = TraciSimulationController.createSimulationController(sumoExe, sumoConfigFile, 1);
_controller.init(Time.SECOND);
_controller.setObservedArea(offsetX, offsetY, offsetX + width, offsetY + height);
_intersections = _controller.getAllIntersections(true);
} else {
_controller = new XMLSimulationController(null, sumoIntersections);
_controller.init();
_controller.init(Time.SECOND);
_controller.setObservedArea(offsetX, offsetY, offsetX + width, offsetY + height);
_intersections = _controller.getAllIntersections(true);
}
......
......@@ -60,6 +60,8 @@ public class VehicleMovementModel implements MovementModel, EventHandler {
private static VehicleMovementModel MOVEMENT;
public static final int TIMESTEP_RATIO = 1;
private long timeBetweenMoveOperations;
private final List<SimLocationActuator> components;
......@@ -75,16 +77,11 @@ public class VehicleMovementModel implements MovementModel, EventHandler {
private final int width;
private final int height;
private double scenarioWidth = 0;
private double scenarioHeight = 0;
private final String sumoExe;
private final String sumoConfigFile;
private final String sumoTrace;
private String sumoIntersections;
private final long timestepConversion = Time.SECOND;
private boolean initialized = false;
private VehicleController _controller;
......@@ -92,6 +89,8 @@ public class VehicleMovementModel implements MovementModel, EventHandler {
private double _percentageOfKnownRoutes = 1;
private int _startTime;
/**
* Constructor for the movement model using the sumo TraCI API
* @param timeBetweenMoveOperations The time between two movement operations.
......@@ -117,6 +116,27 @@ public class VehicleMovementModel implements MovementModel, EventHandler {
this.offsetY = Integer.parseInt(offsetY);
this.width = Integer.parseInt(width);
this.height = Integer.parseInt(height);
Thread current = Thread.currentThread();
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
StackTraceElement[] stackTrace = current.getStackTrace();
System.out.println();
System.out.println();
for (int i = 0; i < stackTrace.length; i++) {
System.out.println(stackTrace[i]);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
}
});
// thread.start();
}
/**
......@@ -154,6 +174,10 @@ public class VehicleMovementModel implements MovementModel, EventHandler {
_percentageOfKnownRoutes = pPercentageOfKnownRoutes;
}
public void setStartTime(long pStartTime) {
_startTime = (int) (pStartTime / timeBetweenMoveOperations);
}
public void setReuseComponents(boolean pReuseComponents) {
_reuseComponents = pReuseComponents;
......@@ -215,14 +239,15 @@ public class VehicleMovementModel implements MovementModel, EventHandler {
protected void initializeModel() {
// Schedule first step
if (!initialized) {
Event.scheduleWithDelay(timeBetweenMoveOperations, this, null, 0);
Event.scheduleWithDelay(timeBetweenMoveOperations * TIMESTEP_RATIO, this, null, 0);
if (sumoExe != null) {
TraciSimulationController simulationController = TraciSimulationController.createSimulationController(sumoExe, sumoConfigFile);
TraciSimulationController simulationController = TraciSimulationController.createSimulationController(sumoExe, sumoConfigFile, TIMESTEP_RATIO);
_controller = simulationController;
_controller.setObservedArea(offsetX, offsetY, offsetX + width, offsetY + height);
_controller.init();
_controller.nextStep();
simulationController.setStartTime(_startTime);
_controller.init(timeBetweenMoveOperations);
_controller.nextStep(timeBetweenMoveOperations);
_extractor = simulationController;
} else {
......@@ -235,15 +260,12 @@ public class VehicleMovementModel implements MovementModel, EventHandler {
_controller = simulationController;
_controller.setObservedArea(offsetX, offsetY, offsetX + width, offsetY + height);
_controller.init();
_controller.nextStep();
_controller.init(timeBetweenMoveOperations);
_controller.nextStep(timeBetweenMoveOperations);
_extractor = simulationController;
}
scenarioWidth = _extractor.getScenarioWidth();
scenarioHeight = _extractor.getScenarioHeight();
System.out.println("Initialization: done.");
}
}
......@@ -260,10 +282,12 @@ public class VehicleMovementModel implements MovementModel, EventHandler {
* simulation performance due to less recalculations in the network
* models.
*/
long currentTime = Time.getCurrentTime() / timestepConversion;
long currentTime = Time.getCurrentTime() / timeBetweenMoveOperations;
System.out.println("Performing movement for step " + currentTime);
while (_controller.getStep() - _controller.getStart() < currentTime) {
if (!_controller.nextStep()) {
if (!_controller.nextStep(timeBetweenMoveOperations)) {
return;
}
}
......@@ -316,7 +340,7 @@ public class VehicleMovementModel implements MovementModel, EventHandler {
}
// Reschedule next step
Event.scheduleWithDelay(timeBetweenMoveOperations, this, null, 0);
Event.scheduleWithDelay(timeBetweenMoveOperations * TIMESTEP_RATIO, this, null, 0);
}
/**
......@@ -385,7 +409,9 @@ public class VehicleMovementModel implements MovementModel, EventHandler {
idComponentMatcher.put(vehicle, simLocationActuator);
hostVehicleIDMatching.put(simLocationActuator.getHost().getId(), vehicle);
} else {
throw new RuntimeException("Unable to assign new components. Please increase node amount" + (_reuseComponents?".":" or enable the reuse of components."));
if (idComponentMatcher.size() != 0) {
throw new RuntimeException("Unable to assign new components. Please increase node amount" + (_reuseComponents?".":" or enable the reuse of components."));
}
}
}
return idComponentMatcher.get(vehicle);
......
......@@ -52,4 +52,8 @@ public class VehicleInformationContainer {
public RoadNetworkRoute getRoute() {
return _route;
}
public void setRoute(RoadNetworkRoute pRoute) {
_route = pRoute;
}
}
\ No newline at end of file
......@@ -12,6 +12,7 @@ import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import de.tud.kom.p2psim.api.simengine.SimulatorObserver;
......@@ -19,6 +20,7 @@ import de.tud.kom.p2psim.impl.simengine.Simulator;
import de.tud.kom.p2psim.impl.topology.movement.vehicular.sumo.simulation.controller.VehicleInformationContainer;
import de.tud.kom.p2psim.impl.topology.util.PositionVector;
import de.tudarmstadt.maki.simonstrator.api.Randoms;
import de.tudarmstadt.maki.simonstrator.api.Time;
import de.tudarmstadt.maki.simonstrator.api.component.sensor.location.Location;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.api.EdgeController;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.api.SimulationSetupExtractor;
......@@ -31,6 +33,8 @@ import de.tudarmstadt.maki.simonstrator.api.component.vehicular.roadnetwork.Road
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.roadnetwork.SerializableRoadNetwork;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.roadnetwork.exception.NoAdditionalRouteAvailableException;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.roadnetwork.exception.NoExitAvailableException;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.roadnetwork.paths.VehiclePathTracker;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.roadnetwork.paths.VehiclePathTrackerFactory;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.roadnetwork.routing.DijkstraAlgorithm;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.roadnetwork.routing.RoutingAlgorithm;
import de.tudresden.sumo.cmd.Edge;
......@@ -54,7 +58,9 @@ import it.polito.appeal.traci.SumoTraciConnection;
*
*/
public class TraciSimulationController implements VehicleController, SimulationSetupExtractor, EdgeController, SimulatorObserver {
private static final File TEMP_FILE = new File(new File(System.getProperty("java.io.tmpdir")), "road_network.tmp");
private static final File TEMP_FILE = new File(new File(System.getProperty("user.home") + "/.simonstrator"), "road_network.tmp");
private static final boolean TRAIN_PATH_PROBABILITIES = false;
private Random _random = Randoms.getRandom(getClass());
......@@ -75,6 +81,8 @@ public class TraciSimulationController implements VehicleController, SimulationS
private double _endX;
private double _endY;
private int _startTime = 0;
private Map<String, VehicleInformationContainer> _positons = new HashMap<>();
private boolean _initalized = false;
......@@ -87,16 +95,23 @@ public class TraciSimulationController implements VehicleController, SimulationS
private RoutingAlgorithm _algorithm = new DijkstraAlgorithm();
public static synchronized TraciSimulationController createSimulationController(String pSumoExe, String pConfigFile) {
private int _timestepRatio;
public static synchronized TraciSimulationController createSimulationController(String pSumoExe, String pConfigFile, int pTimestepRatio) {
if (!CONTROLLER.containsKey(pConfigFile)) {
CONTROLLER.put(pConfigFile, new TraciSimulationController(pSumoExe, pConfigFile));
CONTROLLER.put(pConfigFile, new TraciSimulationController(pSumoExe, pConfigFile, pTimestepRatio));
}
return CONTROLLER.get(pConfigFile);
}
private TraciSimulationController(String pSumoExe, String pConfigFile) {
private TraciSimulationController(String pSumoExe, String pConfigFile, int pTimestepRatio) {
_sumoExe = pSumoExe;
_configFile = pConfigFile;
_timestepRatio = pTimestepRatio;
}
public void setStartTime(int pStartTime) {
_startTime = pStartTime;
}
public static VehicleController getSimulationController() {
......@@ -104,7 +119,7 @@ public class TraciSimulationController implements VehicleController, SimulationS
}
@Override
public synchronized void init() {
public synchronized void init(long pTimeScale) {
if (!_initalized) {
Random random = Randoms.getRandom("SUMO");
......@@ -115,6 +130,7 @@ public class TraciSimulationController implements VehicleController, SimulationS
* prevent vehicles form teleporting (http://sumo.dlr.de/wiki/Simulation/Why_Vehicles_are_teleporting)
*/
_connection.addOption("time-to-teleport", Integer.toString(-1));
_connection.addOption("step-length", String.valueOf(pTimeScale / (double)Time.SECOND));
try {
_connection.runServer();
......@@ -127,6 +143,26 @@ public class TraciSimulationController implements VehicleController, SimulationS
Simulator.getInstance().addObserver(this);
_initalized = true;
for (int i = 0; i < _startTime; i++) {
System.out.println("Pre-Start Setup: " + i + " of " + _startTime + " steps done.");
if (TRAIN_PATH_PROBABILITIES) {
Map<String, VehicleInformationContainer> positions = nextStep();
for (Entry<String, VehicleInformationContainer> entry : positions.entrySet()) {
VehiclePathTrackerFactory.getVehiclePathTracker().setEdge(entry.getKey(), entry.getValue().getRoute().getStart(), i * pTimeScale);
}
} else {
try {
_connection.do_timestep();
} catch (Exception e) {
throw new AssertionError(e);
}
}
}
if (TRAIN_PATH_PROBABILITIES) {
VehiclePathTrackerFactory.getVehiclePathTracker().disableTracking();
}
}
}
......@@ -146,6 +182,13 @@ public class TraciSimulationController implements VehicleController, SimulationS
return _positons.get(pVehicleID).getPosition();
}
@Override
public double getVehicleLength(String pVehicleID) {
SumoCommand lengthCommand = Vehicle.getLength(pVehicleID);
Object requestObject = requestObject(lengthCommand);
return (Double) requestObject;
}
@Override
public double getVehicleHeading(String pVehicleID) {
return _positons.get(pVehicleID).getHeading();
......@@ -176,10 +219,10 @@ public class TraciSimulationController implements VehicleController, SimulationS
if (_observedAreaSet) {
if (_startX <= sumoPosition.x && sumoPosition.x <= _endX && _startY <= sumoPosition.y && sumoPosition.y <= _endY) {
result.add(new PositionVector(sumoPosition.x - _startX, sumoPosition.y - _startY, 0));
result.add(new PositionVector(sumoPosition.x - _startX, sumoPosition.y - _startY));
}
} else {
result.add(new PositionVector(sumoPosition.x, sumoPosition.y, 0));
result.add(new PositionVector(sumoPosition.x, sumoPosition.y));
}
}
......@@ -205,54 +248,63 @@ public class TraciSimulationController implements VehicleController, SimulationS
return result;
}
@Override
public boolean nextStep() {
if (Simulator.getEndTime() == Simulator.getCurrentTime()) {
return false;
}
try {
_connection.do_timestep();
private Map<String, VehicleInformationContainer> nextStep() {
try {
for (int i = 0; i < _timestepRatio; i++) {
_connection.do_timestep();
}
try {
synchronized (_positons) {
_positons.clear();
try {
Map<String, VehicleInformationContainer> vehiclePositions = new HashMap<>();
int temp = (Integer) _connection.do_job_get(Simulation.getCurrentTime());
List<String> allVehicles = requestAllVehicles();
for (String vehicle : allVehicles) {
Location position = requestVehiclePosition(vehicle);
if (position != null) {
double heading = requestVehicleHeading(vehicle);
double speed = requestVehicleSpeed(vehicle);
RoadNetworkRoute route = requestVehicleRoute(vehicle);
_step = temp / 1000.0;
VehicleInformationContainer informationContainer = new VehicleInformationContainer(position, heading, speed, route);
if (_start == -1) {
_start = _step;
}
vehiclePositions.put(vehicle, informationContainer);
}
}
return vehiclePositions;
} catch (Exception e) {
throw new AssertionError(e);
}
} catch (Exception e) {
throw new AssertionError(e);
}
}
Map<String, VehicleInformationContainer> vehiclePositions = new HashMap<>();
@Override
public boolean nextStep(long pTimeScale) {
if (Simulator.getEndTime() == Simulator.getCurrentTime()) {
return false;
}
Map<String, VehicleInformationContainer> vehiclePositions = nextStep();
List<String> allVehicles = requestAllVehicles();
for (String vehicle : allVehicles) {
Location position = requestVehiclePosition(vehicle);
if (position != null) {
double heading = requestVehicleHeading(vehicle);
double speed = requestVehicleSpeed(vehicle);
RoadNetworkRoute route = requestVehicleRoute(vehicle);
try {
int temp = (Integer) _connection.do_job_get(Simulation.getCurrentTime());
VehicleInformationContainer informationContainer = new VehicleInformationContainer(position, heading, speed, route);
_step = temp / (pTimeScale / (double)Time.MILLISECOND);
vehiclePositions.put(vehicle, informationContainer);
}
}
_positons = vehiclePositions;
}
} catch (Exception e) {
e.printStackTrace();
}
if (_start == -1) {
_start = _step;
}
} catch (Exception e) {
throw new AssertionError(e);
}
return true;
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
e.printStackTrace();
if (vehiclePositions != null) {
_positons = vehiclePositions;
return true;
} else {
_positons.clear();
return false;
}
return false;
}
private Location requestVehiclePosition(String pVehicleID) {
......@@ -272,7 +324,7 @@ public class TraciSimulationController implements VehicleController, SimulationS
if (_observedAreaSet) {
if (_startX <= sumoPosition.x && sumoPosition.x <= _endX && _startY <= sumoPosition.y && sumoPosition.y <= _endY) {
return new PositionVector(sumoPosition.x - _startX, sumoPosition.y - _startY, 0);
return new PositionVector(sumoPosition.x - _startX, sumoPosition.y - _startY);
} else {
double diffX = _startX - sumoPosition.x;
if (diffX < 0 || sumoPosition.x - _endX < diffX) {
......@@ -297,7 +349,7 @@ public class TraciSimulationController implements VehicleController, SimulationS
return null;
}
} else {
return new PositionVector(sumoPosition.x, sumoPosition.y, 0);
return new PositionVector(sumoPosition.x, sumoPosition.y);
}
}
......@@ -314,7 +366,6 @@ public class TraciSimulationController implements VehicleController, SimulationS
Object angleObject = requestObject(angleCommand);
if (angleObject != null) {
return (Double) angleObject;
}
......@@ -408,7 +459,11 @@ public class TraciSimulationController implements VehicleController, SimulationS
add = true;
}
if (add) {
streets.add(_roadNetwork.getEdge(street));
RoadNetworkEdge edge = _roadNetwork.getEdge(street);
streets.add(edge);
if (!edge.isUsable()) {
break;
}
}
}
......@@ -484,8 +539,12 @@ public class TraciSimulationController implements VehicleController, SimulationS
SumoCommand netBoundaryCommand = Simulation.getNetBoundary();
try {
SumoBoundingBox netBoundary = (SumoBoundingBox) _connection.do_job_get(netBoundaryCommand);
return Math.max(netBoundary.x_max - netBoundary.x_min, 10);
SumoBoundingBox netBoundary = (SumoBoundingBox) _connection.do_job_get(netBoundaryCommand);
if (_observedAreaSet) {
return Math.max(Math.min(netBoundary.x_max, _endX) - Math.max(netBoundary.x_min, _startX), 10);
} else {
return Math.max(netBoundary.x_max - netBoundary.x_min, 10);
}
} catch (Exception e) {
//Nothing to do
}
......@@ -498,7 +557,11 @@ public class TraciSimulationController implements VehicleController, SimulationS
try {
SumoBoundingBox netBoundary = (SumoBoundingBox) _connection.do_job_get(netBoundaryCommand);
return Math.max(netBoundary.y_max - netBoundary.y_min, 10);
if (_observedAreaSet) {
return Math.max(Math.min(netBoundary.y_max, _endY) - Math.max(netBoundary.y_min, _startY), 10);
} else {
return Math.max(netBoundary.y_max - netBoundary.y_min, 10);
}
} catch (Exception e) {
//Nothing to do
}
......@@ -610,6 +673,7 @@ public class TraciSimulationController implements VehicleController, SimulationS
routeEdges.add(edge.getEdgeID());
}
execute(Vehicle.setRoute(pVehicle, routeEdges));
_positons.get(pVehicle).setRoute(pRoute);
}
@Override
......@@ -707,12 +771,14 @@ public class TraciSimulationController implements VehicleController, SimulationS
_roadNetwork = new RoadNetwork(roadNetwork, this, true);
try {
ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(TEMP_FILE));
if (TEMP_FILE.getParentFile().exists() || TEMP_FILE.getParentFile().mkdirs()) {
ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(TEMP_FILE));
outputStream.writeObject(new SerializableRoadNetwork(_roadNetwork));
outputStream.writeObject(new SerializableRoadNetwork(_roadNetwork));
outputStream.flush();
outputStream.close();
outputStream.flush();
outputStream.close();
}
} catch (IOException e) {
//Nothing to do
e.printStackTrace();
......@@ -749,19 +815,19 @@ public class TraciSimulationController implements VehicleController, SimulationS
public List<Location> getLaneShape(String pLaneID) {
List<Location> positions = new ArrayList<>();
boolean set = true;
boolean set = false;
SumoCommand laneShapeCommand = Lane.getShape(pLaneID);
SumoGeometry geometry = (SumoGeometry)requestObject(laneShapeCommand);
for (SumoPosition2D location : geometry.coords) {
if (!isObservedAreaSet()) {
positions.add(new PositionVector(location.x, location.y));
set = true;
} else {
if (_startX <= location.x && location.x <= _endX && _startY <= location.y && location.y <= _endY) {
positions.add(new PositionVector(location.x - _startX, location.y - _startY));
} else {
set = true;
}
positions.add(new PositionVector(location.x - _startX, location.y - _startY));
}
}
......@@ -830,8 +896,11 @@ public class TraciSimulationController implements VehicleController, SimulationS
length += (double) object;
}
return length / (_roadNetwork.getEdge(pEdgeID).getLaneAmount());
if ((_roadNetwork.getEdge(pEdgeID).getLaneAmount()) != 0) {
return length / (_roadNetwork.getEdge(pEdgeID).getLaneAmount());
} else {
return 0.0;
}
}
@Override
......@@ -839,10 +908,12 @@ public class TraciSimulationController implements VehicleController, SimulationS
if (_observedAreaSet) {
List<RoadNetworkLane> lanes = _roadNetwork.getEdge(pEdgeID).getLanes();
if (lanes.size() > 0) {
List<Location> laneShape = getLaneShape(lanes.get(0).getLaneID());
if (laneShape.size() > 1) {
return true;
}
for (RoadNetworkLane lane : lanes) {
List<Location> laneShape = getLaneShape(lane.getLaneID());
if (laneShape.size() > 1) {
return true;
}
}
}
return false;
}
......
......@@ -12,6 +12,7 @@ import javax.xml.parsers.SAXParserFactory;
import de.tud.kom.p2psim.impl.topology.movement.vehicular.sumo.simulation.controller.VehicleInformationContainer;
import de.tud.kom.p2psim.impl.topology.movement.vehicular.sumo.simulation.controller.csv.RoadSideUnitInformationHandler;
import de.tudarmstadt.maki.simonstrator.api.Time;
import de.tudarmstadt.maki.simonstrator.api.component.sensor.location.Location;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.api.SimulationSetupExtractor;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.api.VehicleController;
......@@ -49,7 +50,7 @@ public class XMLSimulationController implements VehicleController, SimulationSet
}
@Override
public void init() {
public void init(long timeBetweenMoveOperations) {
if (!_initalized) {
if (_vehicleDataPath != null) {
......@@ -57,7 +58,7 @@ public class XMLSimulationController implements VehicleController, SimulationSet
thread.start();
for (int i = 0; i < _futureInformation; i++) {
nextStep();
nextStep(Time.SECOND);
}
}
if (_roadSideUnitDataPath != null) {
......@@ -77,7 +78,7 @@ public class XMLSimulationController implements VehicleController, SimulationSet
}
@Override
public boolean nextStep() {
public boolean nextStep(long pTimeScale) {
_vehicleDataInformationHandler.readNext();
_step = _vehicleDataInformationHandler.getStep() - _futureInformation;
......@@ -171,6 +172,11 @@ public class XMLSimulationController implements VehicleController, SimulationSet
return -1;
}
@Override
public double getVehicleLength(String pVehicleID) {
throw new UnsupportedOperationException("This method is not supported for " + getClass().getSimpleName());
}
@Override
public RoadNetworkRoute getCurrentRoute(String pVehicleID) {
throw new UnsupportedOperationException("This method is not supported for " + getClass().getSimpleName());
......
......@@ -27,6 +27,7 @@ import de.tud.kom.p2psim.api.topology.placement.PlacementModel;
import de.tud.kom.p2psim.impl.topology.movement.vehicular.sumo.simulation.controller.traci.TraciSimulationController;
import de.tud.kom.p2psim.impl.topology.movement.vehicular.sumo.simulation.controller.xml.XMLSimulationController;
import de.tud.kom.p2psim.impl.topology.util.PositionVector;
import de.tudarmstadt.maki.simonstrator.api.Time;
import de.tudarmstadt.maki.simonstrator.api.component.sensor.location.Location;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.api.SimulationSetupExtractor;
import de.tudarmstadt.maki.simonstrator.api.util.XMLConfigurableConstructor;
......@@ -86,13 +87,13 @@ public class RSUPlacement implements PlacementModel {
*/
protected void initializeModel() {
if (this.sumoExe != null) {
_controller = TraciSimulationController.createSimulationController(sumoExe, sumoConfigFile);
_controller.init();
_controller = TraciSimulationController.createSimulationController(sumoExe, sumoConfigFile, 1);
_controller.init(Time.SECOND);
_controller.setObservedArea(offsetX, offsetY, offsetX + width, offsetY + height);
_intersections = _controller.getAllIntersections(true);
} else {
_controller = new XMLSimulationController(null, sumoIntersections);
_controller.init();
_controller.init(Time.SECOND);
_controller.setObservedArea(offsetX, offsetY, offsetX + width, offsetY + height);
_intersections = _controller.getAllIntersections(true);
}
......
......@@ -22,11 +22,23 @@ package de.tud.kom.p2psim.impl.util.db.dao;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.apache.commons.math3.analysis.function.Exp;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Restrictions;
import org.hibernate.service.ServiceRegistry;
import de.tud.kom.p2psim.impl.util.db.metric.CustomMeasurement;
import de.tud.kom.p2psim.impl.util.db.metric.Experiment;
......@@ -45,6 +57,7 @@ import de.tud.kom.p2psim.impl.util.db.metric.Metric;
import de.tud.kom.p2psim.impl.util.db.metric.MetricDescription;
import de.tudarmstadt.maki.simonstrator.api.Monitor;
import de.tudarmstadt.maki.simonstrator.api.Monitor.Level;
import de.tudarmstadt.maki.simonstrator.api.web.WebConfigurationManager;
/**
* This class represents a simple access to persist objects with Hibernate. It
......@@ -91,27 +104,27 @@ public class DAO {
// public static Map<String, Object> configOverwrites = new HashMap<String, Object>();
private static ArrayList<Class<?>> daoClasses = new ArrayList<Class<?>>();
public static String address = "localhost";
public static String port = "3306";
public static String database;
public static String username;
public static String password;
public static String password;
private static SessionFactory sessionFactory;
private static final ThreadLocal<Session> session = new ThreadLocal<Session>();
private static ServiceRegistry serviceRegistry;
/**
* Hibernate-only implementation to support annotated classes without active
* binding
*
*
* @return
*/
public static Session getSession() {
......@@ -129,17 +142,17 @@ public class DAO {
cfg.setProperty("hibernate.connection.url", "jdbc:mysql://"+ address + ":" + port + "/" + database);
cfg.setProperty("hibernate.connection.username", username);
cfg.setProperty("hibernate.connection.password", password);
// mySQL 5
cfg.setProperty("hibernate.dialect",
"org.hibernate.dialect.MySQL5InnoDBDialect");
cfg.setProperty("hibernate.transaction.factory_class",
"org.hibernate.transaction.JDBCTransactionFactory");
cfg.setProperty("hibernate.pool_size", "1");
cfg.setProperty("hibernate.hbm2ddl.auto", "update");
cfg.setProperty("hibernate.current_session_context_class", "thread");
// Add core classes
cfg.addAnnotatedClass(CustomMeasurement.class);
cfg.addAnnotatedClass(Experiment.class);
......@@ -156,7 +169,7 @@ public class DAO {
cfg.addAnnotatedClass(MeasurementStatisticMsgType.class);
cfg.addAnnotatedClass(Metric.class);
cfg.addAnnotatedClass(MetricDescription.class);
for (Class<?> clazz : daoClasses) {
cfg.addAnnotatedClass(clazz);
}
......@@ -175,6 +188,30 @@ public class DAO {
return currSession;
}
public static void setDatabase(String pDatabase) {
if (!WebConfigurationManager.isActive()) {
database = pDatabase;
} else {
database = WebConfigurationManager.getConfig().getOptions().getDatabase().getDatabase();
}
}
public static void setUsername(String pUsername) {
if (!WebConfigurationManager.isActive()) {
username = pUsername;
} else {
username = WebConfigurationManager.getConfig().getOptions().getDatabase().getUsername();
}
}
public static void setPassword(String pPassword) {
if (!WebConfigurationManager.isActive()) {
password = pPassword;
} else {
password = WebConfigurationManager.getConfig().getOptions().getDatabase().getPassword();
}
}
/**
* Gets the session
*
......@@ -282,6 +319,15 @@ public class DAO {
DAO.session.remove();
}
public static <T extends Object> List<T> retrieve(Class<T> pClass) {
begin();
Criteria criteria = getSession().createCriteria(pClass);
List<T> objects = criteria.list();
commit();
return objects;
}
/**
* Persist the given POJO directly to the DB. Should be make, if it exists
* relationships between tables.
......@@ -397,7 +443,7 @@ public class DAO {
*
* @param o
* The same object, which is already used to persist.
*
*
* @return The object attached to the persistence context
*/
public static <T> T update(T o) {
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment